@lunora/shard-engine 1.0.0-alpha.24 → 1.0.0-alpha.26
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 +79 -2
- package/dist/index.d.ts +79 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B5HZoizX.mjs → ADMIN_FUNCTIONS-Cj1pJjVg.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DmQFpsDX.mjs → AGG_COUNT-CKtq03Go.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-DH-KHUfU.mjs → CDC_LOG_TABLE-DNFFQwF_.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs → DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B19vrJxP.mjs → DEFAULT_MAX_RELAYS-Cinp9pPC.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs → DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs} +1 -1
- package/dist/packem_shared/DurableStreamRunner-B54Jt9Iu.mjs +1 -0
- package/dist/packem_shared/{NotUniqueError-By65lhla.mjs → NotUniqueError-DYo7r67J.mjs} +1 -1
- package/dist/packem_shared/{RANK_TIEBREAK-DDtST3gN.mjs → RANK_TIEBREAK-BGk411OR.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-Cu8IfE1M.mjs → ReactiveCache-D_T10KLy.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-DgYMC5tr.mjs → aggregateTableName-DN7gk6uh.mjs} +1 -1
- package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +19 -0
- package/dist/packem_shared/{applyOnDelete-By23GK-k.mjs → applyOnDelete-crbAzVfE.mjs} +1 -1
- package/dist/packem_shared/{applySelect-UY-o13Ia.mjs → applySelect-5w13bMAR.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-BEMWTEq1.mjs → backfillAggregateIndexes-DTOIsYbi.mjs} +1 -1
- package/dist/packem_shared/{buildPokeFrames-CqxaN8_H.mjs → buildPokeFrames-DmB-FBeQ.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-YQSJX2cC.mjs → buildReprojectionMigration-JUwsTNTB.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-D1ygctSC.mjs → computeRankPage-BU8LXvQs.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +1 -0
- package/dist/packem_shared/{ctx-db-companions-c12P7dbv.mjs → ctx-db-companions-BJlCofon.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-Dp5E4UvF.mjs → defineEngineContractSuite-CvdzORsy.mjs} +1 -1
- package/dist/packem_shared/{do-sql-C7qrlm6-.mjs → do-sql-DKSFK627.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-Tr2to2aw.mjs → isSoftDeleted-DyEJueIu.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-D53xwGfY.mjs → materializeExternalRows-C-5TKdc1.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-BCuK60KT.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-C3Vv1gPm.mjs → selectExpiredIds-C4Ry_NxG.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMemberIds-WzxOG62k.mjs → selectShapeMemberIds-Bkkug6vU.mjs} +1 -1
- package/dist/packem_shared/{stableWireKey-l3cjIt-9.mjs → stableWireKey-Diuu1gGc.mjs} +1 -1
- package/dist/packem_shared/{wire-codec-Dsy70M3Q.mjs → wire-codec-Dh0j-GnY.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-D7DEvUvt.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-BWElJTC8.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CvdzORsy.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -839,6 +839,7 @@ interface ShapeSubscriptionQuery {
|
|
|
839
839
|
sinceSeq?: number;
|
|
840
840
|
}
|
|
841
841
|
interface SubscriptionEnvelope {
|
|
842
|
+
caps?: string[];
|
|
842
843
|
clientId?: string;
|
|
843
844
|
context?: Record<string, unknown>;
|
|
844
845
|
data?: unknown;
|
|
@@ -849,6 +850,7 @@ interface SubscriptionEnvelope {
|
|
|
849
850
|
name: string;
|
|
850
851
|
};
|
|
851
852
|
sinceCheckpoint?: number;
|
|
853
|
+
sinceChunk?: number;
|
|
852
854
|
sinceEpoch?: string;
|
|
853
855
|
topic?: string;
|
|
854
856
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
@@ -865,6 +867,7 @@ interface SocketAttachment {
|
|
|
865
867
|
context?: Record<string, unknown>;
|
|
866
868
|
expiresAt?: number;
|
|
867
869
|
identity?: Record<string, unknown>;
|
|
870
|
+
pageDeltas?: boolean;
|
|
868
871
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
869
872
|
subs: Record<string, SubscriptionQuery>;
|
|
870
873
|
userId?: string;
|
|
@@ -1018,6 +1021,70 @@ declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
|
1018
1021
|
declare const param: (value: unknown) => SQL;
|
|
1019
1022
|
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
1020
1023
|
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
1024
|
+
type DurableStreamStatus = "complete" | "error" | "running";
|
|
1025
|
+
interface DurableStreamRun {
|
|
1026
|
+
error?: string;
|
|
1027
|
+
errorCode?: string;
|
|
1028
|
+
lastSeq: number;
|
|
1029
|
+
startedAt: number;
|
|
1030
|
+
status: DurableStreamStatus;
|
|
1031
|
+
}
|
|
1032
|
+
interface DurableStreamChunk {
|
|
1033
|
+
dataJson: string;
|
|
1034
|
+
seq: number;
|
|
1035
|
+
}
|
|
1036
|
+
declare const migrateDurableStreams: (sql: SqlExec) => void;
|
|
1037
|
+
declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
|
|
1038
|
+
declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
|
|
1039
|
+
declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
|
|
1040
|
+
declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
|
|
1041
|
+
declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
|
|
1042
|
+
declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
|
|
1043
|
+
code: string;
|
|
1044
|
+
message: string;
|
|
1045
|
+
}) => void;
|
|
1046
|
+
declare const trimStreamRuns: (sql: SqlExec, now: number) => void;
|
|
1047
|
+
declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
|
|
1048
|
+
declare const MAX_DURABLE_STREAM_BYTES: number;
|
|
1049
|
+
interface DurableStreamSink {
|
|
1050
|
+
readonly chunk: (chunk: {
|
|
1051
|
+
data: unknown;
|
|
1052
|
+
seq: number;
|
|
1053
|
+
}) => boolean;
|
|
1054
|
+
readonly complete: () => void;
|
|
1055
|
+
readonly fail: (failure: {
|
|
1056
|
+
code: string;
|
|
1057
|
+
message: string;
|
|
1058
|
+
}) => void;
|
|
1059
|
+
}
|
|
1060
|
+
type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
|
|
1061
|
+
declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
|
|
1062
|
+
live: boolean;
|
|
1063
|
+
resuming: boolean;
|
|
1064
|
+
}) => DurableAttachDecision;
|
|
1065
|
+
interface DurableStreamAttach {
|
|
1066
|
+
readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
|
|
1067
|
+
readonly runKey: string;
|
|
1068
|
+
readonly sinceChunk: number;
|
|
1069
|
+
readonly sink: DurableStreamSink;
|
|
1070
|
+
readonly ttlMs?: number;
|
|
1071
|
+
}
|
|
1072
|
+
declare class DurableStreamRunner {
|
|
1073
|
+
private lastTrimAt;
|
|
1074
|
+
private readonly runs;
|
|
1075
|
+
private readonly sql;
|
|
1076
|
+
private readonly waitUntil;
|
|
1077
|
+
constructor(dependencies: {
|
|
1078
|
+
sql: () => SqlExec;
|
|
1079
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
1080
|
+
});
|
|
1081
|
+
attach(request: DurableStreamAttach): Promise<void>;
|
|
1082
|
+
detach(runKey: string, sink: DurableStreamSink): void;
|
|
1083
|
+
isLive(runKey: string): boolean;
|
|
1084
|
+
private attachOrThrow;
|
|
1085
|
+
private produce;
|
|
1086
|
+
private trim;
|
|
1087
|
+
}
|
|
1021
1088
|
interface ExternalSourceDiffResult {
|
|
1022
1089
|
changes: CdcChange[];
|
|
1023
1090
|
nextBaseline: Map<string, string>;
|
|
@@ -2022,7 +2089,17 @@ interface DrainableSink {
|
|
|
2022
2089
|
readonly bufferedAmount?: unknown;
|
|
2023
2090
|
}
|
|
2024
2091
|
declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
|
|
2025
|
-
|
|
2092
|
+
interface SubscriptionFrameInput {
|
|
2093
|
+
cursorSuffix: string;
|
|
2094
|
+
lastMutationId?: number;
|
|
2095
|
+
nextResult: unknown;
|
|
2096
|
+
pageDeltas?: boolean;
|
|
2097
|
+
previousJson?: string;
|
|
2098
|
+
snapshotJson: string;
|
|
2099
|
+
subId: string;
|
|
2100
|
+
table: string;
|
|
2101
|
+
}
|
|
2102
|
+
declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
|
|
2026
2103
|
declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
|
|
2027
2104
|
interface SubscriptionReadFootprint {
|
|
2028
2105
|
ranges?: Map<string, KeyRange[]>;
|
|
@@ -2061,4 +2138,4 @@ interface WhereSqlStrategy {
|
|
|
2061
2138
|
}
|
|
2062
2139
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2063
2140
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2064
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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_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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2141
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -839,6 +839,7 @@ interface ShapeSubscriptionQuery {
|
|
|
839
839
|
sinceSeq?: number;
|
|
840
840
|
}
|
|
841
841
|
interface SubscriptionEnvelope {
|
|
842
|
+
caps?: string[];
|
|
842
843
|
clientId?: string;
|
|
843
844
|
context?: Record<string, unknown>;
|
|
844
845
|
data?: unknown;
|
|
@@ -849,6 +850,7 @@ interface SubscriptionEnvelope {
|
|
|
849
850
|
name: string;
|
|
850
851
|
};
|
|
851
852
|
sinceCheckpoint?: number;
|
|
853
|
+
sinceChunk?: number;
|
|
852
854
|
sinceEpoch?: string;
|
|
853
855
|
topic?: string;
|
|
854
856
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
@@ -865,6 +867,7 @@ interface SocketAttachment {
|
|
|
865
867
|
context?: Record<string, unknown>;
|
|
866
868
|
expiresAt?: number;
|
|
867
869
|
identity?: Record<string, unknown>;
|
|
870
|
+
pageDeltas?: boolean;
|
|
868
871
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
869
872
|
subs: Record<string, SubscriptionQuery>;
|
|
870
873
|
userId?: string;
|
|
@@ -1018,6 +1021,70 @@ declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
|
1018
1021
|
declare const param: (value: unknown) => SQL;
|
|
1019
1022
|
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
1020
1023
|
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
1024
|
+
type DurableStreamStatus = "complete" | "error" | "running";
|
|
1025
|
+
interface DurableStreamRun {
|
|
1026
|
+
error?: string;
|
|
1027
|
+
errorCode?: string;
|
|
1028
|
+
lastSeq: number;
|
|
1029
|
+
startedAt: number;
|
|
1030
|
+
status: DurableStreamStatus;
|
|
1031
|
+
}
|
|
1032
|
+
interface DurableStreamChunk {
|
|
1033
|
+
dataJson: string;
|
|
1034
|
+
seq: number;
|
|
1035
|
+
}
|
|
1036
|
+
declare const migrateDurableStreams: (sql: SqlExec) => void;
|
|
1037
|
+
declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
|
|
1038
|
+
declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
|
|
1039
|
+
declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
|
|
1040
|
+
declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
|
|
1041
|
+
declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
|
|
1042
|
+
declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
|
|
1043
|
+
code: string;
|
|
1044
|
+
message: string;
|
|
1045
|
+
}) => void;
|
|
1046
|
+
declare const trimStreamRuns: (sql: SqlExec, now: number) => void;
|
|
1047
|
+
declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
|
|
1048
|
+
declare const MAX_DURABLE_STREAM_BYTES: number;
|
|
1049
|
+
interface DurableStreamSink {
|
|
1050
|
+
readonly chunk: (chunk: {
|
|
1051
|
+
data: unknown;
|
|
1052
|
+
seq: number;
|
|
1053
|
+
}) => boolean;
|
|
1054
|
+
readonly complete: () => void;
|
|
1055
|
+
readonly fail: (failure: {
|
|
1056
|
+
code: string;
|
|
1057
|
+
message: string;
|
|
1058
|
+
}) => void;
|
|
1059
|
+
}
|
|
1060
|
+
type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
|
|
1061
|
+
declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
|
|
1062
|
+
live: boolean;
|
|
1063
|
+
resuming: boolean;
|
|
1064
|
+
}) => DurableAttachDecision;
|
|
1065
|
+
interface DurableStreamAttach {
|
|
1066
|
+
readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
|
|
1067
|
+
readonly runKey: string;
|
|
1068
|
+
readonly sinceChunk: number;
|
|
1069
|
+
readonly sink: DurableStreamSink;
|
|
1070
|
+
readonly ttlMs?: number;
|
|
1071
|
+
}
|
|
1072
|
+
declare class DurableStreamRunner {
|
|
1073
|
+
private lastTrimAt;
|
|
1074
|
+
private readonly runs;
|
|
1075
|
+
private readonly sql;
|
|
1076
|
+
private readonly waitUntil;
|
|
1077
|
+
constructor(dependencies: {
|
|
1078
|
+
sql: () => SqlExec;
|
|
1079
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
1080
|
+
});
|
|
1081
|
+
attach(request: DurableStreamAttach): Promise<void>;
|
|
1082
|
+
detach(runKey: string, sink: DurableStreamSink): void;
|
|
1083
|
+
isLive(runKey: string): boolean;
|
|
1084
|
+
private attachOrThrow;
|
|
1085
|
+
private produce;
|
|
1086
|
+
private trim;
|
|
1087
|
+
}
|
|
1021
1088
|
interface ExternalSourceDiffResult {
|
|
1022
1089
|
changes: CdcChange[];
|
|
1023
1090
|
nextBaseline: Map<string, string>;
|
|
@@ -2022,7 +2089,17 @@ interface DrainableSink {
|
|
|
2022
2089
|
readonly bufferedAmount?: unknown;
|
|
2023
2090
|
}
|
|
2024
2091
|
declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
|
|
2025
|
-
|
|
2092
|
+
interface SubscriptionFrameInput {
|
|
2093
|
+
cursorSuffix: string;
|
|
2094
|
+
lastMutationId?: number;
|
|
2095
|
+
nextResult: unknown;
|
|
2096
|
+
pageDeltas?: boolean;
|
|
2097
|
+
previousJson?: string;
|
|
2098
|
+
snapshotJson: string;
|
|
2099
|
+
subId: string;
|
|
2100
|
+
table: string;
|
|
2101
|
+
}
|
|
2102
|
+
declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
|
|
2026
2103
|
declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
|
|
2027
2104
|
interface SubscriptionReadFootprint {
|
|
2028
2105
|
ranges?: Map<string, KeyRange[]>;
|
|
@@ -2061,4 +2138,4 @@ interface WhereSqlStrategy {
|
|
|
2061
2138
|
}
|
|
2062
2139
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2063
2140
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2064
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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_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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2141
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as h}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as I,mergeWhere as R,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-By65lhla.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BEMWTEq1.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DH-KHUfU.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-c12P7dbv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as me,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as he,writeIdempotent as Ae}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Re,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-D1ygctSC.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-WzxOG62k.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as qe,tableFromDepKey as Ke}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-C7qrlm6-.mjs";import{param as ir,renderSql as pr,sqliteInList as mr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{diffExternalSource as Sr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as xr,normalizeSourceDocument as fr,normalizeSourceValue as Tr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Er,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Ir}from"./packem_shared/materializeExternalRows-D53xwGfY.mjs";import{isSoftDeleted as Cr,isSourceDue as _r,pullExternalSourceIncrementalTick as Lr,pullExternalSourceTick as br}from"./packem_shared/isSoftDeleted-Tr2to2aw.mjs";import{GEO_DEFAULT_PRECISION as Nr,boundingBoxCenter as Mr,boundingBoxGeohashes as Or,coveringGeohashes as Fr,encodeGeohash as Dr,haversineMeters as Pr,pointInBoundingBox as kr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Ur,DEFAULT_FANOUT_TOPIC_LIMIT as wr,FLAGS_FUNCTION_PREFIX as qr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as vr,facetColumn as zr,findStorageReferences as Hr,listTables as Vr,readTablePage as Xr,recordFanoutPass as jr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as Jr}from"./packem_shared/ADMIN_FUNCTIONS-B5HZoizX.mjs";import{MAIL_RETENTION as $r,MAIL_TABLE as eo,clearCapturedMail as ro,ensureMailTable as oo,readCapturedMail as ao,recordCapturedMail as to}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as lo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as po}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as co,buildSeekBeforeWhere as So,buildSeekWhere as uo,decodeCursor as xo,encodeCursor as fo,normalizeOrderKeys as To,softDeleteScope as go}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Io,readQueueMessageById as Ro,readQueueMessages as Co,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as bo,encodePartitionKey as yo,matchesRankStaticWhere as No,rankKeyFromDoc as Mo,rankTableName as Oo,resolveRankPartition as Fo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as ko,reactiveCacheKey as Go}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Uo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as qo,indexKeysForRow as Ko,keysTouchRanges as Wo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as zo,assertFlatPredicate as Ho,assertShapeShardable as Vo,containsRelationPredicate as Xo,isRelationPredicate as jo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as Jo,distinctValues as Zo,fanOutScalarCounts as $o,relationHooks as ea,resolveWith as ra,runRowValidators as oa}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ta,clampPromotionThresholds as na,nextPromotionState as la,relayCountFor as sa,shapeRoutingKey as ia}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ma,OwnerRelay as da,RelayMember as ca,createRelayLink as Sa}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as xa,gateReplicaDispatch as fa,handleReplicaControl as Ta}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ea,countLegacyRows as ha,reprojectableFields as Aa,reprojectionTables as Ia}from"./packem_shared/buildReprojectionMigration-YQSJX2cC.mjs";import{RLS_UNWRAP_SYMBOL as Ca,RlsRequiredError as _a,guardWriter as La}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ya,readSchemaHistory as Na,readSchemaVersion as Ma,recordSchemaVersion as Oa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Da}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ka,isDevEnvironment as Ga}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Ua,diffGlobalMembership as wa,encodeRowsPatch as qa,projectColumns as Ka}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as va}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Ha}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Xa,assertReadonly as ja,lintReadonlySql as Qa,runReadonlySql as Ya}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Za,sendDeltaFrames as $a,subscriptionListDeltas as et,trySendFrame as rt}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as at,recordChangedKeys as tt,writeTouchesMemo as nt}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as st}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as pt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as dt,TransactionHeadroomTracker as ct}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as ut,runTriggers as xt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Tt}from"./packem_shared/selectExpiredIds-C3Vv1gPm.mjs";import{compileWhereSql as Et,literalInList as ht}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as It}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ct,reprojectionMigrationId as _t}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as bt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Nt}from"./packem_shared/runShardMigrations-BWElJTC8.mjs";import{stableStringify as Ot}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Dt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{Br as ADMIN_FUNCTIONS,Ur as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,pt as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,wr as DEFAULT_FANOUT_TOPIC_LIMIT,zo as DEFAULT_MAX_RELATION_KEYS,ma as DEFAULT_MAX_RELAYS,ta as DEFAULT_PROMOTION_THRESHOLDS,dt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,$r as MAIL_RETENTION,eo as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Xa as MAX_SQL_ROWS,lo as NotFoundError,P as NotUniqueError,da as OwnerRelay,ho as QUEUE_TABLE,bo as RANK_TIEBREAK,It as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,Ct as REPROJECTION_MIGRATION_PREFIX,Ca as RLS_UNWRAP_SYMBOL,ko as ReactiveCache,ca as RelayMember,_a as RlsRequiredError,Ue as SCAN_DEP,ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,va as ShardRunner,ct as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Jo as applyOnDelete,co as applySelect,io as armRestore,Ho as assertFlatPredicate,ja as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,Za as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Mr as boundingBoxCenter,Or as boundingBoxGeohashes,qo as buildIndexRange,Ua as buildPokeFrames,Ea as buildReprojectionMigration,So as buildSeekBeforeWhere,uo as buildSeekWhere,ka as buildSettings,j as bumpCdcEpoch,na as clampPromotionThresholds,ro as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,Et as compileWhereSql,Re as computeRankPage,Xo as containsRelationPredicate,ha as countLegacyRows,Fr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,vr as createFanoutCounters,Je as createIndexSql,Uo as createReadFootprint,Sa as createRelayLink,xa as createReplicaLink,G as createShardCtxDb,st as createSystemReader,xo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,qe as depKey,Sr as diffExternalSource,wa as diffGlobalMembership,Zo as distinctValues,g as encodeAggregateKey,fo as encodeCursor,Dr as encodeGeohash,yo as encodePartitionKey,qa as encodeRowsPatch,O as ensureAuditTable,oo as ensureMailTable,o as exportShardRows,a as exportShardTable,zr as facetColumn,$o as fanOutScalarCounts,Hr as findStorageReferences,E as foldAggregateTally,fa as gateReplicaDispatch,Ze as geoTableName,La as guardWriter,Ta as handleReplicaControl,ut as hasTrigger,Pr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ga as isDevEnvironment,$e as isFtsAvailable,Io as isLossyBody,jo as isRelationPredicate,Cr as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,Wo as keysTouchRanges,xr as liftSourceId,Qa as lintReadonlySql,Vr as listTables,ht as literalInList,No as matchesRankStaticWhere,c as matchesStaticWhere,Er as materializeExternalRows,hr as materializeExternalRowsIncremental,at as mergeChangedKeys,R as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,la as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,To as normalizeOrderKeys,fr as normalizeSourceDocument,Tr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,kr as pointInBoundingBox,Ka as projectColumns,Lr as pullExternalSourceIncrementalTick,br as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,bt as quoteIdentifier,Mo as rankKeyFromDoc,Oo as rankTableName,Go as reactiveCacheKey,h as readAggregateValue,F as readAuditLog,po as readBookmark,ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,Ro as readQueueMessageById,Co as readQueueMessages,Na as readSchemaHistory,Ma as readSchemaVersion,ye as readSearchBackfillState,Xr as readTablePage,to as recordCapturedMail,tt as recordChangedKeys,jr as recordFanoutPass,_o as recordQueueMessages,Oa as recordSchemaVersion,ea as relationHooks,sa as relayCountFor,pr as renderSql,Aa as reprojectableFields,_t as reprojectionMigrationId,Ia as reprojectionTables,Fo as resolveRankPartition,Qo as resolveRelationPredicates,ra as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,Ir as runExternalSourceTick,Ya as runReadonlySql,oa as runRowValidators,Nt as runShardMigrations,Ha as runSocketPool,ze as runSql,xt as runTriggers,Tt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,$a as sendDeltaFrames,Da as serializeSqlValue,ia as shapeRoutingKey,go as softDeleteScope,Do as sortColumnName,mr as sqliteInList,Ot as stableStringify,Dt as stableWireKey,et as subscriptionListDeltas,Yr as summarizeFanoutTopics,Jr as summarizeSubscriptions,nr as tableColumns,Ke as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,lr as tryRowToDocument,rt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ae as writeIdempotent,Ne as writeSearchBackfillState,nt as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as g}from"./packem_shared/aggregateTableName-DN7gk6uh.mjs";import{CountRlsUnsupportedError as R,mergeWhere as I,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DYo7r67J.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as X,appendCdcChange as H,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-BJlCofon.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as ge,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ie,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-BU8LXvQs.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as De,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-Bkkug6vU.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as He,c as Ve,p as Ye,a as je,A as Qe,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-DKSFK627.mjs";import{param as ir,renderSql as mr,sqliteInList as pr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Sr,claimStreamRun as ur,deleteStreamRun as xr,finishStreamRun as fr,migrateDurableStreams as Tr,readStreamChunks as Ar,readStreamRun as Er,trimStreamRuns as gr}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Rr,MAX_DURABLE_STREAM_BYTES as Ir,MAX_DURABLE_STREAM_CHUNKS as Cr,decideDurableAttach as _r}from"./packem_shared/DurableStreamRunner-B54Jt9Iu.mjs";import{diffExternalSource as br}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Nr,normalizeSourceDocument as yr,normalizeSourceValue as Dr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Fr,materializeExternalRowsIncremental as kr,readExternalSourceBaseline as Pr,runExternalSourceTick as Br}from"./packem_shared/materializeExternalRows-C-5TKdc1.mjs";import{isSoftDeleted as Ur,isSourceDue as wr,pullExternalSourceIncrementalTick as Kr,pullExternalSourceTick as qr}from"./packem_shared/isSoftDeleted-DyEJueIu.mjs";import{GEO_DEFAULT_PRECISION as vr,boundingBoxCenter as zr,boundingBoxGeohashes as Xr,coveringGeohashes as Hr,encodeGeohash as Vr,haversineMeters as Yr,pointInBoundingBox as jr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Jr,ADMIN_FUNCTION_PREFIX as Zr,DEFAULT_FANOUT_TOPIC_LIMIT as $r,FLAGS_FUNCTION_PREFIX as eo,MAX_PAGE_SIZE as ro,RELATION_FUNCTION_PREFIX as oo,createFanoutCounters as ao,facetColumn as to,findStorageReferences as no,listTables as lo,readTablePage as so,recordFanoutPass as io,selectMatchingIds as mo,summarizeFanoutTopics as po,summarizeSubscriptions as co}from"./packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs";import{MAIL_RETENTION as uo,MAIL_TABLE as xo,clearCapturedMail as fo,ensureMailTable as To,readCapturedMail as Ao,recordCapturedMail as Eo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as ho}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Io,readBookmark as Co}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Lo,buildSeekBeforeWhere as bo,buildSeekWhere as Mo,decodeCursor as No,encodeCursor as yo,normalizeOrderKeys as Do,softDeleteScope as Oo}from"./packem_shared/applySelect-5w13bMAR.mjs";import{QUEUE_TABLE as ko,clearQueueMessages as Po,isLossyBody as Bo,readQueueMessageById as Go,readQueueMessages as Uo,recordQueueMessages as wo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as qo,encodePartitionKey as Wo,matchesRankStaticWhere as vo,rankKeyFromDoc as zo,rankTableName as Xo,resolveRankPartition as Ho,sortColumnName as Vo}from"./packem_shared/RANK_TIEBREAK-BGk411OR.mjs";import{ReactiveCache as jo,reactiveCacheKey as Qo}from"./packem_shared/ReactiveCache-D_T10KLy.mjs";import{createReadFootprint as Zo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ea,indexKeysForRow as ra,keysTouchRanges as oa}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as ta,assertFlatPredicate as na,assertShapeShardable as la,containsRelationPredicate as sa,isRelationPredicate as ia,resolveRelationPredicates as ma}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{applyOnDelete as da,distinctValues as ca,fanOutScalarCounts as Sa,relationHooks as ua,resolveWith as xa,runRowValidators as fa}from"./packem_shared/applyOnDelete-crbAzVfE.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Aa,clampPromotionThresholds as Ea,nextPromotionState as ga,relayCountFor as ha,shapeRoutingKey as Ra}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{DEFAULT_MAX_RELAYS as Ca,OwnerRelay as _a,RelayMember as La,createRelayLink as ba}from"./packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{createReplicaLink as Na,gateReplicaDispatch as ya,handleReplicaControl as Da}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Fa,countLegacyRows as ka,reprojectableFields as Pa,reprojectionTables as Ba}from"./packem_shared/buildReprojectionMigration-JUwsTNTB.mjs";import{RLS_UNWRAP_SYMBOL as Ua,RlsRequiredError as wa,guardWriter as Ka}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wa,readSchemaHistory as va,readSchemaVersion as za,recordSchemaVersion as Xa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Va}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ja,isDevEnvironment as Qa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Za,diffGlobalMembership as $a,encodeRowsPatch as et,projectColumns as rt}from"./packem_shared/buildPokeFrames-DmB-FBeQ.mjs";import{ShardRunner as at}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as nt}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as st,assertReadonly as it,lintReadonlySql as mt,runReadonlySql as pt}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ct,subscriptionFrames as St,subscriptionListDeltas as ut,trySendFrame as xt}from"./packem_shared/awaitWsDrain-PT9o0d6J.mjs";import{mergeChangedKeys as Tt,recordChangedKeys as At,writeTouchesMemo as Et}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ht}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as It}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _t,TransactionHeadroomTracker as Lt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as Mt,runTriggers as Nt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Dt}from"./packem_shared/selectExpiredIds-C4Ry_NxG.mjs";import{compileWhereSql as Ft,literalInList as kt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as Bt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ut,reprojectionMigrationId as wt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as qt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vt}from"./packem_shared/runShardMigrations-BCuK60KT.mjs";import{stableStringify as Xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Vt}from"./packem_shared/stableWireKey-Diuu1gGc.mjs";export{Jr as ADMIN_FUNCTIONS,Zr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Ve as AGG_KEY,Ye as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,X as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,It as ConflictError,R as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,$r as DEFAULT_FANOUT_TOPIC_LIMIT,ta as DEFAULT_MAX_RELATION_KEYS,Ca as DEFAULT_MAX_RELAYS,Aa as DEFAULT_PROMOTION_THRESHOLDS,_t as DEFAULT_TRANSACTION_LIMITS,je as DOC_COLUMN,Rr as DurableStreamRunner,eo as FLAGS_FUNCTION_PREFIX,vr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,uo as MAIL_RETENTION,xo as MAIL_TABLE,Ir as MAX_DURABLE_STREAM_BYTES,Cr as MAX_DURABLE_STREAM_CHUNKS,ro as MAX_PAGE_SIZE,st as MAX_SQL_ROWS,ho as NotFoundError,k as NotUniqueError,_a as OwnerRelay,ko as QUEUE_TABLE,qo as RANK_TIEBREAK,Bt as RELATION_EXISTS_KEY,oo as RELATION_FUNCTION_PREFIX,Ut as REPROJECTION_MIGRATION_PREFIX,Ua as RLS_UNWRAP_SYMBOL,jo as ReactiveCache,La as RelayMember,wa as RlsRequiredError,Ue as SCAN_DEP,Wa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,at as ShardRunner,Lt as TransactionHeadroomTracker,te as advanceClientWatermark,Qe as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,H as appendCdcChange,Sr as appendStreamChunk,V as applyCdcChanges,da as applyOnDelete,Lo as applySelect,Io as armRestore,na as assertFlatPredicate,it as assertReadonly,la as assertShapeShardable,P as assertValidClientId,ct as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,zr as boundingBoxCenter,Xr as boundingBoxGeohashes,ea as buildIndexRange,Za as buildPokeFrames,Fa as buildReprojectionMigration,bo as buildSeekBeforeWhere,Mo as buildSeekWhere,ja as buildSettings,Y as bumpCdcEpoch,ur as claimStreamRun,Ea as clampPromotionThresholds,fo as clearCapturedMail,Po as clearQueueMessages,T as coerceAggregateNumber,Ft as compileWhereSql,Ie as computeRankPage,sa as containsRelationPredicate,ka as countLegacyRows,Hr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,ao as createFanoutCounters,Je as createIndexSql,Zo as createReadFootprint,ba as createRelayLink,Na as createReplicaLink,B as createShardCtxDb,ht as createSystemReader,_r as decideDurableAttach,No as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,xr as deleteStreamRun,Ke as depKey,br as diffExternalSource,$a as diffGlobalMembership,ca as distinctValues,A as encodeAggregateKey,yo as encodeCursor,Vr as encodeGeohash,Wo as encodePartitionKey,et as encodeRowsPatch,D as ensureAuditTable,To as ensureMailTable,o as exportShardRows,a as exportShardTable,to as facetColumn,Sa as fanOutScalarCounts,no as findStorageReferences,fr as finishStreamRun,E as foldAggregateTally,ya as gateReplicaDispatch,Ze as geoTableName,Ka as guardWriter,Da as handleReplicaControl,Mt as hasTrigger,Yr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,ra as indexKeysForRow,Qa as isDevEnvironment,$e as isFtsAvailable,Bo as isLossyBody,ia as isRelationPredicate,Ur as isSoftDeleted,wr as isSourceDue,er as jsonPath,rr as jsonPathSql,oa as keysTouchRanges,Nr as liftSourceId,mt as lintReadonlySql,lo as listTables,kt as literalInList,vo as matchesRankStaticWhere,c as matchesStaticWhere,Fr as materializeExternalRows,kr as materializeExternalRowsIncremental,Tt as mergeChangedKeys,I as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,Tr as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ga as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Do as normalizeOrderKeys,yr as normalizeSourceDocument,Dr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,jr as pointInBoundingBox,rt as projectColumns,Kr as pullExternalSourceIncrementalTick,qr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,qt as quoteIdentifier,zo as rankKeyFromDoc,Xo as rankTableName,Qo as reactiveCacheKey,g as readAggregateValue,O as readAuditLog,Co as readBookmark,Ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Pr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,Pe as readMigrationStatus,Go as readQueueMessageById,Uo as readQueueMessages,va as readSchemaHistory,za as readSchemaVersion,Me as readSearchBackfillState,Ar as readStreamChunks,Er as readStreamRun,so as readTablePage,Eo as recordCapturedMail,At as recordChangedKeys,io as recordFanoutPass,wo as recordQueueMessages,Xa as recordSchemaVersion,ua as relationHooks,ha as relayCountFor,mr as renderSql,Pa as reprojectableFields,wt as reprojectionMigrationId,Ba as reprojectionTables,Ho as resolveRankPartition,ma as resolveRelationPredicates,xa as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Br as runExternalSourceTick,pt as runReadonlySql,fa as runRowValidators,vt as runShardMigrations,nt as runSocketPool,ze as runSql,Nt as runTriggers,Dt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,mo as selectMatchingIds,De as selectShapeMemberIds,Oe as selectShapeRows,Va as serializeSqlValue,Ra as shapeRoutingKey,Oo as softDeleteScope,Vo as sortColumnName,pr as sqliteInList,Xt as stableStringify,Vt as stableWireKey,St as subscriptionFrames,ut as subscriptionListDeltas,po as summarizeFanoutTopics,co as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,ge as trimIdempotent,gr as trimStreamRuns,lr as tryRowToDocument,xt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,Et as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-C7qrlm6-.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dh0j-GnY.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-
|
|
1
|
+
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dh0j-GnY.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-DKSFK627.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${e.identifier("table")} TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-crbAzVfE.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B19vrJxP.mjs → DEFAULT_MAX_RELAYS-Cinp9pPC.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dsy70M3Q.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-CqxaN8_H.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-Bp2jKzIb.mjs";import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";const $=2,F=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{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 P(this.host.env(),e.headers.get(R),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),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",F)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;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(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){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()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",$);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}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(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.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:r,cursor:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();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.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;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,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(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(s=>s!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{F as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
|
|
1
|
+
import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dh0j-GnY.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-DmB-FBeQ.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-PT9o0d6J.mjs";import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";const F=2,$=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{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 P(this.host.env(),e.headers.get(R),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),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",$)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;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(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){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()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}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(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.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:r,cursor:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();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.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;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,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(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(s=>s!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{$ as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-Diuu1gGc.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{a as p}from"./wire-codec-Dh0j-GnY.mjs";import{readStreamRun as k,deleteStreamRun as T,claimStreamRun as w,appendStreamChunk as y,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as _}from"./appendStreamChunk-ksZYy1hZ.mjs";const g=5e4,E=64*1024*1024,b=864e5,N=36e5,M=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class v{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:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=k(r,t),u=i>0,n=this.runs.get(t),a=M(s,{live:n!==void 0,resuming:u}),c=()=>{for(const h of _(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(a==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(a==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(n){c()&&n.sinks.add(o);return}a==="reclaim"&&T(r,t),this.trim(r),w(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const n of r(o.signal)){const a=p(n),c=JSON.stringify(a);if(s+=1,u+=c.length,s>g||u>E)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(g)} chunks / ${String(E)} bytes); yield less, or drop \`durable\``,{status:507});y(i,e,s,c);for(const l of t.sinks)l.chunk({data:a,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:c}=f(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),R(i,e,"error",s,{code:a.code,message:a.message});for(const l of t.sinks)l.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{A(e,r)}catch{}}}}export{v as DurableStreamRunner,E as MAX_DURABLE_STREAM_BYTES,g as MAX_DURABLE_STREAM_CHUNKS,M as decideDurableAttach};
|