@lunora/shard-engine 1.0.0-alpha.40 → 1.0.0-alpha.41
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 +25 -8
- package/dist/index.d.ts +25 -8
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-DcSYybsq.mjs → ADMIN_FUNCTIONS-DKos6M_I.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-B6_CmAZD.mjs → AGG_COUNT-DLoWGwBC.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-uNVU9O1W.mjs → AUDIT_LOG_TABLE-ONxmEAIz.mjs} +1 -1
- package/dist/packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs +15 -0
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs → CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-CSe_oNZu.mjs → COMMIT_SEQ_FIELD-BUdOMG5y.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs → DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs → DEFAULT_MAX_RELATION_KEYS-Bbyb7_rO.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BPv7jVgK.mjs → DEFAULT_MAX_RELAYS-4Lslx8Qu.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs → DEFAULT_PROMOTION_THRESHOLDS-BDnVpbQ9.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-DDBi1UXj.mjs → DurableStreamRunner-cq7kMv9M.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-DKVe2Ohf.mjs → IDEMPOTENCY_TABLE-DOpm_oMF.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-Cig9Dmc8.mjs → MAIL_RETENTION-DGAQTHHs.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-D5URxcDG.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-zj9Tt6tk.mjs → QUEUE_TABLE-s7QJZvBz.mjs} +1 -1
- package/dist/packem_shared/{RANK_TIEBREAK-ci3MaM65.mjs → RANK_TIEBREAK-DBzb8aDX.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-Cr9Orfp8.mjs → REACTOR_STATE_TABLE-QPRFyxMS.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-DlJ38txF.mjs → ReactiveCache-gcV_jBm2.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs → SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-Dju8ebbU.mjs → SEARCH_STATE_TABLE-BCqn5ksa.mjs} +1 -1
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs +8 -0
- package/dist/packem_shared/{ShapeDiffCache-mE7ZzdPr.mjs → ShapeDiffCache-DLBPMAaA.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-Cy5e03oz.mjs → aggregateTableName-XtEbp1DE.mjs} +1 -1
- package/dist/packem_shared/{appendStreamChunk-CH4e4nJn.mjs → appendStreamChunk-8eH4HB1Q.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-BlcwKjuO.mjs → applyOnDelete-VGMOvm-o.mjs} +1 -1
- package/dist/packem_shared/applySelect-gwCG8hQF.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-BpfFOTSS.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-C9wGiPH4.mjs → backfillAggregateIndexes-wsjTZz7k.mjs} +1 -1
- package/dist/packem_shared/{buildPokeFrames-BhYUbqzO.mjs → buildPokeFrames-BvgtmTHk.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-D0f-sshM.mjs → buildReprojectionMigration-DcEoW2QQ.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-C3sZW3bZ.mjs → buildShapeDiff-DEPp9Rbv.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-CXULwypv.mjs → clearMemoryTables-BGbmag2i.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-DMH7Qtzd.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-Bby1Npkd.mjs → computeRankPage-CfDhzXMF.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-29Gp1xI_.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-Bv7250Ef.mjs → createReplicaLink-GrknD9FY.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-companions-BQRTS_WY.mjs → ctx-db-companions-B4gOYjdz.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-Jf5xpD1r.mjs → ctx-db-relay-shapes-C93UQ7LV.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-CjxJNwwG.mjs → defineEngineContractSuite-Dvd03W9-.mjs} +1 -1
- package/dist/packem_shared/do-sql-DqQTxsj_.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-D0iaSrDV.mjs → isSoftDeleted-DvUFsJE9.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-CX55UoV7.mjs → materializeExternalRows-DmSW2ujk.mjs} +1 -1
- package/dist/packem_shared/{param-Ib8WHnrF.mjs → param-DlozcSQu.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-it6rL9bR.mjs → runDrizzle-2ULFQR_k.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-C4bvso2W.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-w4fPtlwT.mjs → selectExpiredIds-rvmKjueQ.mjs} +1 -1
- package/dist/packem_shared/selectShapeMembers-Ce5Jr6UH.mjs +1 -0
- package/dist/packem_shared/{stableWireKey-DSCJB6E7.mjs → stableWireKey-BC6DtQic.mjs} +1 -1
- package/dist/packem_shared/where-sql-DxCbgqDJ.mjs +1 -0
- package/dist/packem_shared/wire-codec-CDds5uQW.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs +0 -15
- package/dist/packem_shared/NotUniqueError-Dnik6z41.mjs +0 -1
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs +0 -7
- package/dist/packem_shared/applySelect-BQbHyo-W.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-CeaR5jj8.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Cfju9Ng2.mjs +0 -1
- package/dist/packem_shared/do-sql-DbEszTyj.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DFc_LoP-.mjs +0 -5
- package/dist/packem_shared/selectShapeMembers-C0vtU60D.mjs +0 -1
- package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Dvd03W9-.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -251,6 +251,7 @@ interface QueryArgs {
|
|
|
251
251
|
cursor?: null | string;
|
|
252
252
|
includeDeleted?: boolean;
|
|
253
253
|
limit?: number;
|
|
254
|
+
omitContinueCursor?: boolean;
|
|
254
255
|
orderBy?: OrderByInput[];
|
|
255
256
|
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
256
257
|
relationMask?: RelationMask;
|
|
@@ -975,6 +976,12 @@ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
|
975
976
|
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
976
977
|
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
977
978
|
declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
|
|
979
|
+
interface ShapePokeCursorRow {
|
|
980
|
+
connectionId: string;
|
|
981
|
+
cursor: number;
|
|
982
|
+
subId: string;
|
|
983
|
+
}
|
|
984
|
+
declare const writeShapePokeCursors: (sql: SqlExec, rows: ReadonlyArray<ShapePokeCursorRow>) => void;
|
|
978
985
|
declare const minShapePokeCursor: (sql: SqlExec) => number | undefined;
|
|
979
986
|
declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
980
987
|
declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
@@ -2285,15 +2292,25 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
|
|
|
2285
2292
|
hasMore: boolean;
|
|
2286
2293
|
ids: string[];
|
|
2287
2294
|
};
|
|
2288
|
-
|
|
2295
|
+
interface WhereFragments<T> {
|
|
2296
|
+
binary: (reference: T, comparator: string, value: unknown) => T;
|
|
2297
|
+
connect: (left: T, right: T, connector: "AND" | "OR") => T;
|
|
2298
|
+
constant: (value: boolean) => T;
|
|
2299
|
+
contains: (reference: T, term: T) => T;
|
|
2300
|
+
inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
|
|
2301
|
+
negate: (inner: T) => T;
|
|
2302
|
+
nullCheck: (reference: T, negated: boolean) => T;
|
|
2303
|
+
value: (value: unknown) => T;
|
|
2304
|
+
}
|
|
2305
|
+
type FieldRefSql<T> = (field: string) => T;
|
|
2289
2306
|
type SerializeValue = (value: unknown) => unknown;
|
|
2290
|
-
interface WhereSqlStrategy {
|
|
2291
|
-
containsExpr?: (reference:
|
|
2292
|
-
fieldRef: FieldRefSql
|
|
2293
|
-
inList?: (reference:
|
|
2294
|
-
relationExists?: (request: unknown) =>
|
|
2307
|
+
interface WhereSqlStrategy<T = SQL> {
|
|
2308
|
+
containsExpr?: (reference: T, term: T) => T;
|
|
2309
|
+
fieldRef: FieldRefSql<T>;
|
|
2310
|
+
inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
|
|
2311
|
+
relationExists?: (request: unknown) => T;
|
|
2295
2312
|
serialize: SerializeValue;
|
|
2296
2313
|
}
|
|
2297
2314
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2298
|
-
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) =>
|
|
2299
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
|
2315
|
+
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2316
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -251,6 +251,7 @@ interface QueryArgs {
|
|
|
251
251
|
cursor?: null | string;
|
|
252
252
|
includeDeleted?: boolean;
|
|
253
253
|
limit?: number;
|
|
254
|
+
omitContinueCursor?: boolean;
|
|
254
255
|
orderBy?: OrderByInput[];
|
|
255
256
|
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
256
257
|
relationMask?: RelationMask;
|
|
@@ -975,6 +976,12 @@ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
|
975
976
|
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
976
977
|
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
977
978
|
declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
|
|
979
|
+
interface ShapePokeCursorRow {
|
|
980
|
+
connectionId: string;
|
|
981
|
+
cursor: number;
|
|
982
|
+
subId: string;
|
|
983
|
+
}
|
|
984
|
+
declare const writeShapePokeCursors: (sql: SqlExec, rows: ReadonlyArray<ShapePokeCursorRow>) => void;
|
|
978
985
|
declare const minShapePokeCursor: (sql: SqlExec) => number | undefined;
|
|
979
986
|
declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
980
987
|
declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
@@ -2285,15 +2292,25 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
|
|
|
2285
2292
|
hasMore: boolean;
|
|
2286
2293
|
ids: string[];
|
|
2287
2294
|
};
|
|
2288
|
-
|
|
2295
|
+
interface WhereFragments<T> {
|
|
2296
|
+
binary: (reference: T, comparator: string, value: unknown) => T;
|
|
2297
|
+
connect: (left: T, right: T, connector: "AND" | "OR") => T;
|
|
2298
|
+
constant: (value: boolean) => T;
|
|
2299
|
+
contains: (reference: T, term: T) => T;
|
|
2300
|
+
inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
|
|
2301
|
+
negate: (inner: T) => T;
|
|
2302
|
+
nullCheck: (reference: T, negated: boolean) => T;
|
|
2303
|
+
value: (value: unknown) => T;
|
|
2304
|
+
}
|
|
2305
|
+
type FieldRefSql<T> = (field: string) => T;
|
|
2289
2306
|
type SerializeValue = (value: unknown) => unknown;
|
|
2290
|
-
interface WhereSqlStrategy {
|
|
2291
|
-
containsExpr?: (reference:
|
|
2292
|
-
fieldRef: FieldRefSql
|
|
2293
|
-
inList?: (reference:
|
|
2294
|
-
relationExists?: (request: unknown) =>
|
|
2307
|
+
interface WhereSqlStrategy<T = SQL> {
|
|
2308
|
+
containsExpr?: (reference: T, term: T) => T;
|
|
2309
|
+
fieldRef: FieldRefSql<T>;
|
|
2310
|
+
inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
|
|
2311
|
+
relationExists?: (request: unknown) => T;
|
|
2295
2312
|
serialize: SerializeValue;
|
|
2296
2313
|
}
|
|
2297
2314
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2298
|
-
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) =>
|
|
2299
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
|
2315
|
+
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2316
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Dnik6z41.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-C9wGiPH4.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as Te,COMMIT_SEQ_TABLE as he,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-BQRTS_WY.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Me,readGlobalShapeSnapshot as Pe,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as Fe,trimIdempotent as ke,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{selectShapeMembers as tr,selectShapeRows as nr}from"./packem_shared/selectShapeMembers-C0vtU60D.mjs";import{DATA_MIGRATION_STATE_TABLE as sr,readMigrationStatus as ir,runDataMigration as mr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as pr,createDependencyTracker as dr,depKey as Sr,tableFromDepKey as ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as xr,runSql as Tr}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as Er,a as Cr,b as Rr,D as Ar,c as gr,d as _r,g as Ir,i as br,j as Lr,e as Mr,q as Pr,f as Dr,r as yr,t as Nr,h as Or}from"./packem_shared/do-sql-DbEszTyj.mjs";import{param as kr,renderSql as Br,sqliteInList as Gr,unionAll as Ur}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as wr,claimStreamRun as Kr,deleteStreamRun as vr,finishStreamRun as Wr,migrateDurableStreams as Hr,readStreamChunks as Xr,readStreamRun as zr,trimStreamRuns as Vr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as jr,MAX_DURABLE_STREAM_BYTES as Yr,MAX_DURABLE_STREAM_CHUNKS as Jr,decideDurableAttach as Zr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{envOptionalPositiveInt as eo,envPositiveInt as ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as ao}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as no,normalizeSourceDocument as lo,normalizeSourceValue as so}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as mo,materializeExternalRowsIncremental as co,readExternalSourceBaseline as po,runExternalSourceTick as So}from"./packem_shared/materializeExternalRows-CX55UoV7.mjs";import{isSoftDeleted as fo,isSourceDue as xo,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as ho}from"./packem_shared/isSoftDeleted-D0iaSrDV.mjs";import{GEO_DEFAULT_PRECISION as Co,boundingBoxCenter as Ro,boundingBoxGeohashes as Ao,coveringGeohashes as go,encodeGeohash as _o,haversineMeters as Io,pointInBoundingBox as bo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Do,ADMIN_FUNCTION_PREFIX as yo,DEFAULT_FANOUT_TOPIC_LIMIT as No,FLAGS_FUNCTION_PREFIX as Oo,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as ko,createFanoutCounters as Bo,createGlobalPollCounters as Go,createShapeProbeCounters as Uo,facetColumn as qo,findStorageReferences as wo,listTables as Ko,readTablePage as vo,recordFanoutPass as Wo,recordGlobalPollPass as Ho,recordShapeProbePass as Xo,selectMatchingIds as zo,summarizeFanoutTopics as Vo,summarizeSubscriptions as Qo}from"./packem_shared/ADMIN_FUNCTIONS-DcSYybsq.mjs";import{MAIL_RETENTION as Yo,MAIL_TABLE as Jo,clearCapturedMail as Zo,ensureMailTable as $o,readCapturedMail as ea,recordCapturedMail as ra}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as na,readBookmark as la}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ia,buildSeekBeforeWhere as ma,buildSeekWhere as ca,decodeCursor as pa,encodeCursor as da,normalizeOrderKeys as Sa,softDeleteScope as ua}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as xa,clearQueueMessages as Ta,isLossyBody as ha,readQueueMessageById as Ea,readQueueMessages as Ca,recordQueueMessages as Ra}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ga,encodePartitionKey as _a,matchesRankStaticWhere as Ia,rankKeyFromDoc as ba,rankTableName as La,resolveRankPartition as Ma,sortColumnName as Pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as ya,reactiveCacheKey as Na}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as ka,migrateReactorState as Ba,reactorNeedsRun as Ga,readReactorState as Ua,writeReactorState as qa}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{UNVOUCHABLE_DEP as Ka,createReadFootprint as va,markUnvouchableReads as Wa}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Xa,indexKeysForRow as za,keysTouchRanges as Va}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as ja,assertFlatPredicate as Ya,assertShapeShardable as Ja,containsRelationPredicate as Za,isRelationPredicate as $a,resolveRelationPredicates as et}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ot,distinctValues as at,fanOutScalarCounts as tt,relationHooks as nt,resolveWith as lt,runRowValidators as st}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as mt,clampPromotionThresholds as ct,nextPromotionState as pt,relayCountFor as dt,shapeRoutingKey as St}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as ft,OwnerRelay as xt,RelayMember as Tt,createRelayLink as ht}from"./packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{createReplicaLink as Ct,gateReplicaDispatch as Rt,handleReplicaControl as At}from"./packem_shared/createReplicaLink-Bv7250Ef.mjs";import{buildReprojectionMigration as _t,countLegacyRows as It,reprojectableFields as bt,reprojectionTables as Lt}from"./packem_shared/buildReprojectionMigration-D0f-sshM.mjs";import{RLS_UNWRAP_SYMBOL as Pt,RlsRequiredError as Dt,guardWriter as yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ot,readSchemaHistory as Ft,readSchemaVersion as kt,recordSchemaVersion as Bt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Ut}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as wt,isDevEnvironment as Kt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Wt}from"./packem_shared/buildShapeDiff-C3sZW3bZ.mjs";import{ShapeDiffCache as Xt,createShapeDiffCache as zt,globalShapeReadKey as Vt}from"./packem_shared/ShapeDiffCache-mE7ZzdPr.mjs";import{buildPokeFrames as jt,diffGlobalMembership as Yt,encodeRowsPatch as Jt,projectColumns as Zt}from"./packem_shared/buildPokeFrames-BhYUbqzO.mjs";import{ShardRunner as en}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as on}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as tn,assertReadonly as nn,lintReadonlySql as ln,runReadonlySql as sn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as cn,subscriptionFrames as pn,subscriptionListDeltas as dn,trySendFrame as Sn}from"./packem_shared/awaitWsDrain-CeaR5jj8.mjs";import{mergeChangedKeys as fn,recordChangedKeys as xn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as gn,TransactionHeadroomTracker as _n}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as bn,runTriggers as Ln}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Pn}from"./packem_shared/selectExpiredIds-w4fPtlwT.mjs";import{compileWhereSql as yn,literalInList as Nn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as qn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Kn}from"./packem_shared/runShardMigrations-DFc_LoP-.mjs";import{stableStringify as Wn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{Do as ADMIN_FUNCTIONS,yo as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Er as AGG_COUNT,Cr as AGG_KEY,Rr as AGG_VALUE,P as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,Te as COMMIT_SEQ_FIELD,he as COMMIT_SEQ_TABLE,Rn as ConflictError,A as CountRlsUnsupportedError,sr as DATA_MIGRATION_STATE_TABLE,No as DEFAULT_FANOUT_TOPIC_LIMIT,ja as DEFAULT_MAX_RELATION_KEYS,ft as DEFAULT_MAX_RELAYS,mt as DEFAULT_PROMOTION_THRESHOLDS,gn as DEFAULT_TRANSACTION_LIMITS,Ar as DOC_COLUMN,jr as DurableStreamRunner,Oo as FLAGS_FUNCTION_PREFIX,Co as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Yo as MAIL_RETENTION,Jo as MAIL_TABLE,Yr as MAX_DURABLE_STREAM_BYTES,Jr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,tn as MAX_SQL_ROWS,aa as NotFoundError,F as NotUniqueError,xt as OwnerRelay,xa as QUEUE_TABLE,ga as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,ko as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Pt as RLS_UNWRAP_SYMBOL,ya as ReactiveCache,Tt as RelayMember,Dt as RlsRequiredError,pr as SCAN_DEP,Ot as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,Xt as ShapeDiffCache,en as ShardRunner,_n as TransactionHeadroomTracker,Ka as UNVOUCHABLE_DEP,Se as advanceClientWatermark,gr as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,wr as appendStreamChunk,Q as applyCdcChanges,ot as applyOnDelete,ia as applySelect,na as armRestore,Ya as assertFlatPredicate,nn as assertReadonly,Ja as assertShapeShardable,k as assertValidClientId,cn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ro as boundingBoxCenter,Ao as boundingBoxGeohashes,Xa as buildIndexRange,jt as buildPokeFrames,_t as buildReprojectionMigration,ma as buildSeekBeforeWhere,ca as buildSeekWhere,wt as buildSettings,Wt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Kr as claimStreamRun,ct as clampPromotionThresholds,Zo as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,yn as compileWhereSql,ve as computeRankPage,Za as containsRelationPredicate,It as countLegacyRows,go as coveringGeohashes,ge as createCompanionSync,dr as createDependencyTracker,Bo as createFanoutCounters,Go as createGlobalPollCounters,_r as createIndexSql,va as createReadFootprint,ht as createRelayLink,Ct as createReplicaLink,zt as createShapeDiffCache,Uo as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,re as cursorBelowRetainedFloor,Zr as decideDurableAttach,pa as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,vr as deleteStreamRun,Sr as depKey,ao as diffExternalSource,Yt as diffGlobalMembership,at as distinctValues,h as encodeAggregateKey,da as encodeCursor,_o as encodeGeohash,_a as encodePartitionKey,Jt as encodeRowsPatch,y as ensureAuditTable,$o as ensureMailTable,eo as envOptionalPositiveInt,ro as envPositiveInt,o as exportShardRows,a as exportShardTable,qo as facetColumn,tt as fanOutScalarCounts,wo as findStorageReferences,Wr as finishStreamRun,E as foldAggregateTally,Rt as gateReplicaDispatch,Ir as geoTableName,Vt as globalShapeReadKey,yt as guardWriter,At as handleReplicaControl,bn as hasTrigger,Io as haversineMeters,We as hydrateDocsById,t as importShardRows,za as indexKeysForRow,Kt as isDevEnvironment,br as isFtsAvailable,ha as isLossyBody,qe as isMemoryTable,$a as isRelationPredicate,fo as isSoftDeleted,xo as isSourceDue,Lr as jsonPath,Mr as jsonPathSql,Va as keysTouchRanges,no as liftSourceId,ln as lintReadonlySql,ka as listReactorStates,Ko as listTables,Nn as literalInList,Wa as markUnvouchableReads,Ia as matchesRankStaticWhere,d as matchesStaticWhere,mo as materializeExternalRows,co as materializeExternalRowsIncremental,we as memoryTableNames,fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Hr as migrateDurableStreams,Me as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ba as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,pt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Sa as normalizeOrderKeys,lo as normalizeSourceDocument,so as normalizeSourceValue,kr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,bo as pointInBoundingBox,Zt as projectColumns,To as pullExternalSourceIncrementalTick,ho as pullExternalSourceTick,Pr as qualifiedJsonPath,Dr as qualifiedJsonPathSql,qn as quoteIdentifier,ba as rankKeyFromDoc,La as rankTableName,Na as reactiveCacheKey,Ga as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,la as readBookmark,ea as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,po as readExternalSourceBaseline,Pe as readGlobalShapeSnapshot,Fe as readIdempotent,ir as readMigrationStatus,Ea as readQueueMessageById,Ca as readQueueMessages,Ua as readReactorState,Ft as readSchemaHistory,kt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,Xr as readStreamChunks,zr as readStreamRun,vo as readTablePage,ra as recordCapturedMail,xn as recordChangedKeys,Wo as recordFanoutPass,Ho as recordGlobalPollPass,Ra as recordQueueMessages,Bt as recordSchemaVersion,Xo as recordShapeProbePass,nt as relationHooks,dt as relayCountFor,Br as renderSql,bt as reprojectableFields,Gn as reprojectionMigrationId,Lt as reprojectionTables,Ma as resolveRankPartition,et as resolveRelationPredicates,lt as resolveWith,yr as rowToDocument,mr as runDataMigration,xr as runDrizzle,So as runExternalSourceTick,sn as runReadonlySql,st as runRowValidators,Kn as runShardMigrations,on as runSocketPool,Tr as runSql,Ln as runTriggers,Pn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,zo as selectMatchingIds,tr as selectShapeMembers,nr as selectShapeRows,Ut as serializeSqlValue,St as shapeRoutingKey,ua as softDeleteScope,Pa as sortColumnName,Gr as sqliteInList,Wn as stableStringify,Xn as stableWireKey,pn as subscriptionFrames,dn as subscriptionListDeltas,Vo as summarizeFanoutTopics,Qo as summarizeSubscriptions,Nr as tableColumns,ur as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,ke as trimIdempotent,Vr as trimStreamRuns,Or as tryRowToDocument,Sn as trySendFrame,Ur as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,qa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,Tn 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-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as h,encodeAggregateKey as T,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-XtEbp1DE.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as M,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-D5URxcDG.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-wsjTZz7k.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as he,COMMIT_SEQ_TABLE as Te,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-B4gOYjdz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Pe,readGlobalShapeSnapshot as Me,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as ke,trimIdempotent as Fe,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-CfDhzXMF.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or,writeShapePokeCursors as ar}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as nr,selectShapeRows as lr}from"./packem_shared/selectShapeMembers-Ce5Jr6UH.mjs";import{DATA_MIGRATION_STATE_TABLE as ir,readMigrationStatus as mr,runDataMigration as cr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs";import{SCAN_DEP as dr,createDependencyTracker as Sr,depKey as ur,tableFromDepKey as fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as hr,runSql as Tr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Cr,a as Rr,b as Ar,D as gr,c as _r,d as Ir,g as br,i as Lr,j as Pr,e as Mr,q as Dr,f as yr,r as Nr,t as Or,h as kr}from"./packem_shared/do-sql-DqQTxsj_.mjs";import{param as Br,renderSql as Gr,sqliteInList as Ur,unionAll as qr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as Kr,claimStreamRun as vr,deleteStreamRun as Wr,finishStreamRun as Hr,migrateDurableStreams as Xr,readStreamChunks as zr,readStreamRun as Vr,trimStreamRuns as Qr}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as Yr,MAX_DURABLE_STREAM_BYTES as Jr,MAX_DURABLE_STREAM_CHUNKS as Zr,decideDurableAttach as $r}from"./packem_shared/DurableStreamRunner-cq7kMv9M.mjs";import{envOptionalPositiveInt as ro,envPositiveInt as oo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as to}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as lo,normalizeSourceDocument as so,normalizeSourceValue as io}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as co,materializeExternalRowsIncremental as po,readExternalSourceBaseline as So,runExternalSourceTick as uo}from"./packem_shared/materializeExternalRows-DmSW2ujk.mjs";import{isSoftDeleted as xo,isSourceDue as ho,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as Eo}from"./packem_shared/isSoftDeleted-DvUFsJE9.mjs";import{GEO_DEFAULT_PRECISION as Ro,boundingBoxCenter as Ao,boundingBoxGeohashes as go,coveringGeohashes as _o,encodeGeohash as Io,haversineMeters as bo,pointInBoundingBox as Lo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as yo,ADMIN_FUNCTION_PREFIX as No,DEFAULT_FANOUT_TOPIC_LIMIT as Oo,FLAGS_FUNCTION_PREFIX as ko,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as Bo,createFanoutCounters as Go,createGlobalPollCounters as Uo,createShapeProbeCounters as qo,facetColumn as wo,findStorageReferences as Ko,listTables as vo,readTablePage as Wo,recordFanoutPass as Ho,recordGlobalPollPass as Xo,recordShapeProbePass as zo,selectMatchingIds as Vo,summarizeFanoutTopics as Qo,summarizeSubscriptions as jo}from"./packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs";import{MAIL_RETENTION as Jo,MAIL_TABLE as Zo,clearCapturedMail as $o,ensureMailTable as ea,readCapturedMail as ra,recordCapturedMail as oa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ta}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as la,readBookmark as sa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ma,buildSeekBeforeWhere as ca,buildSeekWhere as pa,decodeCursor as da,encodeCursor as Sa,normalizeOrderKeys as ua,softDeleteScope as fa}from"./packem_shared/applySelect-gwCG8hQF.mjs";import{QUEUE_TABLE as ha,clearQueueMessages as Ta,isLossyBody as Ea,readQueueMessageById as Ca,readQueueMessages as Ra,recordQueueMessages as Aa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as _a,encodePartitionKey as Ia,matchesRankStaticWhere as ba,rankKeyFromDoc as La,rankTableName as Pa,resolveRankPartition as Ma,sortColumnName as Da}from"./packem_shared/RANK_TIEBREAK-DBzb8aDX.mjs";import{ReactiveCache as Na,reactiveCacheKey as Oa}from"./packem_shared/ReactiveCache-gcV_jBm2.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as Ba,migrateReactorState as Ga,reactorNeedsRun as Ua,readReactorState as qa,writeReactorState as wa}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as va,createReadFootprint as Wa,markUnvouchableReads as Ha}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as za,indexKeysForRow as Va,keysTouchRanges as Qa}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ya,assertFlatPredicate as Ja,assertShapeShardable as Za,containsRelationPredicate as $a,isRelationPredicate as et,resolveRelationPredicates as rt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Bbyb7_rO.mjs";import{applyOnDelete as at,distinctValues as tt,fanOutScalarCounts as nt,relationHooks as lt,resolveWith as st,runRowValidators as it}from"./packem_shared/applyOnDelete-VGMOvm-o.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ct,clampPromotionThresholds as pt,nextPromotionState as dt,relayCountFor as St,shapeRoutingKey as ut}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BDnVpbQ9.mjs";import{DEFAULT_MAX_RELAYS as xt,OwnerRelay as ht,RelayMember as Tt,createRelayLink as Et}from"./packem_shared/DEFAULT_MAX_RELAYS-4Lslx8Qu.mjs";import{createReplicaLink as Rt,gateReplicaDispatch as At,handleReplicaControl as gt}from"./packem_shared/createReplicaLink-GrknD9FY.mjs";import{buildReprojectionMigration as It,countLegacyRows as bt,reprojectableFields as Lt,reprojectionTables as Pt}from"./packem_shared/buildReprojectionMigration-DcEoW2QQ.mjs";import{RLS_UNWRAP_SYMBOL as Dt,RlsRequiredError as yt,guardWriter as Nt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as kt,readSchemaHistory as Ft,readSchemaVersion as Bt,recordSchemaVersion as Gt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as qt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Kt,isDevEnvironment as vt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Ht}from"./packem_shared/buildShapeDiff-DEPp9Rbv.mjs";import{ShapeDiffCache as zt,createShapeDiffCache as Vt,globalShapeReadKey as Qt}from"./packem_shared/ShapeDiffCache-DLBPMAaA.mjs";import{buildPokeFrames as Yt,diffGlobalMembership as Jt,encodeRowsPatch as Zt,projectColumns as $t}from"./packem_shared/buildPokeFrames-BvgtmTHk.mjs";import{ShardRunner as rn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as an}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as nn,assertReadonly as ln,lintReadonlySql as sn,runReadonlySql as mn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as pn,subscriptionFrames as dn,subscriptionListDeltas as Sn,trySendFrame as un}from"./packem_shared/awaitWsDrain-BpfFOTSS.mjs";import{mergeChangedKeys as xn,recordChangedKeys as hn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Cn}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as An}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _n,TransactionHeadroomTracker as In}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Ln,runTriggers as Pn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Dn}from"./packem_shared/selectExpiredIds-rvmKjueQ.mjs";import{c as Nn,l as On}from"./packem_shared/where-sql-DxCbgqDJ.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Gn,reprojectionMigrationId as Un}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as wn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vn}from"./packem_shared/runShardMigrations-C4bvso2W.mjs";import{stableStringify as Hn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as zn}from"./packem_shared/stableWireKey-BC6DtQic.mjs";export{yo as ADMIN_FUNCTIONS,No as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Cr as AGG_COUNT,Rr as AGG_KEY,Ar as AGG_VALUE,M as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,he as COMMIT_SEQ_FIELD,Te as COMMIT_SEQ_TABLE,An as ConflictError,A as CountRlsUnsupportedError,ir as DATA_MIGRATION_STATE_TABLE,Oo as DEFAULT_FANOUT_TOPIC_LIMIT,Ya as DEFAULT_MAX_RELATION_KEYS,xt as DEFAULT_MAX_RELAYS,ct as DEFAULT_PROMOTION_THRESHOLDS,_n as DEFAULT_TRANSACTION_LIMITS,gr as DOC_COLUMN,Yr as DurableStreamRunner,ko as FLAGS_FUNCTION_PREFIX,Ro as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Jo as MAIL_RETENTION,Zo as MAIL_TABLE,Jr as MAX_DURABLE_STREAM_BYTES,Zr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,nn as MAX_SQL_ROWS,ta as NotFoundError,k as NotUniqueError,ht as OwnerRelay,ha as QUEUE_TABLE,_a as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,Bo as RELATION_FUNCTION_PREFIX,Gn as REPROJECTION_MIGRATION_PREFIX,Dt as RLS_UNWRAP_SYMBOL,Na as ReactiveCache,Tt as RelayMember,yt as RlsRequiredError,dr as SCAN_DEP,kt as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,zt as ShapeDiffCache,rn as ShardRunner,In as TransactionHeadroomTracker,va as UNVOUCHABLE_DEP,Se as advanceClientWatermark,_r as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,Kr as appendStreamChunk,Q as applyCdcChanges,at as applyOnDelete,ma as applySelect,la as armRestore,Ja as assertFlatPredicate,ln as assertReadonly,Za as assertShapeShardable,F as assertValidClientId,pn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ao as boundingBoxCenter,go as boundingBoxGeohashes,za as buildIndexRange,Yt as buildPokeFrames,It as buildReprojectionMigration,ca as buildSeekBeforeWhere,pa as buildSeekWhere,Kt as buildSettings,Ht as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,vr as claimStreamRun,pt as clampPromotionThresholds,$o as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,Nn as compileWhereSql,ve as computeRankPage,$a as containsRelationPredicate,bt as countLegacyRows,_o as coveringGeohashes,ge as createCompanionSync,Sr as createDependencyTracker,Go as createFanoutCounters,Uo as createGlobalPollCounters,Ir as createIndexSql,Wa as createReadFootprint,Et as createRelayLink,Rt as createReplicaLink,Vt as createShapeDiffCache,qo as createShapeProbeCounters,B as createShardCtxDb,Cn as createSystemReader,re as cursorBelowRetainedFloor,$r as decideDurableAttach,da as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,Wr as deleteStreamRun,ur as depKey,to as diffExternalSource,Jt as diffGlobalMembership,tt as distinctValues,T as encodeAggregateKey,Sa as encodeCursor,Io as encodeGeohash,Ia as encodePartitionKey,Zt as encodeRowsPatch,y as ensureAuditTable,ea as ensureMailTable,ro as envOptionalPositiveInt,oo as envPositiveInt,o as exportShardRows,a as exportShardTable,wo as facetColumn,nt as fanOutScalarCounts,Ko as findStorageReferences,Hr as finishStreamRun,E as foldAggregateTally,At as gateReplicaDispatch,br as geoTableName,Qt as globalShapeReadKey,Nt as guardWriter,gt as handleReplicaControl,Ln as hasTrigger,bo as haversineMeters,We as hydrateDocsById,t as importShardRows,Va as indexKeysForRow,vt as isDevEnvironment,Lr as isFtsAvailable,Ea as isLossyBody,qe as isMemoryTable,et as isRelationPredicate,xo as isSoftDeleted,ho as isSourceDue,Pr as jsonPath,Mr as jsonPathSql,Qa as keysTouchRanges,lo as liftSourceId,sn as lintReadonlySql,Ba as listReactorStates,vo as listTables,On as literalInList,Ha as markUnvouchableReads,ba as matchesRankStaticWhere,d as matchesStaticWhere,co as materializeExternalRows,po as materializeExternalRowsIncremental,we as memoryTableNames,xn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Xr as migrateDurableStreams,Pe as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ga as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,dt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,ua as normalizeOrderKeys,so as normalizeSourceDocument,io as normalizeSourceValue,Br as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Lo as pointInBoundingBox,$t as projectColumns,To as pullExternalSourceIncrementalTick,Eo as pullExternalSourceTick,Dr as qualifiedJsonPath,yr as qualifiedJsonPathSql,wn as quoteIdentifier,La as rankKeyFromDoc,Pa as rankTableName,Oa as reactiveCacheKey,Ua as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,sa as readBookmark,ra as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,So as readExternalSourceBaseline,Me as readGlobalShapeSnapshot,ke as readIdempotent,mr as readMigrationStatus,Ca as readQueueMessageById,Ra as readQueueMessages,qa as readReactorState,Ft as readSchemaHistory,Bt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,zr as readStreamChunks,Vr as readStreamRun,Wo as readTablePage,oa as recordCapturedMail,hn as recordChangedKeys,Ho as recordFanoutPass,Xo as recordGlobalPollPass,Aa as recordQueueMessages,Gt as recordSchemaVersion,zo as recordShapeProbePass,lt as relationHooks,St as relayCountFor,Gr as renderSql,Lt as reprojectableFields,Un as reprojectionMigrationId,Pt as reprojectionTables,Ma as resolveRankPartition,rt as resolveRelationPredicates,st as resolveWith,Nr as rowToDocument,cr as runDataMigration,hr as runDrizzle,uo as runExternalSourceTick,mn as runReadonlySql,it as runRowValidators,vn as runShardMigrations,an as runSocketPool,Tr as runSql,Pn as runTriggers,Dn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,Vo as selectMatchingIds,nr as selectShapeMembers,lr as selectShapeRows,qt as serializeSqlValue,ut as shapeRoutingKey,fa as softDeleteScope,Da as sortColumnName,Ur as sqliteInList,Hn as stableStringify,zn as stableWireKey,dn as subscriptionFrames,Sn as subscriptionListDeltas,Qo as summarizeFanoutTopics,jo as summarizeSubscriptions,Or as tableColumns,fr as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,Fe as trimIdempotent,Qr as trimStreamRuns,kr as tryRowToDocument,un as trySendFrame,qr as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,wa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,ar as writeShapePokeCursors,Tn as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-DbEszTyj.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",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,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:x(e,d(n))});return r},P=(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)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-DqQTxsj_.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-CDds5uQW.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",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,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:x(e,d(n))});return r},P=(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)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-
|
|
1
|
+
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-DqQTxsj_.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-CDds5uQW.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as T}from"./runDrizzle-
|
|
1
|
+
import{runSql as T}from"./runDrizzle-2ULFQR_k.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
op TEXT NOT NULL,
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as p,l as q}from"./do-sql-DqQTxsj_.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${f(c)} (ts, ${f("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,O="__cdc_log_table_seq",y=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},g=(e,o,r,i,s,d)=>{const E=d===void 0?null:p(d);A(e,N,o,r,i,s,E)},S=90,L=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=L(o.tables),E=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const C={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?C:{...C,doc:q(a.doc)}});return{changes:E,cursor:E.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=S){const d=new Set(i.slice(s,s+S));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${L(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),B=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq FROM ${t.identifier(c)}
|
|
9
|
+
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
|
+
GROUP BY id
|
|
11
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>({id:d.id,op:d.op,seq:d.maxSeq})),v=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
|
|
12
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
|
+
)`)},x=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
|
|
14
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
+
)`)},W=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},Y=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},P=(e,o)=>e!==void 0&&e>o+1,G=(e,o,r)=>new m("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,K=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",u=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{u(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{u(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const s={...r};delete s._id,await e.replace(o.id,s,void 0,{allowExplicitId:!0})}},k=async(e,o)=>{for(const r of o)await h(e,r)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,O as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,g as appendCdcChange,k as applyCdcChanges,V as bumpCdcEpoch,B as cdcCanVouchFor,W as cdcSeqLeavingRows,X as cdcTouchesTables,G as cdcTrimmedError,x as compactCdcDocs,P as cursorBelowRetainedFloor,y as migrateCdcLog,u as migrateCdcMeta,K as minCdcReplayableSeq,$ as minCdcSeq,H as readCdcChangeKeys,U as readCdcChanges,Y as readCdcCursor,z as readCdcEpoch,v as trimCdcChanges};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
2
|
identity TEXT NOT NULL,
|
|
3
3
|
client_id TEXT NOT NULL,
|
|
4
4
|
last_mutation_id INTEGER NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-2ULFQR_k.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 0),
|
|
3
3
|
value INTEGER NOT NULL
|
|
4
4
|
)`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-2ULFQR_k.mjs";const n="__lunora_migrations",x=100,D=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
direction TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-VGMOvm-o.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BPv7jVgK.mjs → DEFAULT_MAX_RELAYS-4Lslx8Qu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-BU9T2xJ7.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-BhYUbqzO.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CeaR5jj8.mjs";import{stableWireKey as f}from"./stableWireKey-DSCJB6E7.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
1
|
+
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-CDds5uQW.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-C93UQ7LV.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-BDnVpbQ9.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-BvgtmTHk.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-BpfFOTSS.mjs";import{stableWireKey as f}from"./stableWireKey-BC6DtQic.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-BC6DtQic.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
package/dist/packem_shared/{DurableStreamRunner-DDBi1UXj.mjs → DurableStreamRunner-cq7kMv9M.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-CDds5uQW.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{y(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-2ULFQR_k.mjs";const r="__global_shape_snapshot",T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
members TEXT NOT NULL,
|
package/dist/packem_shared/{IDEMPOTENCY_TABLE-DKVe2Ohf.mjs → IDEMPOTENCY_TABLE-DOpm_oMF.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
2
|
identity TEXT NOT NULL,
|
|
3
3
|
mutation_id TEXT NOT NULL,
|
|
4
4
|
result_json TEXT NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-
|
|
1
|
+
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-2ULFQR_k.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
|
|
2
2
|
… [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
captured_at INTEGER NOT NULL,
|