@lunora/shard-engine 1.0.0-alpha.54 → 1.0.0-alpha.55
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.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +14 -5
- package/dist/index.d.ts +14 -5
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-sWDxFnHX.mjs → CDC_LOG_TABLE-DELonHMe.mjs} +3 -3
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-DlyTtTEl.mjs +8 -0
- package/dist/packem_shared/{DurableStreamRunner-Du20UUg5.mjs → DurableStreamRunner-prbsN-c8.mjs} +1 -1
- package/dist/packem_shared/{NotUniqueError-B9TFf3sO.mjs → NotUniqueError-jtPeUPmD.mjs} +1 -1
- package/dist/packem_shared/appendStreamChunk-C1Ok4b6J.mjs +19 -0
- package/dist/packem_shared/{buildShapeDiff-HJ9dLr5f.mjs → buildShapeDiff-BNRhEpVK.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-C89kRMX9.mjs → createReplicaLink-B4cdZv8z.mjs} +1 -1
- package/dist/packem_shared/defineEngineContractSuite-Dtb4oupe.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-C6-82CUa.mjs → isSoftDeleted-q1fob5XF.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-Dh2BViyA.mjs → materializeExternalRows-Dk3HhwxL.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-y2s6phJT.mjs → runShardMigrations-56dKx7Jq.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-32PiFmOR.mjs +0 -1
- package/dist/packem_shared/appendStreamChunk-8eH4HB1Q.mjs +0 -19
- package/dist/packem_shared/defineEngineContractSuite-DqeKwl1d.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Dtb4oupe.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -902,6 +902,7 @@ interface RpcRequest {
|
|
|
902
902
|
}
|
|
903
903
|
interface SocketAttachment {
|
|
904
904
|
admin?: boolean;
|
|
905
|
+
adminBinding?: string;
|
|
905
906
|
clientId?: string;
|
|
906
907
|
connected?: boolean;
|
|
907
908
|
connectionId?: string;
|
|
@@ -2025,6 +2026,10 @@ interface RelayHost {
|
|
|
2025
2026
|
shardBinding: () => string | undefined;
|
|
2026
2027
|
sql: () => SqlExec;
|
|
2027
2028
|
}
|
|
2029
|
+
interface RelayPokeDelivery {
|
|
2030
|
+
delivered: number;
|
|
2031
|
+
matched: number;
|
|
2032
|
+
}
|
|
2028
2033
|
declare abstract class RelayLink {
|
|
2029
2034
|
protected readonly host: RelayHost;
|
|
2030
2035
|
protected readonly roleId: {
|
|
@@ -2059,7 +2064,7 @@ declare abstract class RelayLink {
|
|
|
2059
2064
|
protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
|
|
2060
2065
|
protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
|
|
2061
2066
|
protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
|
|
2062
|
-
protected abstract onShapePoke(poke: RelayShapePoke):
|
|
2067
|
+
protected abstract onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
|
|
2063
2068
|
}
|
|
2064
2069
|
declare class OwnerRelay extends RelayLink {
|
|
2065
2070
|
private readonly shapeUniformCache;
|
|
@@ -2085,7 +2090,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2085
2090
|
protected onDetach(index: number): void;
|
|
2086
2091
|
protected onWhisperFrame(message: RelayFrame): Promise<void>;
|
|
2087
2092
|
protected onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
|
|
2088
|
-
protected onShapePoke():
|
|
2093
|
+
protected onShapePoke(): RelayPokeDelivery;
|
|
2089
2094
|
private buildShapePoke;
|
|
2090
2095
|
private multicastShapePokes;
|
|
2091
2096
|
private multicastToRelays;
|
|
@@ -2104,7 +2109,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2104
2109
|
}
|
|
2105
2110
|
declare class RelayMember extends RelayLink {
|
|
2106
2111
|
private relayAnnounced;
|
|
2107
|
-
private
|
|
2112
|
+
private relayMemoCache;
|
|
2108
2113
|
private readonly shapeControl;
|
|
2109
2114
|
constructor(host: RelayHost, ownerKey: string, relayIndex: number);
|
|
2110
2115
|
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
@@ -2124,10 +2129,14 @@ declare class RelayMember extends RelayLink {
|
|
|
2124
2129
|
protected onWhisperFrame(): Promise<void>;
|
|
2125
2130
|
protected onShapeSubscribe(): RelayShapeSeed;
|
|
2126
2131
|
protected onShapeUnsubscribe(): void;
|
|
2127
|
-
protected onShapePoke(poke: RelayShapePoke):
|
|
2132
|
+
protected onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
|
|
2128
2133
|
private queueShapeControl;
|
|
2134
|
+
private relayMemos;
|
|
2135
|
+
private connectionMemos;
|
|
2129
2136
|
private recordRelayShapeMemo;
|
|
2137
|
+
private forgetRelayShapeMemos;
|
|
2130
2138
|
private deliverShapePoke;
|
|
2139
|
+
private pokeSocketShapes;
|
|
2131
2140
|
}
|
|
2132
2141
|
declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
|
|
2133
2142
|
declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
|
|
@@ -2343,4 +2352,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2343
2352
|
}
|
|
2344
2353
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2345
2354
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2346
|
-
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 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, 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 };
|
|
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, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -902,6 +902,7 @@ interface RpcRequest {
|
|
|
902
902
|
}
|
|
903
903
|
interface SocketAttachment {
|
|
904
904
|
admin?: boolean;
|
|
905
|
+
adminBinding?: string;
|
|
905
906
|
clientId?: string;
|
|
906
907
|
connected?: boolean;
|
|
907
908
|
connectionId?: string;
|
|
@@ -2025,6 +2026,10 @@ interface RelayHost {
|
|
|
2025
2026
|
shardBinding: () => string | undefined;
|
|
2026
2027
|
sql: () => SqlExec;
|
|
2027
2028
|
}
|
|
2029
|
+
interface RelayPokeDelivery {
|
|
2030
|
+
delivered: number;
|
|
2031
|
+
matched: number;
|
|
2032
|
+
}
|
|
2028
2033
|
declare abstract class RelayLink {
|
|
2029
2034
|
protected readonly host: RelayHost;
|
|
2030
2035
|
protected readonly roleId: {
|
|
@@ -2059,7 +2064,7 @@ declare abstract class RelayLink {
|
|
|
2059
2064
|
protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
|
|
2060
2065
|
protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
|
|
2061
2066
|
protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
|
|
2062
|
-
protected abstract onShapePoke(poke: RelayShapePoke):
|
|
2067
|
+
protected abstract onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
|
|
2063
2068
|
}
|
|
2064
2069
|
declare class OwnerRelay extends RelayLink {
|
|
2065
2070
|
private readonly shapeUniformCache;
|
|
@@ -2085,7 +2090,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2085
2090
|
protected onDetach(index: number): void;
|
|
2086
2091
|
protected onWhisperFrame(message: RelayFrame): Promise<void>;
|
|
2087
2092
|
protected onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
|
|
2088
|
-
protected onShapePoke():
|
|
2093
|
+
protected onShapePoke(): RelayPokeDelivery;
|
|
2089
2094
|
private buildShapePoke;
|
|
2090
2095
|
private multicastShapePokes;
|
|
2091
2096
|
private multicastToRelays;
|
|
@@ -2104,7 +2109,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2104
2109
|
}
|
|
2105
2110
|
declare class RelayMember extends RelayLink {
|
|
2106
2111
|
private relayAnnounced;
|
|
2107
|
-
private
|
|
2112
|
+
private relayMemoCache;
|
|
2108
2113
|
private readonly shapeControl;
|
|
2109
2114
|
constructor(host: RelayHost, ownerKey: string, relayIndex: number);
|
|
2110
2115
|
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
@@ -2124,10 +2129,14 @@ declare class RelayMember extends RelayLink {
|
|
|
2124
2129
|
protected onWhisperFrame(): Promise<void>;
|
|
2125
2130
|
protected onShapeSubscribe(): RelayShapeSeed;
|
|
2126
2131
|
protected onShapeUnsubscribe(): void;
|
|
2127
|
-
protected onShapePoke(poke: RelayShapePoke):
|
|
2132
|
+
protected onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
|
|
2128
2133
|
private queueShapeControl;
|
|
2134
|
+
private relayMemos;
|
|
2135
|
+
private connectionMemos;
|
|
2129
2136
|
private recordRelayShapeMemo;
|
|
2137
|
+
private forgetRelayShapeMemos;
|
|
2130
2138
|
private deliverShapePoke;
|
|
2139
|
+
private pokeSocketShapes;
|
|
2131
2140
|
}
|
|
2132
2141
|
declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
|
|
2133
2142
|
declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
|
|
@@ -2343,4 +2352,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2343
2352
|
}
|
|
2344
2353
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2345
2354
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2346
|
-
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 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, 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 };
|
|
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, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as p,normalizeCountArgument as d,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as T,readAggregateValue as C}from"./packem_shared/aggregateTableName-qWuEmkPn.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-B9TFf3sO.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-T3lmKtDf.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-sWDxFnHX.mjs";import{archiveCdcSegment as de,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Te,migrateClientWatermark as Ce,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-CPMFTDV1.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-BSxeZLfg.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 pr}from"./packem_shared/selectShapeMembers-g5Fqi2XK.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CO1FLIVO.mjs";import{SCAN_DEP as xr,createDependencyTracker as Tr,depKey as Cr,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-By2TU17Q.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-8eH4HB1Q.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-Du20UUg5.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 To,runExternalSourceTick as Co}from"./packem_shared/materializeExternalRows-Dh2BViyA.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-C6-82CUa.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-PfT6efQf.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 pa,readBookmark as da}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ta,encodeCursor as Ca,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as ga}from"./packem_shared/CURSOR_PREFIX-BoaSx8bs.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,rankTableName as Fa,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-CWCVFaq_.mjs";import{ReactiveCache as qa,reactiveCacheKey as wa}from"./packem_shared/ReactiveCache-DpfLbuFX.mjs";import{REACTOR_STATE_TABLE as va,listReactorStates as Wa,migrateReactorState as Xa,reactorNeedsRun as Ha,readReactorState as za,writeReactorState as Va}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Ya,createReadFootprint as ja,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as st,resolveRelationPredicates as lt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Zf2Yn4YT.mjs";import{applyOnDelete as ct,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-CYV38T1y.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as xt,clampPromotionThresholds as Tt,nextPromotionState as Ct,relayCountFor as Et,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BewDXVhw.mjs";import{DEFAULT_MAX_RELAYS as At,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-32PiFmOR.mjs";import{createReplicaLink as Pt,gateReplicaDispatch as Mt,handleReplicaControl as Dt}from"./packem_shared/createReplicaLink-C89kRMX9.mjs";import{buildReprojectionMigration as yt,countLegacyRows as Ot,reprojectableFields as kt,reprojectionTables as Ft}from"./packem_shared/buildReprojectionMigration-HbwBP2Xx.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as qt}from"./packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Kt,readSchemaHistory as vt,readSchemaVersion as Wt,recordSchemaVersion as Xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as zt}from"./packem_shared/serializeSqlValue-B_-zaEWZ.mjs";import{buildSettings as Qt,isDevEnvironment as Yt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-HJ9dLr5f.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-DOTafqGL.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as sn}from"./packem_shared/buildPokeFrames-p3hk61w7.mjs";import{ShardRunner as mn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as hn}from"./packem_shared/MAX_SQL_ROWS-CY5qwGU3.mjs";import{BIGINT_KEY_DIGITS as Tn,bigintSqlKey as Cn,decodeBigintSqlKey as En}from"./packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{awaitWsDrain as gn,subscriptionFrames as An,subscriptionListDeltas as _n,trySendFrame as In}from"./packem_shared/awaitWsDrain-CPihRl1x.mjs";import{mergeChangedKeys as Ln,recordChangedKeys as Pn,writeTouchesMemo as Mn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Nn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as On}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Fn,TransactionHeadroomTracker as Bn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs";import{hasTrigger as Un,runTriggers as qn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Kn}from"./packem_shared/selectExpiredIds-CZ-ABXDQ.mjs";import{c as Wn,l as Xn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as zn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Qn,reprojectionMigrationId as Yn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Jn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as $n}from"./packem_shared/runShardMigrations-y2s6phJT.mjs";import{stableStringify as ri}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ai}from"./packem_shared/stableWireKey-iezqS3-d.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,On as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,At as DEFAULT_MAX_RELAYS,xt as DEFAULT_PROMOTION_THRESHOLDS,Fn 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,Sn as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,va as REACTOR_STATE_TABLE,zn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Qn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,qa as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,xr as SCAN_DEP,Kt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,mn as ShardRunner,Bn as TransactionHeadroomTracker,Ya as UNVOUCHABLE_DEP,Te 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,ct as applyOnDelete,fa as applySelect,de as archiveCdcSegment,pa as armRestore,tt as assertFlatPredicate,k as assertNoExplicitUndefined,un as assertReadonly,nt as assertShapeShardable,F as assertValidClientId,gn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Cn as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,yt as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Qt as buildSettings,Jt 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,Wn as compileWhereSql,Ve as computeRankPage,it as containsRelationPredicate,Ot as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Tr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,ja as createReadFootprint,bt as createRelayLink,Pt as createReplicaLink,en as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Nn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,En as decodeBigintSqlKey,Ta as decodeCursor,Ne as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Cr as depKey,mo as diffExternalSource,tn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ca as encodeCursor,Do as encodeGeohash,ya as encodePartitionKey,nn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,dt as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,T as foldAggregateTally,Mt as gateReplicaDispatch,Nr as geoTableName,rn as globalShapeReadKey,qt as guardWriter,Dt as handleReplicaControl,Un as hasTrigger,No as haversineMeters,a as importShardRows,et as indexKeysForRow,Yt as isDevEnvironment,yr as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,st as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,Vo as listTables,Xn as literalInList,Ja as markUnvouchableReads,Oa as matchesRankStaticWhere,p as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Ln as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Ce as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Xa as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Ct as nextPromotionState,d 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,sn as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Jn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankTableName,wa as reactiveCacheKey,Ha as reactorNeedsRun,C as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,da as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,To as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,za as readReactorState,vt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,Pn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Xt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Et as relayCountFor,vr as renderSql,kt as reprojectableFields,Yn as reprojectionMigrationId,Ft as reprojectionTables,Ba as resolveRankPartition,Qe as resolveRankSeekTuple,lt as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,Co as runExternalSourceTick,hn as runReadonlySql,ft as runRowValidators,$n as runShardMigrations,pn as runSocketPool,Ar as runSql,qn as runTriggers,Kn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,pr as selectShapeRows,zt as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,ri as stableStringify,ai as stableWireKey,An as subscriptionFrames,_n 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,In as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,Va as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Mn 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 p,normalizeCountArgument as d,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as T,readAggregateValue as C}from"./packem_shared/aggregateTableName-qWuEmkPn.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-jtPeUPmD.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-T3lmKtDf.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-DELonHMe.mjs";import{archiveCdcSegment as de,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Te,migrateClientWatermark as Ce,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-CPMFTDV1.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-BSxeZLfg.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 pr}from"./packem_shared/selectShapeMembers-g5Fqi2XK.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CO1FLIVO.mjs";import{SCAN_DEP as xr,createDependencyTracker as Tr,depKey as Cr,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-By2TU17Q.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-prbsN-c8.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 To,runExternalSourceTick as Co}from"./packem_shared/materializeExternalRows-Dk3HhwxL.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-q1fob5XF.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-PfT6efQf.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 pa,readBookmark as da}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ta,encodeCursor as Ca,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as ga}from"./packem_shared/CURSOR_PREFIX-BoaSx8bs.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,rankTableName as Fa,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-CWCVFaq_.mjs";import{ReactiveCache as qa,reactiveCacheKey as wa}from"./packem_shared/ReactiveCache-DpfLbuFX.mjs";import{REACTOR_STATE_TABLE as va,listReactorStates as Wa,migrateReactorState as Xa,reactorNeedsRun as Ha,readReactorState as za,writeReactorState as Va}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Ya,createReadFootprint as ja,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as st,resolveRelationPredicates as lt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Zf2Yn4YT.mjs";import{applyOnDelete as ct,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-CYV38T1y.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as xt,clampPromotionThresholds as Tt,nextPromotionState as Ct,relayCountFor as Et,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BewDXVhw.mjs";import{DEFAULT_MAX_RELAYS as At,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-DlyTtTEl.mjs";import{createReplicaLink as Pt,gateReplicaDispatch as Mt,handleReplicaControl as Dt}from"./packem_shared/createReplicaLink-B4cdZv8z.mjs";import{buildReprojectionMigration as yt,countLegacyRows as Ot,reprojectableFields as kt,reprojectionTables as Ft}from"./packem_shared/buildReprojectionMigration-HbwBP2Xx.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as qt}from"./packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Kt,readSchemaHistory as vt,readSchemaVersion as Wt,recordSchemaVersion as Xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as zt}from"./packem_shared/serializeSqlValue-B_-zaEWZ.mjs";import{buildSettings as Qt,isDevEnvironment as Yt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-BNRhEpVK.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-DOTafqGL.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as sn}from"./packem_shared/buildPokeFrames-p3hk61w7.mjs";import{ShardRunner as mn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as hn}from"./packem_shared/MAX_SQL_ROWS-CY5qwGU3.mjs";import{BIGINT_KEY_DIGITS as Tn,bigintSqlKey as Cn,decodeBigintSqlKey as En}from"./packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{awaitWsDrain as gn,subscriptionFrames as An,subscriptionListDeltas as _n,trySendFrame as In}from"./packem_shared/awaitWsDrain-CPihRl1x.mjs";import{mergeChangedKeys as Ln,recordChangedKeys as Pn,writeTouchesMemo as Mn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Nn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as On}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Fn,TransactionHeadroomTracker as Bn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs";import{hasTrigger as Un,runTriggers as qn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Kn}from"./packem_shared/selectExpiredIds-CZ-ABXDQ.mjs";import{c as Wn,l as Xn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as zn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Qn,reprojectionMigrationId as Yn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Jn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as $n}from"./packem_shared/runShardMigrations-56dKx7Jq.mjs";import{stableStringify as ri}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ai}from"./packem_shared/stableWireKey-iezqS3-d.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,On as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,At as DEFAULT_MAX_RELAYS,xt as DEFAULT_PROMOTION_THRESHOLDS,Fn 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,Sn as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,va as REACTOR_STATE_TABLE,zn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Qn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,qa as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,xr as SCAN_DEP,Kt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,mn as ShardRunner,Bn as TransactionHeadroomTracker,Ya as UNVOUCHABLE_DEP,Te 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,ct as applyOnDelete,fa as applySelect,de as archiveCdcSegment,pa as armRestore,tt as assertFlatPredicate,k as assertNoExplicitUndefined,un as assertReadonly,nt as assertShapeShardable,F as assertValidClientId,gn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Cn as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,yt as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Qt as buildSettings,Jt 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,Wn as compileWhereSql,Ve as computeRankPage,it as containsRelationPredicate,Ot as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Tr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,ja as createReadFootprint,bt as createRelayLink,Pt as createReplicaLink,en as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Nn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,En as decodeBigintSqlKey,Ta as decodeCursor,Ne as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Cr as depKey,mo as diffExternalSource,tn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ca as encodeCursor,Do as encodeGeohash,ya as encodePartitionKey,nn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,dt as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,T as foldAggregateTally,Mt as gateReplicaDispatch,Nr as geoTableName,rn as globalShapeReadKey,qt as guardWriter,Dt as handleReplicaControl,Un as hasTrigger,No as haversineMeters,a as importShardRows,et as indexKeysForRow,Yt as isDevEnvironment,yr as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,st as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,Vo as listTables,Xn as literalInList,Ja as markUnvouchableReads,Oa as matchesRankStaticWhere,p as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Ln as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Ce as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Xa as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Ct as nextPromotionState,d 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,sn as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Jn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankTableName,wa as reactiveCacheKey,Ha as reactorNeedsRun,C as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,da as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,To as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,za as readReactorState,vt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,Pn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Xt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Et as relayCountFor,vr as renderSql,kt as reprojectableFields,Yn as reprojectionMigrationId,Ft as reprojectionTables,Ba as resolveRankPartition,Qe as resolveRankSeekTuple,lt as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,Co as runExternalSourceTick,hn as runReadonlySql,ft as runRowValidators,$n as runShardMigrations,pn as runSocketPool,Ar as runSql,qn as runTriggers,Kn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,pr as selectShapeRows,zt as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,ri as stableStringify,ai as stableWireKey,An as subscriptionFrames,_n 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,In as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,Va as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Mn as writeTouchesMemo};
|
|
@@ -8,8 +8,8 @@ import{LunoraError as p}from"@lunora/errors";import{sql as t}from"drizzle-orm";i
|
|
|
8
8
|
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},U=(e,o,r,i,s,d)=>{const a=d===void 0?null:A(d);m(e,N,o,r,i,s,a)},S=90,u=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,g=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=u(o.tables),a=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(E=>{const C={id:E.id,op:E.op,seq:E.seq,table:E.table,ts:E.ts};return E.doc===null?C:{...C,doc:q(E.doc)}});return{changes:a,cursor:a.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=S){const d=new Set(i.slice(s,s+S));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${u(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),B=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(c)}
|
|
9
9
|
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
10
|
GROUP BY id
|
|
11
|
-
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),
|
|
11
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),x=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
|
|
12
12
|
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
|
-
)`)},
|
|
13
|
+
)`)},W=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
|
|
14
14
|
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
-
)`)},
|
|
15
|
+
)`)},v=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},Y=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},P=(e,o)=>e!==void 0&&e>o+1,G=(e,o,r)=>new p("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,K=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},M=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const s={...r};delete s._id,await e.replace(o.id,s,o.table,{allowExplicitId:!0})}},k=async(e,o)=>{for(const r of o)await M(e,r)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,O as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,U as appendCdcChange,k as applyCdcChanges,V as bumpCdcEpoch,B as cdcCanVouchFor,v as cdcSeqLeavingRows,X as cdcTouchesTables,G as cdcTrimmedError,W as compactCdcDocs,P as cursorBelowRetainedFloor,y as migrateCdcLog,L as migrateCdcMeta,K as minCdcReplayableSeq,$ as minCdcSeq,H as readCdcChangeKeys,g as readCdcChanges,Y as readCdcCursor,z as readCdcEpoch,x as trimCdcChanges};
|
|
@@ -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-Cu_2ZASD.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-1gdkHCG2.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-BewDXVhw.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-p3hk61w7.mjs";import{v as j,R as L,s as z,a as G,b as V}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as J,trySendFrame as x}from"./awaitWsDrain-CPihRl1x.mjs";import{stableWireKey as b}from"./stableWireKey-iezqS3-d.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)}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 V(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 J(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};
|
package/dist/packem_shared/{DurableStreamRunner-Du20UUg5.mjs → DurableStreamRunner-prbsN-c8.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-Cu_2ZASD.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-Cu_2ZASD.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-C1Ok4b6J.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as it}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as ln,S as un,l as Me,a as fn}from"./ctx-db-companions-CPMFTDV1.mjs";import{sql as i}from"drizzle-orm";import{d as hn}from"./wire-codec-Cu_2ZASD.mjs";import{throwingScheduler as wn,aggregateSqlFunction as De,normalizeCountArgument as pn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Qe,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-qWuEmkPn.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Ve,selectIndexForGroupBy as gn,selectIndexForCount as $n,selectIndexForAggregate as yn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as En,searchIndexCoversTable as mn}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{backfillAggregateIndexes as Sr,backfillRankIndexes as _r,backfillSearchIndexes as Rr}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{appendCdcChange as Sn}from"./CDC_LOG_TABLE-sWDxFnHX.mjs";import{CDC_LOG_TABLE as vr,applyCdcChanges as Ar,bumpCdcEpoch as Ir,cdcCanVouchFor as Cr,cdcSeqLeavingRows as xr,cdcTouchesTables as br,cdcTrimmedError as Mr,compactCdcDocs as Dr,cursorBelowRetainedFloor as Lr,minCdcReplayableSeq as kr,minCdcSeq as Fr,readCdcChangeKeys as qr,readCdcChanges as Br,readCdcCursor as Wr,readCdcEpoch as Ur,trimCdcChanges as Pr}from"./CDC_LOG_TABLE-sWDxFnHX.mjs";import{allocateCommitSeq as _n,COMMIT_SEQ_FIELD as Rn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as St}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as _t}from"./computeRankPage-BSxeZLfg.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as Le,A as Ye,a as ke,e as X,t as Nt,j as Be,q as Rt,i as Tn,h as jt,g as vn}from"./do-sql-By2TU17Q.mjs";import{renderSql as Kt,unionAll as st,WORKERD_SQLITE_LIMITS as Qt,sqliteInList as An}from"./param-DlozcSQu.mjs";import{coveringGeohashes as In,boundingBoxGeohashes as Cn,haversineMeters as xn,pointInBoundingBox as bn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Mn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as tt,buildSeekWhere as zt,decodeCursor as nt,applySelect as Tt,encodeCursor as ot,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Dn}from"./CURSOR_PREFIX-BoaSx8bs.mjs";import{rankTableName as vt,sortColumnName as At,resolveRankPartition as Ln,encodePartitionKey as kn,RANK_TIEBREAK as Fn}from"./RANK_TIEBREAK-CWCVFaq_.mjs";import{UNVOUCHABLE_DEP as It}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as qn,buildIndexRange as Bn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Xe,resolveRelationPredicates as Ct}from"./DEFAULT_MAX_RELATION_KEYS-Zf2Yn4YT.mjs";import{runRowValidators as Ze,resolveWith as xt,relationHooks as bt,applyOnDelete as Wn,fanOutScalarCounts as Un}from"./applyOnDelete-CYV38T1y.mjs";import{guardWriter as Pn}from"./RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{isProjectedKind as Gn}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{createSystemReader as Hn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as On}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ue,r as We,j as Ee,i as Mt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Hr,advanceClientWatermark as Or,migrateClientWatermark as Nr,readClientWatermark as jr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Qr,deleteGlobalShapeSnapshot as zr,deleteGlobalShapeSnapshotsForConnection as Jr,migrateGlobalShapeSnapshot as Vr,readGlobalShapeSnapshot as Yr,writeGlobalShapeSnapshot as Xr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ei,readIdempotent as ti,trimIdempotent as ni,writeIdempotent as oi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ii}from"./runShardMigrations-y2s6phJT.mjs";import{S as ci}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as di,selectShapeRows as li}from"./selectShapeMembers-g5Fqi2XK.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-B_-zaEWZ.mjs";const Nn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},jn=()=>new $("BAD_REQUEST","invalid cursor"),Dt=16,Lt=8,Y=1024,ct=(o,r)=>r.query(o),Kn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},Qn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},zn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Lt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Lt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=ct(p,t).length;if(S>Dt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Dt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Jn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vn=o=>Math.min(o.offset+o.numItems+1,Y),Yn=o=>btoa(`search:${String(o)}`),Xn=o=>{let r;try{r=Nn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Xn(o.cursor):0;if(t===void 0)throw jn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},eo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Yn(t):null,isDone:!a,page:o.slice(r.offset,t)}},to=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(oe),no=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),kt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),oo=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),ro=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),io="SELECT changes() AS changed",Ft=new Map,so="",co=o=>{const r=JSON.stringify(o),t=Ft.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(p)} WHERE id = ${so}`),{sql:d}=Kt("sqlite",i`${st(a)} LIMIT 1`);return Ft.set(r,d),d},ao=(o,r)=>r.map(()=>o),lo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uo=o=>{if(!lo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},qt=50,Vt=500,Fe=Math.floor(Qt.boundParams/3),ge=Qt.boundParams,fo=128,ae=(o,r,t)=>{const a=r??Vt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},ho=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},wo=o=>Math.max(o,Y),Yt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},po=(o,r,t,a,d)=>{const p=ct(t.query,it(t.definition.language));if(p.length===0)return[];const E=un(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,L)=>{const B=Qn(R,L===_),K=B.exact?i`${i.identifier("term")} = ${B.lower}`:i`${i.identifier("term")} >= ${B.lower} AND ${i.identifier("term")} < ${B.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(L))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${K} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,L)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(L))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${st(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,v=Yt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(F=i`${F} WHERE ${i.join(v,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const L=jt(R);if(L){const B=R.__score__;j.push({document:L,score:typeof B=="number"?B:Number(B??0)})}}return j},go=(o,r,t,a,d)=>{const p=it(t.definition.language),E=ct(t.query,p);if(E.length===0)return[];const S=Yt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(wo(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const v=jt(A);if(!v)continue;const F=Kn(fn(v,t.definition),E);F>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:F})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},et=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},$o=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d.sw,".within() sw corner",r,t.indexName),et(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},yo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Eo=(o,r)=>{const t=yo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=xn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return bn(t,r.within)?{creationTime:a,distance:0}:void 0},mo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?In(t.near.point,t.near.radiusMeters):Cn(t.within),p=vn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const v=le(A),F=v?Eo(v,t):void 0;v&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Xt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},So=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=mo(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Zt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=So(o,r,E,S?void 0:d,a,p);return S?Xt(_,t.inMemoryFilters,d,D=>D.document):_},en=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(oe)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?We(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},_o=(o,r,t,a,d,p=()=>{})=>Zt(o,r,t,a,d,p).map(E=>E.document),Ro=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const v=le(A);if(v&&t.inMemoryFilters.every(F=>F(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},tn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Gn(t)},Bt=(o,r)=>r.some(t=>tn(o,t)),Wt=(o,r,t)=>{if(tn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},at={fieldRef:o=>We(Be(o)),serialize:re},To=o=>{let r=0;const t=[],a={fieldRef:d=>We(Be(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,G);const A=_.kind==="one"?_.field:_.references,v=_.kind==="one"?_.references:_.field,F=We(`${Rt(D,v)} = ${Rt(y,A)}`);t.push(D);const j=ne(p,a,Ue);t.pop();const R=j===void 0?F:Ee(F," AND ",j),L=Ee("EXISTS (SELECT 1 FROM ",Mt(_.table)," AS ",Mt(D)," WHERE ",R,")");return E?Ee("NOT ",L):L},serialize:re};return a},nn=o=>{const r=o.map(t=>`${Be(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Be("id")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},vo=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Ao={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Io=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},on=(o,r)=>{const t=o.order,a=Io(o);return a.length>0?tt(a.map(d=>({[d]:t})),r):tt([{_creationTime:t}],r)},Co=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Ao[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,nt(t))),a&&d.push(Dn(r,nt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},xo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},bo=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=on(a,t),D=typeof d.endCursor=="string",y=ne(Co(a,_,d.cursor,d.endCursor),at,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,F=en(r,A,nn(_),v||D?void 0:S+1),j=me(o,F.text,...F.params).toArray();E(j.length);const R=xo(j,a.inMemoryFilters,v||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?ot(O,_):null}}const L=R.length>S,B=L?R.slice(0,S):R,K=B.at(-1);return{continueCursor:L&&K?ot(K,_):null,isDone:!L,page:B}};class Mo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Do=/\s/u,Lo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Do.test(t)||t.includes(Lo)?null:t},ko=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,$e):void 0,D=S?ne(S,at,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");En(o,t,E);const M=y.inMemoryFilters.length>0,k=to(M?void 0:m),H=Tn(o);if(H&&!mn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=H?po(o,t,C,k,_):go(o,t,C,k,_);return M?(A=Z.length,Xt(Z,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Jn(Z),Z)},F=m=>v(m).map(C=>C.document),j=m=>{const C=Zn(m);return eo(F(Vn(C)),C)},R=()=>vo(on(y,E.shape)),L=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Bn(t,y.indexName,y.indexFields,y.sqlConditions,re))},B=m=>{L();let C=0;const M=(()=>{if(y.search){const k=F(m);return C=A,k}return y.geo?_o(o,t,y,_,m,k=>{C=k}):Ro(o,t,y,_,R(),m,k=>{C=k})})();return p(Math.max(C,M.length)),M},K=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let m=0;const C=(()=>{if(y.search){const M=v(void 0);return m=A,M}return Zt(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*B(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:fo});for(const k of M.page)m.every(H=>H(k))&&(yield k);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return B(void 0)},async collectWithScores(){return K()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return B(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(L(),y.search){const k=j(m);return p(k.page.length),k}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=bo(o,t,E.shape,y,m,D,k=>{C=k});return p(Math.max(C,M.page.length)),M},async take(m){return B(m)},async unique(){const m=B(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Mo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const k={definition:M,indexName:m};if(y.geo=k,C($o(k,t)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(k=>k.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(ho(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const k={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=k,C(zn(k,t,it(M.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Pt=(o,r,t)=>{const a={...r};for(const[d,p]of Nt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Gt=(o,r,t,a)=>{const d=t;for(const[p,E]of Nt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ht=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Fo=/unique constraint failed/i,qo=o=>o instanceof Error&&Fo.test(o.message),Bo=/string or blob too big/iu,Wo=(o,r)=>{if(!(!(o instanceof Error)||!Bo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},rt=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw qo(d)?new ye(`unique constraint violation on "${r}"`,"unique"):(Wo(d,r),d)}},qe=(o,r,t,a)=>{if(rt(o,r,t,a),me(o,io).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Ot=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let L=0;L<A;L+=1)v.push(i`${i.identifier(t[L])} IS ${p[L]}`);const F=t[A],j=a[A];if(F!==void 0&&j!==void 0){const L=j.direction==="desc"?">":"<";v.push(i`${i.identifier(F)} ${i.raw(L)} ${p[A]}`)}else v.push(i`${i.identifier(Fn)} < ${E}`);const[R]=v;S.push(v.length===1&&R!==void 0?R:i`(${i.join(v,i` AND `)})`)}const _=i.join(S,i` OR `),D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},yr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=_n(r)),{[Rn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...qn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),v=e=>{St(t.tables[e])&&A(It,It)},F=o.onReadRange??(e=>{A(e.table,G)}),j=e=>{v(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==G&&!D&&_?.recordRead(1),v(e),A(e,n)},L=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),K=e=>{D||_?.recordWrite(e)},O=async e=>{K(e.doc),await B(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??wn,{globalDb:H}=o,Z=o.auth??{identity:null,userId:null},Ge=o.cdc??!1,He=k,rn=Hn({scheduler:typeof He.list=="function"&&typeof He.get=="function"?He:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Ge&&!St(t.tables[e])&&Sn(r,C(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",dt=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}return W},Oe=e=>dt(e,"cascade"),z=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}},lt=async(e,n,s,f,h)=>{h&&K(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Ne=(e,n)=>dt(e,"relation load").findMany(e,n),ut=(e,n)=>(se(e)&&R(e,G),Ne(e,n)),sn=e=>!se(e.table),ft=o.relationExistsPushDown??"auto",ht=ft!=="never",{maxRelationKeys:wt}=o,_e=(e,n,s)=>Ct(e,{fetcher:ut,maxRelationKeys:wt,relationBaseWhere:s,schema:t,tableName:n}),pt=async(e,n,s,f)=>{const h=z(e,"relation grouped count");if(h)return R(e,G),Un((q,I)=>h.count(q,I),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=J(J(l,f),c),T=await _e(w,e,void 0),g=ne(T,$e),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const U=N(r,x).toArray();return new Map(U.map(q=>[q.__fk__,q.count]))};let Re=0;const gt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))gt.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>gt.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Re+=1,Re>qt)throw Re-=1,new ye(`trigger recursion exceeded ${String(qt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await On({ctx:an,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Re-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:je,ensureRankBackfilled:Ke,ensureRankBackfilledForTable:we,syncAggregates:Te,syncCompanionsForInsert:$t,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=ln({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),yt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Et=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=Et(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,co(h),...ao(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},cn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Et(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=An(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,st(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},mt={assertRankPartitionLocal:yt,ensureRankBackfilled:Ke,onRead:R,rowToDocument:le,schema:t,sql:r},W={system:rn,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,G);const h=de(f.softDeleteMode,void 0),u=J(J(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Bt(f,[n.field]))){const q=yn(f.aggregateIndexes,n.op,n.field,n.where);if(q){je(e,q.index);const I=ze(q.index.by??[],q.key),Q=Qe(e,q.index.name),V=N(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(Q)} WHERE ${ke} = ${I}`).toArray()[0];return Je(n.op,V)}}Wt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,$e),T=De(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const U=N(r,b).toArray()[0]?.value;return U??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return R(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=pn(n);if(h.restrictsCounts)throw new Ve(e);R(e,G);const u=de(f.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=$n(f.aggregateIndexes,h.where);if(x){je(e,x.index);const U=ze(x.index.by??[],x.key),q=Qe(e,x.index.name),I=N(r,i`SELECT ${Le} AS value FROM ${i.identifier(q)} WHERE ${ke} = ${U}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?H:void 0;g&&(K(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Wn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Oe(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Oe(g).delete(b,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,b,x)=>Oe(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};qe(r,c,kt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Te(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}qe(r,c,ro(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Te(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Vt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await W.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(z(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new Mn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,G):R(e);const u=tt(n.orderBy,f.shape),c=n.cursor?zt(u,nt(n.cursor)):void 0;let l=J(n.baseWhere,n.where);l=J(l,de(f.softDeleteMode,n.includeDeleted)),l=await Ct(l,{canPushExists:ht?sn:void 0,existsPushMode:ft==="always"?"always":"auto",fetcher:ut,maxRelationKeys:wt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ht?To(R):at,T=ne(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=en(e,T,nn(u),g===void 0?void 0:g+1),x=me(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const U=[];for(const V of x){const P=le(V);P&&(U.push(P),!h&&typeof P._id=="string"&&R(e,P._id))}if(g===void 0)return n.with&&await xt({groupedCounter:pt,fetcher:Ne,parents:U,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Tt(U,n.select,n.with)};const q=U.length>g,I=q?U.slice(0,g):U,Q=I.at(-1);return n.with&&await xt({fetcher:Ne,groupedCounter:pt,parents:I,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q&&n.omitContinueCursor!==!0?ot(Q,u):null,isDone:!q,page:Tt(I,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?H:void 0;return f?f.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return R(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Bt(f,T))){const I=gn(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(Q===0||Q===V)){je(e,I.index);const P=Qe(e,I.index.name),Ie=Object.keys(I.partial),Ce=[];if(Ie.length===(I.index.by??[]).length&&Ie.length>0){const xe=ze(I.index.by??[],I.partial),be=N(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(P)} WHERE ${ke} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...I.partial},value:Je(h.op,be[0])}),Ce}const dn=N(r,i`SELECT ${ke} AS key, ${Le} AS value, ${Ye} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of dn){const be=hn(JSON.parse(xe.key));Ce.push({key:be,value:Je(h.op,xe)})}return Ce}}for(const I of T){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Wt(f,I,Q)}const g=ne(l,$e),b=n.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(De(h.op))}(${X(I)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(I=>X(I)),i`, `)}`;const U=N(r,x).toArray(),q=[];for(const I of U){const Q={};for(const P of n.by)Q[P]=I[P]??null;const{value:V}=I;q.push({key:Q,value:V==null?null:Number(V)})}return q},async insert(e,n,s){const f=z(e,"insert");if(f)return lt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Pt(h,n,Z);Ze(h,u);let c;s?.clientId!==void 0?(uo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),rt(r,e,no(e),[c,l,ce(w)]),$t(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await O({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=z(e,"insert");if(f){const l=[];for(const w of n)K(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const T=Pt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/Fe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)K(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Kt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);rt(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)$t(e,w,l),await B({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=z(e,"insert");if(u)for(const l of n)K(l);const c=async l=>u?lt(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const T=s===void 0?H:void 0;if(T){K(n),await T.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ht("patch",n);const w={...u,...n,...E(c),_id:e};Gt(l,n,w,Z),Ze(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,kt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Te(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await O({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(z(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},query(e){const n=z(e,"query");return n?(R(e,G),n.query(e)):ko(r,t,e,L,s=>{s?j(s):R(e,G)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=z(e,"rank");if(f)return R(e,G),f.rank(e,n,s);L(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(yt(e,h,u),s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((P,Ie)=>At(Ie)),T=w.map(P=>Se(P)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const U=J(s.baseWhere,s.where);Xe(U,t,e,"rank");const q=Ln(u,U);if(q){const P=kn(u.partitionBy??[],q);if(P!==x)return null;x=P}const I=w.map(P=>b[P]),{before:Q,total:V}=Ot(r,l,w,u.sortBy,x,I,c);return{position:Q+1,total:V}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>At(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Ot(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage");const f=z(e,"rankPage");if(f)return R(e,G),f.rankPage(e,n,s);L(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=_t(mt,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage"),L(e,n,"rank");const{directions:f,hasMore:h,rows:u}=_t(mt,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?H:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const b=s===void 0?H:void 0;if(b){K(n),await b.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ht("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Gt(w,n,g,Z),Ze(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,oo(l),[T,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Te(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},an={db:W,scheduler:k};return o.enforceRls===!0?Pn(W,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>cn(e,n)):W};export{vr as CDC_LOG_TABLE,Hr as CLIENT_WATERMARK_TABLE,Qr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ei as IDEMPOTENCY_TABLE,Mo as NotUniqueError,ci as SEARCH_STATE_TABLE,Or as advanceClientWatermark,Ar as applyCdcChanges,Ht as assertNoExplicitUndefined,uo as assertValidClientId,Sr as backfillAggregateIndexes,_r as backfillRankIndexes,Rr as backfillSearchIndexes,Ir as bumpCdcEpoch,Cr as cdcCanVouchFor,xr as cdcSeqLeavingRows,br as cdcTouchesTables,Mr as cdcTrimmedError,Dr as compactCdcDocs,yr as createShardCtxDb,Lr as cursorBelowRetainedFloor,zr as deleteGlobalShapeSnapshot,Jr as deleteGlobalShapeSnapshotsForConnection,Nr as migrateClientWatermark,Vr as migrateGlobalShapeSnapshot,kr as minCdcReplayableSeq,Fr as minCdcSeq,Ut as normalizeIdStructurally,qr as readCdcChangeKeys,Br as readCdcChanges,Wr as readCdcCursor,Ur as readCdcEpoch,jr as readClientWatermark,Yr as readGlobalShapeSnapshot,ti as readIdempotent,ii as runShardMigrations,di as selectShapeMembers,li as selectShapeRows,Pr as trimCdcChanges,ni as trimIdempotent,Xr as writeGlobalShapeSnapshot,oi as writeIdempotent};
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as it}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as ln,S as un,l as Me,a as fn}from"./ctx-db-companions-CPMFTDV1.mjs";import{sql as i}from"drizzle-orm";import{d as hn}from"./wire-codec-Cu_2ZASD.mjs";import{throwingScheduler as wn,aggregateSqlFunction as De,normalizeCountArgument as pn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Qe,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-qWuEmkPn.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Ve,selectIndexForGroupBy as gn,selectIndexForCount as $n,selectIndexForAggregate as yn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as En,searchIndexCoversTable as mn}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{backfillAggregateIndexes as Sr,backfillRankIndexes as _r,backfillSearchIndexes as Rr}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{appendCdcChange as Sn}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{CDC_LOG_TABLE as vr,applyCdcChanges as Ar,bumpCdcEpoch as Ir,cdcCanVouchFor as Cr,cdcSeqLeavingRows as xr,cdcTouchesTables as br,cdcTrimmedError as Mr,compactCdcDocs as Dr,cursorBelowRetainedFloor as Lr,minCdcReplayableSeq as kr,minCdcSeq as Fr,readCdcChangeKeys as qr,readCdcChanges as Br,readCdcCursor as Wr,readCdcEpoch as Ur,trimCdcChanges as Pr}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{allocateCommitSeq as _n,COMMIT_SEQ_FIELD as Rn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as St}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as _t}from"./computeRankPage-BSxeZLfg.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as Le,A as Ye,a as ke,e as X,t as Nt,j as Be,q as Rt,i as Tn,h as jt,g as vn}from"./do-sql-By2TU17Q.mjs";import{renderSql as Kt,unionAll as st,WORKERD_SQLITE_LIMITS as Qt,sqliteInList as An}from"./param-DlozcSQu.mjs";import{coveringGeohashes as In,boundingBoxGeohashes as Cn,haversineMeters as xn,pointInBoundingBox as bn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Mn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as tt,buildSeekWhere as zt,decodeCursor as nt,applySelect as Tt,encodeCursor as ot,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Dn}from"./CURSOR_PREFIX-BoaSx8bs.mjs";import{rankTableName as vt,sortColumnName as At,resolveRankPartition as Ln,encodePartitionKey as kn,RANK_TIEBREAK as Fn}from"./RANK_TIEBREAK-CWCVFaq_.mjs";import{UNVOUCHABLE_DEP as It}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as qn,buildIndexRange as Bn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Xe,resolveRelationPredicates as Ct}from"./DEFAULT_MAX_RELATION_KEYS-Zf2Yn4YT.mjs";import{runRowValidators as Ze,resolveWith as xt,relationHooks as bt,applyOnDelete as Wn,fanOutScalarCounts as Un}from"./applyOnDelete-CYV38T1y.mjs";import{guardWriter as Pn}from"./RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{isProjectedKind as Gn}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{createSystemReader as Hn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as On}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ue,r as We,j as Ee,i as Mt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Hr,advanceClientWatermark as Or,migrateClientWatermark as Nr,readClientWatermark as jr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Qr,deleteGlobalShapeSnapshot as zr,deleteGlobalShapeSnapshotsForConnection as Jr,migrateGlobalShapeSnapshot as Vr,readGlobalShapeSnapshot as Yr,writeGlobalShapeSnapshot as Xr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ei,readIdempotent as ti,trimIdempotent as ni,writeIdempotent as oi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ii}from"./runShardMigrations-56dKx7Jq.mjs";import{S as ci}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as di,selectShapeRows as li}from"./selectShapeMembers-g5Fqi2XK.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-B_-zaEWZ.mjs";const Nn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},jn=()=>new $("BAD_REQUEST","invalid cursor"),Dt=16,Lt=8,Y=1024,ct=(o,r)=>r.query(o),Kn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},Qn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},zn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Lt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Lt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=ct(p,t).length;if(S>Dt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Dt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Jn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vn=o=>Math.min(o.offset+o.numItems+1,Y),Yn=o=>btoa(`search:${String(o)}`),Xn=o=>{let r;try{r=Nn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Xn(o.cursor):0;if(t===void 0)throw jn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},eo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Yn(t):null,isDone:!a,page:o.slice(r.offset,t)}},to=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(oe),no=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),kt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),oo=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),ro=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),io="SELECT changes() AS changed",Ft=new Map,so="",co=o=>{const r=JSON.stringify(o),t=Ft.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(p)} WHERE id = ${so}`),{sql:d}=Kt("sqlite",i`${st(a)} LIMIT 1`);return Ft.set(r,d),d},ao=(o,r)=>r.map(()=>o),lo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uo=o=>{if(!lo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},qt=50,Vt=500,Fe=Math.floor(Qt.boundParams/3),ge=Qt.boundParams,fo=128,ae=(o,r,t)=>{const a=r??Vt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},ho=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},wo=o=>Math.max(o,Y),Yt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},po=(o,r,t,a,d)=>{const p=ct(t.query,it(t.definition.language));if(p.length===0)return[];const E=un(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,L)=>{const B=Qn(R,L===_),K=B.exact?i`${i.identifier("term")} = ${B.lower}`:i`${i.identifier("term")} >= ${B.lower} AND ${i.identifier("term")} < ${B.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(L))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${K} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,L)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(L))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${st(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,v=Yt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(F=i`${F} WHERE ${i.join(v,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const L=jt(R);if(L){const B=R.__score__;j.push({document:L,score:typeof B=="number"?B:Number(B??0)})}}return j},go=(o,r,t,a,d)=>{const p=it(t.definition.language),E=ct(t.query,p);if(E.length===0)return[];const S=Yt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(wo(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const v=jt(A);if(!v)continue;const F=Kn(fn(v,t.definition),E);F>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:F})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},et=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},$o=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d.sw,".within() sw corner",r,t.indexName),et(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},yo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Eo=(o,r)=>{const t=yo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=xn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return bn(t,r.within)?{creationTime:a,distance:0}:void 0},mo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?In(t.near.point,t.near.radiusMeters):Cn(t.within),p=vn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const v=le(A),F=v?Eo(v,t):void 0;v&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Xt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},So=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=mo(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Zt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=So(o,r,E,S?void 0:d,a,p);return S?Xt(_,t.inMemoryFilters,d,D=>D.document):_},en=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(oe)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?We(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},_o=(o,r,t,a,d,p=()=>{})=>Zt(o,r,t,a,d,p).map(E=>E.document),Ro=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const v=le(A);if(v&&t.inMemoryFilters.every(F=>F(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},tn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Gn(t)},Bt=(o,r)=>r.some(t=>tn(o,t)),Wt=(o,r,t)=>{if(tn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},at={fieldRef:o=>We(Be(o)),serialize:re},To=o=>{let r=0;const t=[],a={fieldRef:d=>We(Be(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,G);const A=_.kind==="one"?_.field:_.references,v=_.kind==="one"?_.references:_.field,F=We(`${Rt(D,v)} = ${Rt(y,A)}`);t.push(D);const j=ne(p,a,Ue);t.pop();const R=j===void 0?F:Ee(F," AND ",j),L=Ee("EXISTS (SELECT 1 FROM ",Mt(_.table)," AS ",Mt(D)," WHERE ",R,")");return E?Ee("NOT ",L):L},serialize:re};return a},nn=o=>{const r=o.map(t=>`${Be(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Be("id")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},vo=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Ao={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Io=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},on=(o,r)=>{const t=o.order,a=Io(o);return a.length>0?tt(a.map(d=>({[d]:t})),r):tt([{_creationTime:t}],r)},Co=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Ao[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,nt(t))),a&&d.push(Dn(r,nt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},xo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},bo=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=on(a,t),D=typeof d.endCursor=="string",y=ne(Co(a,_,d.cursor,d.endCursor),at,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,F=en(r,A,nn(_),v||D?void 0:S+1),j=me(o,F.text,...F.params).toArray();E(j.length);const R=xo(j,a.inMemoryFilters,v||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?ot(O,_):null}}const L=R.length>S,B=L?R.slice(0,S):R,K=B.at(-1);return{continueCursor:L&&K?ot(K,_):null,isDone:!L,page:B}};class Mo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Do=/\s/u,Lo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Do.test(t)||t.includes(Lo)?null:t},ko=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,$e):void 0,D=S?ne(S,at,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");En(o,t,E);const M=y.inMemoryFilters.length>0,k=to(M?void 0:m),H=Tn(o);if(H&&!mn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=H?po(o,t,C,k,_):go(o,t,C,k,_);return M?(A=Z.length,Xt(Z,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Jn(Z),Z)},F=m=>v(m).map(C=>C.document),j=m=>{const C=Zn(m);return eo(F(Vn(C)),C)},R=()=>vo(on(y,E.shape)),L=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Bn(t,y.indexName,y.indexFields,y.sqlConditions,re))},B=m=>{L();let C=0;const M=(()=>{if(y.search){const k=F(m);return C=A,k}return y.geo?_o(o,t,y,_,m,k=>{C=k}):Ro(o,t,y,_,R(),m,k=>{C=k})})();return p(Math.max(C,M.length)),M},K=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let m=0;const C=(()=>{if(y.search){const M=v(void 0);return m=A,M}return Zt(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*B(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:fo});for(const k of M.page)m.every(H=>H(k))&&(yield k);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return B(void 0)},async collectWithScores(){return K()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return B(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(L(),y.search){const k=j(m);return p(k.page.length),k}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=bo(o,t,E.shape,y,m,D,k=>{C=k});return p(Math.max(C,M.page.length)),M},async take(m){return B(m)},async unique(){const m=B(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Mo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const k={definition:M,indexName:m};if(y.geo=k,C($o(k,t)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(k=>k.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(ho(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const k={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=k,C(zn(k,t,it(M.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Pt=(o,r,t)=>{const a={...r};for(const[d,p]of Nt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Gt=(o,r,t,a)=>{const d=t;for(const[p,E]of Nt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ht=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Fo=/unique constraint failed/i,qo=o=>o instanceof Error&&Fo.test(o.message),Bo=/string or blob too big/iu,Wo=(o,r)=>{if(!(!(o instanceof Error)||!Bo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},rt=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw qo(d)?new ye(`unique constraint violation on "${r}"`,"unique"):(Wo(d,r),d)}},qe=(o,r,t,a)=>{if(rt(o,r,t,a),me(o,io).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Ot=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let L=0;L<A;L+=1)v.push(i`${i.identifier(t[L])} IS ${p[L]}`);const F=t[A],j=a[A];if(F!==void 0&&j!==void 0){const L=j.direction==="desc"?">":"<";v.push(i`${i.identifier(F)} ${i.raw(L)} ${p[A]}`)}else v.push(i`${i.identifier(Fn)} < ${E}`);const[R]=v;S.push(v.length===1&&R!==void 0?R:i`(${i.join(v,i` AND `)})`)}const _=i.join(S,i` OR `),D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},yr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=_n(r)),{[Rn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...qn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),v=e=>{St(t.tables[e])&&A(It,It)},F=o.onReadRange??(e=>{A(e.table,G)}),j=e=>{v(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==G&&!D&&_?.recordRead(1),v(e),A(e,n)},L=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),K=e=>{D||_?.recordWrite(e)},O=async e=>{K(e.doc),await B(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??wn,{globalDb:H}=o,Z=o.auth??{identity:null,userId:null},Ge=o.cdc??!1,He=k,rn=Hn({scheduler:typeof He.list=="function"&&typeof He.get=="function"?He:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Ge&&!St(t.tables[e])&&Sn(r,C(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",dt=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}return W},Oe=e=>dt(e,"cascade"),z=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}},lt=async(e,n,s,f,h)=>{h&&K(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Ne=(e,n)=>dt(e,"relation load").findMany(e,n),ut=(e,n)=>(se(e)&&R(e,G),Ne(e,n)),sn=e=>!se(e.table),ft=o.relationExistsPushDown??"auto",ht=ft!=="never",{maxRelationKeys:wt}=o,_e=(e,n,s)=>Ct(e,{fetcher:ut,maxRelationKeys:wt,relationBaseWhere:s,schema:t,tableName:n}),pt=async(e,n,s,f)=>{const h=z(e,"relation grouped count");if(h)return R(e,G),Un((q,I)=>h.count(q,I),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=J(J(l,f),c),T=await _e(w,e,void 0),g=ne(T,$e),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const U=N(r,x).toArray();return new Map(U.map(q=>[q.__fk__,q.count]))};let Re=0;const gt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))gt.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>gt.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Re+=1,Re>qt)throw Re-=1,new ye(`trigger recursion exceeded ${String(qt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await On({ctx:an,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Re-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:je,ensureRankBackfilled:Ke,ensureRankBackfilledForTable:we,syncAggregates:Te,syncCompanionsForInsert:$t,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=ln({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),yt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Et=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=Et(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,co(h),...ao(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},cn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Et(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=An(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,st(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},mt={assertRankPartitionLocal:yt,ensureRankBackfilled:Ke,onRead:R,rowToDocument:le,schema:t,sql:r},W={system:rn,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,G);const h=de(f.softDeleteMode,void 0),u=J(J(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Bt(f,[n.field]))){const q=yn(f.aggregateIndexes,n.op,n.field,n.where);if(q){je(e,q.index);const I=ze(q.index.by??[],q.key),Q=Qe(e,q.index.name),V=N(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(Q)} WHERE ${ke} = ${I}`).toArray()[0];return Je(n.op,V)}}Wt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,$e),T=De(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const U=N(r,b).toArray()[0]?.value;return U??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return R(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=pn(n);if(h.restrictsCounts)throw new Ve(e);R(e,G);const u=de(f.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=$n(f.aggregateIndexes,h.where);if(x){je(e,x.index);const U=ze(x.index.by??[],x.key),q=Qe(e,x.index.name),I=N(r,i`SELECT ${Le} AS value FROM ${i.identifier(q)} WHERE ${ke} = ${U}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?H:void 0;g&&(K(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Wn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Oe(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Oe(g).delete(b,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,b,x)=>Oe(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};qe(r,c,kt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Te(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}qe(r,c,ro(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Te(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Vt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await W.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(z(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new Mn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,G):R(e);const u=tt(n.orderBy,f.shape),c=n.cursor?zt(u,nt(n.cursor)):void 0;let l=J(n.baseWhere,n.where);l=J(l,de(f.softDeleteMode,n.includeDeleted)),l=await Ct(l,{canPushExists:ht?sn:void 0,existsPushMode:ft==="always"?"always":"auto",fetcher:ut,maxRelationKeys:wt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ht?To(R):at,T=ne(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=en(e,T,nn(u),g===void 0?void 0:g+1),x=me(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const U=[];for(const V of x){const P=le(V);P&&(U.push(P),!h&&typeof P._id=="string"&&R(e,P._id))}if(g===void 0)return n.with&&await xt({groupedCounter:pt,fetcher:Ne,parents:U,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Tt(U,n.select,n.with)};const q=U.length>g,I=q?U.slice(0,g):U,Q=I.at(-1);return n.with&&await xt({fetcher:Ne,groupedCounter:pt,parents:I,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q&&n.omitContinueCursor!==!0?ot(Q,u):null,isDone:!q,page:Tt(I,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?H:void 0;return f?f.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return R(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Bt(f,T))){const I=gn(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(Q===0||Q===V)){je(e,I.index);const P=Qe(e,I.index.name),Ie=Object.keys(I.partial),Ce=[];if(Ie.length===(I.index.by??[]).length&&Ie.length>0){const xe=ze(I.index.by??[],I.partial),be=N(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(P)} WHERE ${ke} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...I.partial},value:Je(h.op,be[0])}),Ce}const dn=N(r,i`SELECT ${ke} AS key, ${Le} AS value, ${Ye} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of dn){const be=hn(JSON.parse(xe.key));Ce.push({key:be,value:Je(h.op,xe)})}return Ce}}for(const I of T){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Wt(f,I,Q)}const g=ne(l,$e),b=n.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(De(h.op))}(${X(I)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(I=>X(I)),i`, `)}`;const U=N(r,x).toArray(),q=[];for(const I of U){const Q={};for(const P of n.by)Q[P]=I[P]??null;const{value:V}=I;q.push({key:Q,value:V==null?null:Number(V)})}return q},async insert(e,n,s){const f=z(e,"insert");if(f)return lt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Pt(h,n,Z);Ze(h,u);let c;s?.clientId!==void 0?(uo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),rt(r,e,no(e),[c,l,ce(w)]),$t(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await O({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=z(e,"insert");if(f){const l=[];for(const w of n)K(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const T=Pt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/Fe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)K(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Kt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);rt(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)$t(e,w,l),await B({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=z(e,"insert");if(u)for(const l of n)K(l);const c=async l=>u?lt(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const T=s===void 0?H:void 0;if(T){K(n),await T.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ht("patch",n);const w={...u,...n,...E(c),_id:e};Gt(l,n,w,Z),Ze(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,kt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Te(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await O({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(z(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},query(e){const n=z(e,"query");return n?(R(e,G),n.query(e)):ko(r,t,e,L,s=>{s?j(s):R(e,G)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=z(e,"rank");if(f)return R(e,G),f.rank(e,n,s);L(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(yt(e,h,u),s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((P,Ie)=>At(Ie)),T=w.map(P=>Se(P)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const U=J(s.baseWhere,s.where);Xe(U,t,e,"rank");const q=Ln(u,U);if(q){const P=kn(u.partitionBy??[],q);if(P!==x)return null;x=P}const I=w.map(P=>b[P]),{before:Q,total:V}=Ot(r,l,w,u.sortBy,x,I,c);return{position:Q+1,total:V}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>At(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Ot(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage");const f=z(e,"rankPage");if(f)return R(e,G),f.rankPage(e,n,s);L(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=_t(mt,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage"),L(e,n,"rank");const{directions:f,hasMore:h,rows:u}=_t(mt,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?H:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const b=s===void 0?H:void 0;if(b){K(n),await b.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ht("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Gt(w,n,g,Z),Ze(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,oo(l),[T,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Te(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},an={db:W,scheduler:k};return o.enforceRls===!0?Pn(W,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>cn(e,n)):W};export{vr as CDC_LOG_TABLE,Hr as CLIENT_WATERMARK_TABLE,Qr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ei as IDEMPOTENCY_TABLE,Mo as NotUniqueError,ci as SEARCH_STATE_TABLE,Or as advanceClientWatermark,Ar as applyCdcChanges,Ht as assertNoExplicitUndefined,uo as assertValidClientId,Sr as backfillAggregateIndexes,_r as backfillRankIndexes,Rr as backfillSearchIndexes,Ir as bumpCdcEpoch,Cr as cdcCanVouchFor,xr as cdcSeqLeavingRows,br as cdcTouchesTables,Mr as cdcTrimmedError,Dr as compactCdcDocs,yr as createShardCtxDb,Lr as cursorBelowRetainedFloor,zr as deleteGlobalShapeSnapshot,Jr as deleteGlobalShapeSnapshotsForConnection,Nr as migrateClientWatermark,Vr as migrateGlobalShapeSnapshot,kr as minCdcReplayableSeq,Fr as minCdcSeq,Ut as normalizeIdStructurally,qr as readCdcChangeKeys,Br as readCdcChanges,Wr as readCdcCursor,Ur as readCdcEpoch,jr as readClientWatermark,Yr as readGlobalShapeSnapshot,ti as readIdempotent,ii as runShardMigrations,di as selectShapeMembers,li as selectShapeRows,Pr as trimCdcChanges,ni as trimIdempotent,Xr as writeGlobalShapeSnapshot,oi as writeIdempotent};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-2ULFQR_k.mjs";const a="__stream_runs",o="__stream_chunks",N=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},_=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(a)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},i=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key = ${t}`)},S=(r,t,n,s)=>_(r,t)!==void 0?!1:(i(r,t),E(r,e`INSERT INTO ${e.identifier(a)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${t}, ${"running"}, 0, ${n}, ${s})`),!0),m=(r,t)=>{i(r,t),E(r,e`DELETE FROM ${e.identifier(a)} WHERE run_key = ${t}`)},$=(r,t,n,s)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(o)} (run_key, seq, data_json) VALUES (${t}, ${n}, ${s})`)},c=(r,t,n)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(o)} WHERE run_key = ${t} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),A=(r,t,n,s,T)=>{if(_(r,t)===void 0){i(r,t);return}const d=T?.code??null,R=T?.message??null;E(r,e`UPDATE ${e.identifier(a)}
|
|
16
|
+
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${R}
|
|
17
|
+
WHERE run_key = ${t}`)},O=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key IN (
|
|
18
|
+
SELECT run_key FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}
|
|
19
|
+
)`),E(r,e`DELETE FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}`)};export{o as STREAM_CHUNKS_TABLE,a as STREAM_RUNS_TABLE,$ as appendStreamChunk,S as claimStreamRun,m as deleteStreamRun,A as finishStreamRun,N as migrateDurableStreams,c as readStreamChunks,_ as readStreamRun,O as trimStreamRuns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-g5Fqi2XK.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-DOTafqGL.mjs";import{projectColumns as g}from"./buildPokeFrames-p3hk61w7.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
package/dist/packem_shared/{createReplicaLink-C89kRMX9.mjs → createReplicaLink-B4cdZv8z.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-jtPeUPmD.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DlyTtTEl.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-56dKx7Jq.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-BewDXVhw.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-Dk3HhwxL.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{selectShapeRows as m}from"./selectShapeMembers-g5Fqi2XK.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
package/dist/packem_shared/{runShardMigrations-y2s6phJT.mjs → runShardMigrations-56dKx7Jq.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-CPMFTDV1.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-qWuEmkPn.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-CPMFTDV1.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-qWuEmkPn.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-T3lmKtDf.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-DELonHMe.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-1gdkHCG2.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-By2TU17Q.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-CWCVFaq_.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${e.identifier(M)} TEXT NOT NULL
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.55",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.31",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.26",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as L,LunoraError as M}from"@lunora/errors";import{e as T,d as I}from"./wire-codec-Cu_2ZASD.mjs";import{d as k,w as _,a as v,m as N,r as O,b as D,c as F}from"./ctx-db-relay-shapes-1gdkHCG2.mjs";import{envPositiveInt as R}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as f,DEFAULT_PROMOTION_THRESHOLDS as w,nextPromotionState as U,shapeRoutingKey as b,relayProxyKey as E,parseRelayName as K,clampPromotionThresholds as W}from"./DEFAULT_PROMOTION_THRESHOLDS-BewDXVhw.mjs";import{encodeRowsPatch as Y,buildPokeFrames as P}from"./buildPokeFrames-p3hk61w7.mjs";import{v as B,R as A,s as H,a as $,b as j}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as z,trySendFrame as x}from"./awaitWsDrain-CPihRl1x.mjs";import{stableWireKey as S}from"./stableWireKey-iezqS3-d.mjs";const G=2,X=8,g={},q=l=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(l)}`)},J=(l,e)=>l===void 0||l.epoch!==e.epoch?!1:l.cursor>=e.fromCursor&&l.cursor<e.checkpoint,V=l=>Response.json(l,{headers:{"content-type":"application/json"}}),p=()=>new Response(null,{status:204});class C{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await B(this.host.env(),e.headers.get(A),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),p();case"relay_detach":return this.onDetach(s.relayIndex),p();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),p();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),p()}case"relay_shape_subscribe":return V(this.onShapeSubscribe({...s,args:I(s.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(s),p();default:return q(s)}}maxRelays(){return R(this.host.env(),"LUNORA_MAX_RELAYS",X)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return H(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=$(this.host.env());n!==void 0&&(o[A]=await j(n,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Q extends C{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(f(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=R(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=R(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=U(this.promotionState,e,W(t,s)),this.promotionState==="owned")return 0;const r=R(this.host.env(),"LUNORA_RELAY_FAN",G);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=b(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onShapeUnsubscribe(e){const{proxies:t}=this.relayShapes(),s=e.subId===void 0?void 0:E(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of t)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(s===void 0||r===s)&&t.delete(r);k(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(f(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let n;try{n=this.host.resolveShape(e.name,e.args,t)}catch{return}if(n===void 0||n.global===!0||!s.has(n.table))return;const i=e,h=i.cursor,a=this.host.buildShapeDiff(n,h,r);if(a.length!==0)return i.cursor=r,_(this.host.sql(),i.key,r),{args:T(e.args),checkpoint:r,epoch:o,fromCursor:h,name:e.name,rowsPatch:Y(a),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const i of r.values()){const h=this.buildShapePoke(i,g,e,t,o);h&&n.push(this.multicastToRelays(s,h,i))}await Promise.all(n)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(f(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of s.values()){const i=this.buildShapePoke(n,n.identity,e,t,r);i&&o.push(this.proxyToRelay(i,n))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(f(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(c){const{body:u}=L(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:i,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let a=o;const{cohort:d,proxies:m}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const c=b(e.name,e.args);let u=d.get(c);u===void 0&&(u={args:e.args,cursor:o,key:c,name:e.name},d.set(c,u),v(this.host.sql(),u)),a=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const c=E(e.relayIndex,e.connectionId,e.subId),u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:c,name:e.name,relayIndex:e.relayIndex};m.set(c,u),v(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=P([{reset:i,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:a,epoch:n,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),N(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of O(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);D(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),F(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(a=>a.on==="read"&&a.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=S(s.effectiveWhere),o=S(s.columns);let n=!1;const i=a=>{const d={groups:[`grp_${a}`],roles:[a],sub:`__lunora_probe_${a}__`};return{identity:new Proxy(d,{get:(y,c)=>typeof c=="symbol"||c in y?Reflect.get(y,c):`${a}:${c}`,getOwnPropertyDescriptor:(y,c)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,c)),has:(y,c)=>typeof c=="symbol"?Reflect.has(y,c):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${a}__`}};return[g,i("a"),i("b")].every(a=>{let d;try{d=this.host.resolveShape(e,t,a)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&S(d.effectiveWhere)===r&&S(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Z extends C{relayAnnounced=!1;shapeRelayMemos=new WeakMap;shapeControl=new Map;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:T(s.args??{}),connectionId:o,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},i=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(i===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await i.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 z(e);for(const a of h.frames)x(e,a);return this.recordRelayShapeMemo(e,t,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.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,t){const{connectionId:s}=this.host.readAttachment(e);s===void 0||!this.canAddressSiblings()||await this.queueShapeControl(s,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:s,relayIndex:this.roleId.relayIndex,...t===void 0?{}:{subId:t},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,t){if(e===void 0)return t();const s=(this.shapeControl.get(e)??Promise.resolve()).then(t,t),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=s.then(o,o);return r.chain=n,this.shapeControl.set(e,n),s}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=b(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:n}=o,i=this.shapeRelayMemos.get(r);if(!(n===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[h,a]of Object.entries(n)){const d=i.get(h);if(b(a.name,a.args)!==t||!J(d,e))continue;const m=P([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of m)x(r,y);i.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ce=l=>{const e=l.doName();if(e===void 0)return;const t=K(e);return t===void 0?new Q(l,e):new Z(l,t.ownerKey,t.relayIndex)};export{X as DEFAULT_MAX_RELAYS,Q as OwnerRelay,Z as RelayMember,ce as createRelayLink};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{sql as r}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-2ULFQR_k.mjs";const a="__stream_runs",o="__stream_chunks",L=e=>{E(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(a)} (
|
|
2
|
-
run_key TEXT PRIMARY KEY,
|
|
3
|
-
status TEXT NOT NULL,
|
|
4
|
-
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
-
error_code TEXT,
|
|
6
|
-
error TEXT,
|
|
7
|
-
started_at REAL NOT NULL,
|
|
8
|
-
ttl_ms REAL NOT NULL
|
|
9
|
-
)`),E(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(o)} (
|
|
10
|
-
run_key TEXT NOT NULL,
|
|
11
|
-
seq INTEGER NOT NULL,
|
|
12
|
-
data_json TEXT NOT NULL,
|
|
13
|
-
PRIMARY KEY (run_key, seq)
|
|
14
|
-
)`)},d=(e,s)=>{const t=E(e,r`SELECT status, last_seq, error_code, error, started_at FROM ${r.identifier(a)} WHERE run_key = ${s} LIMIT 1`).toArray()[0];if(t!==void 0)return{...t.error===null?{}:{error:t.error},...t.error_code===null?{}:{errorCode:t.error_code},lastSeq:t.last_seq,startedAt:t.started_at,status:t.status}},N=(e,s,n,t)=>d(e,s)!==void 0?!1:(E(e,r`INSERT INTO ${r.identifier(a)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
-
VALUES (${s}, ${"running"}, 0, ${n}, ${t})`),!0),$=(e,s)=>{E(e,r`DELETE FROM ${r.identifier(o)} WHERE run_key = ${s}`),E(e,r`DELETE FROM ${r.identifier(a)} WHERE run_key = ${s}`)},S=(e,s,n,t)=>{E(e,r`INSERT OR IGNORE INTO ${r.identifier(o)} (run_key, seq, data_json) VALUES (${s}, ${n}, ${t})`)},m=(e,s,n)=>E(e,r`SELECT seq, data_json FROM ${r.identifier(o)} WHERE run_key = ${s} AND seq > ${n} ORDER BY seq ASC`).toArray().map(t=>({dataJson:t.data_json,seq:t.seq})),c=(e,s,n,t,i)=>{const T=i?.code??null,_=i?.message??null;E(e,r`UPDATE ${r.identifier(a)}
|
|
16
|
-
SET status = ${n}, last_seq = ${t}, error_code = ${T}, error = ${_}
|
|
17
|
-
WHERE run_key = ${s}`)},A=(e,s)=>{E(e,r`DELETE FROM ${r.identifier(o)} WHERE run_key IN (
|
|
18
|
-
SELECT run_key FROM ${r.identifier(a)} WHERE started_at + ttl_ms < ${s}
|
|
19
|
-
)`),E(e,r`DELETE FROM ${r.identifier(a)} WHERE started_at + ttl_ms < ${s}`)};export{o as STREAM_CHUNKS_TABLE,a as STREAM_RUNS_TABLE,S as appendStreamChunk,N as claimStreamRun,$ as deleteStreamRun,c as finishStreamRun,L as migrateDurableStreams,m as readStreamChunks,d as readStreamRun,A as trimStreamRuns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createShardCtxDb as S}from"./NotUniqueError-B9TFf3sO.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-32PiFmOR.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-y2s6phJT.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-BewDXVhw.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|