@lunora/shard-engine 1.0.0-alpha.51 → 1.0.0-alpha.52
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 +5 -16
- package/dist/index.d.ts +5 -16
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-oJ7IyZP6.mjs → ADMIN_FUNCTIONS-1OWiZgrN.mjs} +1 -1
- package/dist/packem_shared/AGG_COUNT-gkJ8xtVW.mjs +1 -0
- package/dist/packem_shared/{sql-projection-BqmxFxQU.mjs → BIGINT_KEY_DIGITS-Djq7G5Xx.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-gl0FuepJ.mjs → CDC_LOG_TABLE-Cva29kfS.mjs} +4 -4
- package/dist/packem_shared/{CURSOR_PREFIX-CoJUQfCI.mjs → CURSOR_PREFIX-B1i1J8Zi.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BHzhEE-y.mjs → DATA_MIGRATION_STATE_TABLE-Jrx6cqEc.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BbmpfQE4.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CH446J5m.mjs → DEFAULT_MAX_RELAYS-BVaTptvb.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs → DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs → DEFAULT_TRANSACTION_LIMITS-D_gjjTFo.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-C3NUyv3s.mjs → DurableStreamRunner-Ds3cmo3F.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-C7gJLEay.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-D157XEqw.mjs → RANK_TIEBREAK-BXD4YaG3.mjs} +1 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CepZvBVl.mjs +1 -0
- package/dist/packem_shared/{ReactiveCache-BngdZxr9.mjs → ReactiveCache-CwSgH_wK.mjs} +1 -1
- package/dist/packem_shared/{ShapeDiffCache-CLm5XXd1.mjs → ShapeDiffCache-BmVH30dI.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-CGi8gxeK.mjs → aggregateTableName-CCCIulmn.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-BOOJzpbw.mjs → applyOnDelete-CeHLU-Hh.mjs} +1 -1
- package/dist/packem_shared/{awaitWsDrain-CjWMVZOG.mjs → awaitWsDrain-BqSGNI0W.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-BCmY3OYO.mjs +1 -0
- package/dist/packem_shared/{buildPokeFrames-C8km3IhJ.mjs → buildPokeFrames-CySyxldi.mjs} +1 -1
- package/dist/packem_shared/buildReprojectionMigration-D-9DU7D2.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-BW5lKBzQ.mjs → buildShapeDiff-C-jrV9kY.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-BB1JlUhC.mjs → compileWhereSql-ByHAmOE-.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-BH2rv2mc.mjs → computeRankPage-CuWuhRZN.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-DlYfWB_e.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-DujqFlHs.mjs → createReplicaLink-COCkDNMK.mjs} +1 -1
- package/dist/packem_shared/ctx-db-companions-CTabzjgb.mjs +1 -0
- package/dist/packem_shared/{ctx-db-relay-shapes-CnOeftkH.mjs → ctx-db-relay-shapes-B4bmET4W.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-B-fWLvpW.mjs → defineEngineContractSuite-BQBhgHJM.mjs} +1 -1
- package/dist/packem_shared/do-sql-qxXsaO03.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-D6KN5_7y.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-B6TNznFv.mjs → isSoftDeleted-cRWEfyMb.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DZPYRDXu.mjs → materializeExternalRows-DDXDqsGW.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-BqH93Q8t.mjs → runShardMigrations-DiCqfU82.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-D784Mqvh.mjs → selectExpiredIds-DHm7CSED.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-CLK9q18N.mjs → selectShapeMembers-CPdl1Ht1.mjs} +1 -1
- package/dist/packem_shared/serializeSqlValue-BBtrWwiu.mjs +1 -0
- package/dist/packem_shared/{stableWireKey-9bjKL5Gy.mjs → stableWireKey-CSJKu_ID.mjs} +1 -1
- package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +1 -0
- package/dist/packem_shared/wire-codec-UyQIjlyN.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/AGG_COUNT-JTc_jUaL.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-DucaxGnP.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-CTPj9dAd.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-CR2RSgJd.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Bo-oIkyU.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-BFBIVIOd.mjs +0 -1
- package/dist/packem_shared/do-sql-bkXQEBl8.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +0 -1
- package/dist/packem_shared/where-sql-4RHk2frP.mjs +0 -1
- package/dist/packem_shared/wire-codec-COhOSEe4.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BQBhgHJM.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -756,21 +756,6 @@ declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
|
756
756
|
json: string;
|
|
757
757
|
};
|
|
758
758
|
}) => void;
|
|
759
|
-
/**
|
|
760
|
-
* How far a search companion's backfill has progressed, and what the next pass
|
|
761
|
-
* should do about it.
|
|
762
|
-
*
|
|
763
|
-
* Neither stored analysis nor query policy, which is why it is its own module
|
|
764
|
-
* rather than a third responsibility bolted onto one of them: it is *progress*,
|
|
765
|
-
* the one piece of search state that is written as the index is built rather
|
|
766
|
-
* than decided when it is read.
|
|
767
|
-
*
|
|
768
|
-
* The policy below is shared because when each engine owned a copy they
|
|
769
|
-
* immediately disagreed about exactly the two cases that matter — whether a row
|
|
770
|
-
* with no recorded profile may be resumed (it may not; nothing says what
|
|
771
|
-
* analyzed it) and whether a never-started index is worth wiping (it is not;
|
|
772
|
-
* there is nothing in it).
|
|
773
|
-
*/
|
|
774
759
|
/**
|
|
775
760
|
* How far a companion's backfill has progressed, and under which analysis.
|
|
776
761
|
* Declared here rather than beside either engine's state table: both record the
|
|
@@ -2286,6 +2271,10 @@ interface SqlDiagnostic {
|
|
|
2286
2271
|
source: "gate" | "plan" | "syntax";
|
|
2287
2272
|
}
|
|
2288
2273
|
declare const lintReadonlySql: (sql: SqlExec, query: string) => SqlLintResult;
|
|
2274
|
+
declare const BIGINT_KEY_DIGITS = 39;
|
|
2275
|
+
declare const NEGATIVE = "0";
|
|
2276
|
+
declare const NON_NEGATIVE = "1";
|
|
2277
|
+
declare const bigintSqlKey: (value: bigint) => string;
|
|
2289
2278
|
declare const subscriptionListDeltas: (previousJson: string, nextResult: unknown, table: string, frames?: string[]) => MutationDelta[] | undefined;
|
|
2290
2279
|
interface FrameSink {
|
|
2291
2280
|
send: (data: string) => void;
|
|
@@ -2353,4 +2342,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2353
2342
|
}
|
|
2354
2343
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2355
2344
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2356
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2345
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, NEGATIVE as BIGINT_KEY_NEGATIVE, NON_NEGATIVE as BIGINT_KEY_NON_NEGATIVE, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -756,21 +756,6 @@ declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
|
756
756
|
json: string;
|
|
757
757
|
};
|
|
758
758
|
}) => void;
|
|
759
|
-
/**
|
|
760
|
-
* How far a search companion's backfill has progressed, and what the next pass
|
|
761
|
-
* should do about it.
|
|
762
|
-
*
|
|
763
|
-
* Neither stored analysis nor query policy, which is why it is its own module
|
|
764
|
-
* rather than a third responsibility bolted onto one of them: it is *progress*,
|
|
765
|
-
* the one piece of search state that is written as the index is built rather
|
|
766
|
-
* than decided when it is read.
|
|
767
|
-
*
|
|
768
|
-
* The policy below is shared because when each engine owned a copy they
|
|
769
|
-
* immediately disagreed about exactly the two cases that matter — whether a row
|
|
770
|
-
* with no recorded profile may be resumed (it may not; nothing says what
|
|
771
|
-
* analyzed it) and whether a never-started index is worth wiping (it is not;
|
|
772
|
-
* there is nothing in it).
|
|
773
|
-
*/
|
|
774
759
|
/**
|
|
775
760
|
* How far a companion's backfill has progressed, and under which analysis.
|
|
776
761
|
* Declared here rather than beside either engine's state table: both record the
|
|
@@ -2286,6 +2271,10 @@ interface SqlDiagnostic {
|
|
|
2286
2271
|
source: "gate" | "plan" | "syntax";
|
|
2287
2272
|
}
|
|
2288
2273
|
declare const lintReadonlySql: (sql: SqlExec, query: string) => SqlLintResult;
|
|
2274
|
+
declare const BIGINT_KEY_DIGITS = 39;
|
|
2275
|
+
declare const NEGATIVE = "0";
|
|
2276
|
+
declare const NON_NEGATIVE = "1";
|
|
2277
|
+
declare const bigintSqlKey: (value: bigint) => string;
|
|
2289
2278
|
declare const subscriptionListDeltas: (previousJson: string, nextResult: unknown, table: string, frames?: string[]) => MutationDelta[] | undefined;
|
|
2290
2279
|
interface FrameSink {
|
|
2291
2280
|
send: (data: string) => void;
|
|
@@ -2353,4 +2342,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2353
2342
|
}
|
|
2354
2343
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2355
2344
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2356
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2345
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, NEGATIVE as BIGINT_KEY_NEGATIVE, NON_NEGATIVE as BIGINT_KEY_NON_NEGATIVE, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-4Xezo8F6.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as m,matchesStaticWhere as p,normalizeCountArgument as d,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-CGi8gxeK.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as M,ensureAuditTable as D,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as k,assertNoExplicitUndefined as y,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DucaxGnP.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as v,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-CTPj9dAd.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-gl0FuepJ.mjs";import{archiveCdcSegment as de,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-BFBIVIOd.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as ke,readGlobalShapeSnapshot as ye,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as we,trimIdempotent as qe,writeIdempotent as ve}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-BH2rv2mc.mjs";import{SEARCH_STATE_TABLE as Ye,migrateSearchState as Je,readSearchBackfillState as Ze,writeSearchBackfillState as $e}from"./packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as mr,selectShapeRows as pr}from"./packem_shared/selectShapeMembers-CLK9q18N.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BHzhEE-y.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as Mr,d as Dr,g as Nr,i as Or,j as kr,e as yr,q as Fr,f as Br,r as Gr,t as Ur,h as wr}from"./packem_shared/do-sql-bkXQEBl8.mjs";import{param as vr,renderSql as Kr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as jr,migrateDurableStreams as Yr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-C3NUyv3s.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-DZPYRDXu.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-B6TNznFv.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as No,pointInBoundingBox as Oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as yo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as wo,MAX_PAGE_SIZE as qo,RELATION_FUNCTION_PREFIX as vo,createFanoutCounters as Ko,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as jo,recordGlobalPollPass as Yo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-oJ7IyZP6.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as pa,readBookmark as da}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as Aa}from"./packem_shared/CURSOR_PREFIX-CoJUQfCI.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Pa,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as Oa,matchesRankStaticWhere as ka,rankKeyFromDoc as ya,rankTableName as Fa,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-D157XEqw.mjs";import{ReactiveCache as wa,reactiveCacheKey as qa}from"./packem_shared/ReactiveCache-BngdZxr9.mjs";import{REACTOR_STATE_TABLE as Ka,listReactorStates as Wa,migrateReactorState as Xa,reactorNeedsRun as Ha,readReactorState as za,writeReactorState as Va}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ya,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as st,resolveRelationPredicates as lt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs";import{applyOnDelete as mt,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-BOOJzpbw.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as xt,clampPromotionThresholds as Ct,nextPromotionState as Tt,relayCountFor as Et,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs";import{DEFAULT_MAX_RELAYS as gt,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-CH446J5m.mjs";import{createReplicaLink as Pt,gateReplicaDispatch as Mt,handleReplicaControl as Dt}from"./packem_shared/createReplicaLink-DujqFlHs.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as kt,reprojectableFields as yt,reprojectionTables as Ft}from"./packem_shared/buildReprojectionMigration-CR2RSgJd.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Kt,readSchemaVersion as Wt,recordSchemaVersion as Xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as zt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Qt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-BW5lKBzQ.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-CLm5XXd1.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as sn}from"./packem_shared/buildPokeFrames-C8km3IhJ.mjs";import{ShardRunner as cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as hn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Cn,subscriptionFrames as Tn,subscriptionListDeltas as En,trySendFrame as Rn}from"./packem_shared/awaitWsDrain-CjWMVZOG.mjs";import{mergeChangedKeys as gn,recordChangedKeys as _n,writeTouchesMemo as In}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Ln}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Nn,TransactionHeadroomTracker as On}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as yn,runTriggers as Fn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Gn}from"./packem_shared/selectExpiredIds-D784Mqvh.mjs";import{c as wn,l as qn}from"./packem_shared/where-sql-4RHk2frP.mjs";import{RELATION_EXISTS_KEY as Kn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Xn,reprojectionMigrationId as Hn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Vn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as jn}from"./packem_shared/runShardMigrations-BqH93Q8t.mjs";import{stableStringify as Jn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as $n}from"./packem_shared/stableWireKey-9bjKL5Gy.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,Mn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,gt as DEFAULT_MAX_RELAYS,xt as DEFAULT_PROMOTION_THRESHOLDS,Nn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,wo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,yo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,qo as MAX_PAGE_SIZE,Sn as MAX_SQL_ROWS,ca as NotFoundError,k as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,Ka as REACTOR_STATE_TABLE,Kn as RELATION_EXISTS_KEY,vo as RELATION_FUNCTION_PREFIX,Xn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,Ye as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,cn as ShardRunner,On as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,m as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,mt as applyOnDelete,fa as applySelect,de as archiveCdcSegment,pa as armRestore,tt as assertFlatPredicate,y as assertNoExplicitUndefined,un as assertReadonly,nt as assertShapeShardable,F as assertValidClientId,Cn as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,v as backfillSearchIndexes,K as backfillSearchIndexesForTable,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Qt as buildSettings,Jt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Ct as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,wn as compileWhereSql,Ve as computeRankPage,it as containsRelationPredicate,kt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,Ko as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ya as createReadFootprint,bt as createRelayLink,Pt as createReplicaLink,en as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Ln as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Ca as decodeCursor,Ne as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,co as diffExternalSource,tn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,Oa as encodePartitionKey,nn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,dt as fanOutScalarCounts,zo as findStorageReferences,jr as finishStreamRun,C as foldAggregateTally,Mt as gateReplicaDispatch,Nr as geoTableName,rn as globalShapeReadKey,wt as guardWriter,Dt as handleReplicaControl,yn as hasTrigger,No as haversineMeters,a as importShardRows,et as indexKeysForRow,jt as isDevEnvironment,Or as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,st as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,kr as jsonPath,yr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,Vo as listTables,qn as literalInList,Ja as markUnvouchableReads,ka as matchesRankStaticWhere,p as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,gn as mergeChangedKeys,A as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,Yr as migrateDurableStreams,ke as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Xa as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Tt as nextPromotionState,d as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,vr as param,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Oo as pointInBoundingBox,sn as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Vn as quoteIdentifier,ya as rankKeyFromDoc,Fa as rankTableName,qa as reactiveCacheKey,Ha as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,da as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,ce as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ye as readGlobalShapeSnapshot,we as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,za as readReactorState,Kt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,_n as recordChangedKeys,jo as recordFanoutPass,Yo as recordGlobalPollPass,Ma as recordQueueMessages,Xt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Et as relayCountFor,Kr as renderSql,yt as reprojectableFields,Hn as reprojectionMigrationId,Ft as reprojectionTables,Ba as resolveRankPartition,Qe as resolveRankSeekTuple,lt as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,To as runExternalSourceTick,hn as runReadonlySql,ft as runRowValidators,jn as runShardMigrations,pn as runSocketPool,gr as runSql,Fn as runTriggers,Gn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,mr as selectShapeMembers,pr as selectShapeRows,zt as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,Jn as stableStringify,$n as stableWireKey,Tn as subscriptionFrames,En as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,Aa as tiebreakDirectionFor,me as trimCdcChanges,qe as trimIdempotent,$r as trimStreamRuns,wr as tryRowToDocument,Rn as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,ve as writeIdempotent,Va as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,In as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-4Xezo8F6.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as p,normalizeCountArgument as d,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as x}from"./packem_shared/aggregateTableName-CCCIulmn.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as P,ensureAuditTable as M,readAuditLog as D}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C7gJLEay.mjs";import{backfillAggregateIndexes as K,backfillRankIndexes as q,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BCmY3OYO.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as H,appendCdcChange as z,applyCdcChanges as Y,bumpCdcEpoch as Q,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as le,readCdcCursor as se,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-Cva29kfS.mjs";import{archiveCdcSegment as de,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as he,advanceClientWatermark as Ee,migrateClientWatermark as xe,readClientWatermark as Ce}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Ne}from"./packem_shared/ctx-db-companions-CTabzjgb.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Me,deleteGlobalShapeSnapshot as De,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as ye,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as Ke,trimIdempotent as qe,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Ve,memoryTableNames as Xe}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as ze,resolveRankSeekTuple as Ye}from"./packem_shared/computeRankPage-CuWuhRZN.mjs";import{SEARCH_STATE_TABLE as je,migrateSearchState as Je,readSearchBackfillState as Ze,writeSearchBackfillState as $e}from"./packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as lr,writeShapePokeCursors as sr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as cr,selectShapeRows as pr}from"./packem_shared/selectShapeMembers-CPdl1Ht1.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-Jrx6cqEc.mjs";import{SCAN_DEP as hr,createDependencyTracker as Er,depKey as xr,tableFromDepKey as Cr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Nr,c as Pr,d as Mr,g as Dr,i as Or,j as yr,e as kr,q as Fr,f as Br,r as Gr,t as Ur,h as Kr}from"./packem_shared/do-sql-qxXsaO03.mjs";import{param as wr,renderSql as vr,sqliteInList as Wr,unionAll as Vr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as Hr,claimStreamRun as zr,deleteStreamRun as Yr,finishStreamRun as Qr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-Ds3cmo3F.mjs";import{envOptionalPositiveInt as io,envPositiveInt as lo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as To,materializeExternalRowsIncremental as ho,readExternalSourceBaseline as Eo,runExternalSourceTick as xo}from"./packem_shared/materializeExternalRows-DDXDqsGW.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-cRWEfyMb.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as No,coveringGeohashes as Po,encodeGeohash as Mo,haversineMeters as Do,pointInBoundingBox as Oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ko}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as Ko,MAX_PAGE_SIZE as qo,RELATION_FUNCTION_PREFIX as wo,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Vo,facetColumn as Xo,findStorageReferences as Ho,listTables as zo,readTablePage as Yo,recordFanoutPass as Qo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-1OWiZgrN.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as la}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as pa,readBookmark as da}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as Ta,buildSeekWhere as ha,decodeCursor as Ea,encodeCursor as xa,normalizeOrderKeys as Ca,softDeleteScope as Ra,tiebreakDirectionFor as Aa}from"./packem_shared/CURSOR_PREFIX-B1i1J8Zi.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Na,recordQueueMessages as Pa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Da,encodePartitionKey as Oa,matchesRankStaticWhere as ya,rankKeyFromDoc as ka,rankTableName as Fa,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-BXD4YaG3.mjs";import{ReactiveCache as Ka,reactiveCacheKey as qa}from"./packem_shared/ReactiveCache-CwSgH_wK.mjs";import{REACTOR_STATE_TABLE as va,listReactorStates as Wa,migrateReactorState as Va,reactorNeedsRun as Xa,readReactorState as Ha,writeReactorState as za}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Qa,createReadFootprint as ja,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as lt,resolveRelationPredicates as st}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BbmpfQE4.mjs";import{applyOnDelete as ct,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-CeHLU-Hh.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ht,clampPromotionThresholds as Et,nextPromotionState as xt,relayCountFor as Ct,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs";import{DEFAULT_MAX_RELAYS as gt,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-BVaTptvb.mjs";import{createReplicaLink as Nt,gateReplicaDispatch as Pt,handleReplicaControl as Mt}from"./packem_shared/createReplicaLink-COCkDNMK.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as yt,reprojectableFields as kt,reprojectionTables as Ft}from"./packem_shared/buildReprojectionMigration-D-9DU7D2.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as Kt}from"./packem_shared/RLS_UNWRAP_SYMBOL-CepZvBVl.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wt,readSchemaHistory as vt,readSchemaVersion as Wt,recordSchemaVersion as Vt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Ht}from"./packem_shared/serializeSqlValue-BBtrWwiu.mjs";import{buildSettings as Yt,isDevEnvironment as Qt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-C-jrV9kY.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-BmVH30dI.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as ln}from"./packem_shared/buildPokeFrames-CySyxldi.mjs";import{ShardRunner as mn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as Tn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{BIGINT_KEY_DIGITS as En,BIGINT_KEY_NEGATIVE as xn,BIGINT_KEY_NON_NEGATIVE as Cn,bigintSqlKey as Rn}from"./packem_shared/BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import{awaitWsDrain as gn,subscriptionFrames as _n,subscriptionListDeltas as In,trySendFrame as bn}from"./packem_shared/awaitWsDrain-BqSGNI0W.mjs";import{mergeChangedKeys as Nn,recordChangedKeys as Pn,writeTouchesMemo as Mn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as On}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as kn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Bn,TransactionHeadroomTracker as Gn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_gjjTFo.mjs";import{hasTrigger as Kn,runTriggers as qn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as vn}from"./packem_shared/selectExpiredIds-DHm7CSED.mjs";import{c as Vn,l as Xn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as zn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Qn,reprojectionMigrationId as jn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ei}from"./packem_shared/runShardMigrations-DiCqfU82.mjs";import{stableStringify as oi}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ti}from"./packem_shared/stableWireKey-CSJKu_ID.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,N as AUDIT_LOG_TABLE,En as BIGINT_KEY_DIGITS,xn as BIGINT_KEY_NEGATIVE,Cn as BIGINT_KEY_NON_NEGATIVE,V as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,H as CDC_META_TABLE,he as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,kn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,gt as DEFAULT_MAX_RELAYS,ht as DEFAULT_PROMOTION_THRESHOLDS,Bn as DEFAULT_TRANSACTION_LIMITS,Nr as DOC_COLUMN,ro as DurableStreamRunner,Ko as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,Me as GLOBAL_SHAPE_SNAPSHOT_TABLE,ko as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,qo as MAX_PAGE_SIZE,Sn as MAX_SQL_ROWS,ma as NotFoundError,y as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,Da as RANK_TIEBREAK,va as REACTOR_STATE_TABLE,zn as RELATION_EXISTS_KEY,wo as RELATION_FUNCTION_PREFIX,Qn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,Ka as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,hr as SCAN_DEP,wt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,mn as ShardRunner,Gn as TransactionHeadroomTracker,Qa as UNVOUCHABLE_DEP,Ee as advanceClientWatermark,Pr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,P as appendAuditEntry,z as appendCdcChange,Hr as appendStreamChunk,Y as applyCdcChanges,ct as applyOnDelete,fa as applySelect,de as archiveCdcSegment,pa as armRestore,tt as assertFlatPredicate,k as assertNoExplicitUndefined,un as assertReadonly,nt as assertShapeShardable,F as assertValidClientId,gn as awaitWsDrain,K as backfillAggregateIndexes,q as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,Rn as bigintSqlKey,Lo as boundingBoxCenter,No as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,Ot as buildReprojectionMigration,Ta as buildSeekBeforeWhere,ha as buildSeekWhere,Yt as buildSettings,Jt as buildShapeDiff,Q as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,zr as claimStreamRun,Et as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,Vn as compileWhereSql,ze as computeRankPage,it as containsRelationPredicate,yt as countLegacyRows,Po as coveringGeohashes,Ne as createCompanionSync,Er as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Mr as createIndexSql,ja as createReadFootprint,bt as createRelayLink,Nt as createReplicaLink,en as createShapeDiffCache,Vo as createShapeProbeCounters,B as createShardCtxDb,On as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Ea as decodeCursor,De as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Yr as deleteStreamRun,xr as depKey,mo as diffExternalSource,tn as diffGlobalMembership,pt as distinctValues,h as encodeAggregateKey,xa as encodeCursor,Mo as encodeGeohash,Oa as encodePartitionKey,nn as encodeRowsPatch,M as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,lo as envPositiveInt,o as exportShardRows,Xo as facetColumn,dt as fanOutScalarCounts,Ho as findStorageReferences,Qr as finishStreamRun,E as foldAggregateTally,Pt as gateReplicaDispatch,Dr as geoTableName,rn as globalShapeReadKey,Kt as guardWriter,Mt as handleReplicaControl,Kn as hasTrigger,Do as haversineMeters,a as importShardRows,et as indexKeysForRow,Qt as isDevEnvironment,Or as isFtsAvailable,ba as isLossyBody,Ve as isMemoryTable,lt as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,yr as jsonPath,kr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,zo as listTables,Xn as literalInList,Ja as markUnvouchableReads,ya as matchesRankStaticWhere,p as matchesStaticWhere,To as materializeExternalRows,ho as materializeExternalRowsIncremental,Xe as memoryTableNames,Nn as mergeChangedKeys,A as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,xe as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,ye as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Va as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,xt as nextPromotionState,d as normalizeCountArgument,G as normalizeIdStructurally,Ca as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,wr as param,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Oo as pointInBoundingBox,ln as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Zn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankTableName,qa as reactiveCacheKey,Xa as reactorNeedsRun,x as readAggregateValue,Se as readArchivedCdcChanges,D as readAuditLog,da as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,le as readCdcChanges,se as readCdcCursor,me as readCdcEpoch,Ce as readClientWatermark,be as readCommitSeq,Eo as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,Ke as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Na as readQueueMessages,Ha as readReactorState,vt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Yo as readTablePage,la as recordCapturedMail,Pn as recordChangedKeys,Qo as recordFanoutPass,jo as recordGlobalPollPass,Pa as recordQueueMessages,Vt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Ct as relayCountFor,vr as renderSql,kt as reprojectableFields,jn as reprojectionMigrationId,Ft as reprojectionTables,Ba as resolveRankPartition,Ye as resolveRankSeekTuple,st as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,xo as runExternalSourceTick,Tn as runReadonlySql,ft as runRowValidators,ei as runShardMigrations,pn as runSocketPool,gr as runSql,qn as runTriggers,vn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,pr as selectShapeRows,Ht as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,oi as stableStringify,ti as stableWireKey,_n as subscriptionFrames,In as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Cr as tableFromDepKey,S as throwingScheduler,Aa as tiebreakDirectionFor,ce as trimCdcChanges,qe as trimIdempotent,$r as trimStreamRuns,Kr as tryRowToDocument,bn as trySendFrame,Vr as unionAll,l as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,we as writeIdempotent,za as writeReactorState,$e as writeSearchBackfillState,lr as writeShapePokeCursor,sr as writeShapePokeCursors,Mn as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-bkXQEBl8.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-COhOSEe4.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-qxXsaO03.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-UyQIjlyN.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{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-qxXsaO03.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-UyQIjlyN.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BBtrWwiu.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 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},i=39,g="0",d="1",
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},i=39,g="0",d="1",E=n=>{const t=n<0n,r=(t?-n:n).toString();if(r.length>i)throw new c("BAD_REQUEST",`bigint ${n.toString()} has ${String(r.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const o=r.padStart(i,"0");return t?g+Array.from(o,f=>String(9-Number(f))).join(""):d+o},N=n=>typeof n=="bigint"?E(n):n instanceof ArrayBuffer?s(new Uint8Array(n)):ArrayBuffer.isView(n)?s(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)):void 0,m=n=>{const t=e(n);return t==="bigint"||t==="bytes"},b=n=>{const t=e(n);return m(n)||t==="any"||t==="union"||t==="from"};export{i as BIGINT_KEY_DIGITS,g as BIGINT_KEY_NEGATIVE,d as BIGINT_KEY_NON_NEGATIVE,E as bigintSqlKey,m as isProjectedKind,b as mayHoldProjectedValue,N as sqlComparableProjection};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as m,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as A,l as q}from"./do-sql-qxXsaO03.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
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${t.identifier("table")} TEXT NOT NULL,
|
|
5
5
|
id TEXT NOT NULL,
|
|
6
6
|
op TEXT NOT NULL,
|
|
7
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{}},
|
|
8
|
+
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},U=(e,o,r,i,s,d)=>{const a=d===void 0?null:A(d);m(e,N,o,r,i,s,a)},S=90,u=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,g=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=u(o.tables),a=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(E=>{const C={id:E.id,op:E.op,seq:E.seq,table:E.table,ts:E.ts};return E.doc===null?C:{...C,doc:q(E.doc)}});return{changes:a,cursor:a.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=S){const d=new Set(i.slice(s,s+S));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${u(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),B=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(c)}
|
|
9
9
|
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
10
|
GROUP BY id
|
|
11
|
-
ORDER BY maxSeq ASC`).toArray().map(d=>
|
|
11
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),v=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
|
|
12
12
|
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
13
|
)`)},x=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
|
|
14
14
|
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
-
)`)},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
|
|
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 p("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,K=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},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,U 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,L as migrateCdcMeta,K as minCdcReplayableSeq,$ as minCdcSeq,H as readCdcChangeKeys,g as readCdcChanges,Y as readCdcCursor,z as readCdcEpoch,v as trimCdcChanges};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-UyQIjlyN.mjs";const p="id",b=e=>e.at(-1)?.direction==="desc"?"desc":"asc",h=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(y.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=(e,t)=>{const n=[];for(const r of e??[])for(const[o,i]of Object.entries(r))n.push({direction:i,field:o,nullable:g(o,t)});return n.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:(n.some(r=>h.has(r.field)||r.field==="_creationTime")||n.push({direction:b(n),field:"_creationTime",nullable:!1}),n)},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},u="~3",C=(e,t)=>{const n=t.map(r=>e[r.field]??null);return n.push(e._id),u+O(JSON.stringify(E(n)))},d=()=>new _("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(u))throw d();let t;try{t=N(JSON.parse(T(e.slice(u.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,i=e.direction!=="desc"===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[o]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[o]:{isNull:!0}}]}},S=(e,t,n,r)=>{const o=e.some(l=>h.has(l.field))?e:[...e,{direction:b(e),field:p,nullable:!1}];if(t.length<o.length)throw d();const i=l=>{const a=o[l];if(a===void 0)throw d();const f=m(a,t[l],n,r&&l===o.length-1);return l===o.length-1?f:{OR:[f,{AND:[{[a.field]:{eq:t[l]}},i(l+1)]}]}},s=i(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?s:{AND:[m(c,t[0],n,!0),s]}},L=(e,t)=>S(e,t,!0,!1),k=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(o=>{const i={};for(const s of r)s in o&&(i[s]=o[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,v=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{u as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,L as buildSeekWhere,I as decodeCursor,C as encodeCursor,T as fromBase64,d as invalidCursor,v as isLiveForCompanion,A as normalizeOrderKeys,B as softDeleteScope,b as tiebreakDirectionFor,O as toBase64};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-CSJKu_ID.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{ConflictError as U}from"./ConflictError-C8GtJmjS.mjs";const c="__lunora_migrations",$=100,y=3e4,w=1e4,F=e=>{u(e,`CREATE TABLE IF NOT EXISTS "${c}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
direction TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-CeHLU-Hh.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CH446J5m.mjs → DEFAULT_MAX_RELAYS-BVaTptvb.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as M,LunoraError as k}from"@lunora/errors";import{e as T,d as I}from"./wire-codec-COhOSEe4.mjs";import{d as C,w as _,a as w,m as N,r as O,b as D,c as F}from"./ctx-db-relay-shapes-CnOeftkH.mjs";import{envPositiveInt as R}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as f,DEFAULT_PROMOTION_THRESHOLDS as v,nextPromotionState as U,shapeRoutingKey as b,relayProxyKey as E,parseRelayName as K,clampPromotionThresholds as W}from"./DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs";import{encodeRowsPatch as Y,buildPokeFrames as P}from"./buildPokeFrames-C8km3IhJ.mjs";import{v as B,R as A,s as H,a as $,b as j}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as z,trySendFrame as x}from"./awaitWsDrain-CjWMVZOG.mjs";import{stableWireKey as S}from"./stableWireKey-9bjKL5Gy.mjs";const G=2,X=8,g={},J=h=>{throw new k("INTERNAL",`unhandled relay frame: ${JSON.stringify(h)}`)},V=(h,e)=>h===void 0||h.epoch!==e.epoch?!1:h.cursor>=e.fromCursor&&h.cursor<e.checkpoint,q=h=>Response.json(h,{headers:{"content-type":"application/json"}}),p=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await B(this.host.env(),e.headers.get(A),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),p();case"relay_detach":return this.onDetach(s.relayIndex),p();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),p();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),p()}case"relay_shape_subscribe":return q(this.onShapeSubscribe({...s,args:I(s.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(s),p();default:return J(s)}}maxRelays(){return R(this.host.env(),"LUNORA_MAX_RELAYS",X)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return H(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=$(this.host.env());n!==void 0&&(o[A]=await j(n,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Q extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(f(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=R(this.host.env(),"LUNORA_RELAY_THRESHOLD",v.tUp),s=R(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",v.tDown);if(this.promotionState=U(this.promotionState,e,W(t,s)),this.promotionState==="owned")return 0;const r=R(this.host.env(),"LUNORA_RELAY_FAN",G);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=b(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onShapeUnsubscribe(e){const{proxies:t}=this.relayShapes(),s=e.subId===void 0?void 0:E(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of t)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(s===void 0||r===s)&&t.delete(r);C(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(f(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let n;try{n=this.host.resolveShape(e.name,e.args,t)}catch{return}if(n===void 0||n.global===!0||!s.has(n.table))return;const a=e,l=a.cursor,i=this.host.buildShapeDiff(n,l,r);if(i.length!==0)return a.cursor=r,_(this.host.sql(),a.key,r),{args:T(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:Y(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const l=this.buildShapePoke(a,g,e,t,o);l&&n.push(this.multicastToRelays(s,l,a))}await Promise.all(n)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(f(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of s.values()){const a=this.buildShapePoke(n,n.identity,e,t,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(f(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(c){const{body:u}=M(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:m}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const c=b(e.name,e.args);let u=d.get(c);u===void 0&&(u={args:e.args,cursor:o,key:c,name:e.name},d.set(c,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const c=E(e.relayIndex,e.connectionId,e.subId),u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:c,name:e.name,relayIndex:e.relayIndex};m.set(c,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=P([{reset:a,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:n,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),N(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of O(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);D(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),F(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=S(s.effectiveWhere),o=S(s.columns);let n=!1;const a=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,c)=>typeof c=="symbol"||c in y?Reflect.get(y,c):`${i}:${c}`,getOwnPropertyDescriptor:(y,c)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,c)),has:(y,c)=>typeof c=="symbol"?Reflect.has(y,c):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,a("a"),a("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&S(d.effectiveWhere)===r&&S(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Z extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:T(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},n=await this.requestRelayMessage(this.roleId.ownerKey,o);if(n===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let a;try{a=await n.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(a.error!==void 0)return a.error;if(a.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await z(e);for(const l of a.frames)x(e,l);return this.recordRelayShapeMemo(e,t,a.cursor??0,a.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,t){const{connectionId:s}=this.host.readAttachment(e);s===void 0||!this.canAddressSiblings()||await this.postRelayMessage(this.roleId.ownerKey,{connectionId:s,relayIndex:this.roleId.relayIndex,...t===void 0?{}:{subId:t},type:"relay_shape_unsubscribe"})}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=b(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:n}=o,a=this.shapeRelayMemos.get(r);if(!(n===void 0||a===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(n)){const d=a.get(l);if(b(i.name,i.args)!==t||!V(d,e))continue;const m=P([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of m)x(r,y);a.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const he=h=>{const e=h.doName();if(e===void 0)return;const t=K(e);return t===void 0?new Q(h,e):new Z(h,t.ownerKey,t.relayIndex)};export{X as DEFAULT_MAX_RELAYS,Q as OwnerRelay,Z as RelayMember,he as createRelayLink};
|
|
1
|
+
import{toErrorBody as M,LunoraError as k}from"@lunora/errors";import{e as T,d as I}from"./wire-codec-UyQIjlyN.mjs";import{d as C,w as _,a as w,m as N,r as O,b as D,c as F}from"./ctx-db-relay-shapes-B4bmET4W.mjs";import{envPositiveInt as R}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as f,DEFAULT_PROMOTION_THRESHOLDS as v,nextPromotionState as U,shapeRoutingKey as b,relayProxyKey as E,parseRelayName as K,clampPromotionThresholds as W}from"./DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs";import{encodeRowsPatch as Y,buildPokeFrames as P}from"./buildPokeFrames-CySyxldi.mjs";import{v as B,R as A,s as H,a as $,b as j}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as z,trySendFrame as x}from"./awaitWsDrain-BqSGNI0W.mjs";import{stableWireKey as S}from"./stableWireKey-CSJKu_ID.mjs";const G=2,X=8,g={},J=h=>{throw new k("INTERNAL",`unhandled relay frame: ${JSON.stringify(h)}`)},V=(h,e)=>h===void 0||h.epoch!==e.epoch?!1:h.cursor>=e.fromCursor&&h.cursor<e.checkpoint,q=h=>Response.json(h,{headers:{"content-type":"application/json"}}),p=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await B(this.host.env(),e.headers.get(A),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),p();case"relay_detach":return this.onDetach(s.relayIndex),p();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),p();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),p()}case"relay_shape_subscribe":return q(this.onShapeSubscribe({...s,args:I(s.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(s),p();default:return J(s)}}maxRelays(){return R(this.host.env(),"LUNORA_MAX_RELAYS",X)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return H(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=$(this.host.env());n!==void 0&&(o[A]=await j(n,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Q extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(f(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=R(this.host.env(),"LUNORA_RELAY_THRESHOLD",v.tUp),s=R(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",v.tDown);if(this.promotionState=U(this.promotionState,e,W(t,s)),this.promotionState==="owned")return 0;const r=R(this.host.env(),"LUNORA_RELAY_FAN",G);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=b(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onShapeUnsubscribe(e){const{proxies:t}=this.relayShapes(),s=e.subId===void 0?void 0:E(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of t)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(s===void 0||r===s)&&t.delete(r);C(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(f(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let n;try{n=this.host.resolveShape(e.name,e.args,t)}catch{return}if(n===void 0||n.global===!0||!s.has(n.table))return;const a=e,l=a.cursor,i=this.host.buildShapeDiff(n,l,r);if(i.length!==0)return a.cursor=r,_(this.host.sql(),a.key,r),{args:T(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:Y(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const l=this.buildShapePoke(a,g,e,t,o);l&&n.push(this.multicastToRelays(s,l,a))}await Promise.all(n)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(f(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of s.values()){const a=this.buildShapePoke(n,n.identity,e,t,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(f(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(c){const{body:u}=M(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:m}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const c=b(e.name,e.args);let u=d.get(c);u===void 0&&(u={args:e.args,cursor:o,key:c,name:e.name},d.set(c,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const c=E(e.relayIndex,e.connectionId,e.subId),u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:c,name:e.name,relayIndex:e.relayIndex};m.set(c,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=P([{reset:a,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:n,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),N(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of O(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);D(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),F(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=S(s.effectiveWhere),o=S(s.columns);let n=!1;const a=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,c)=>typeof c=="symbol"||c in y?Reflect.get(y,c):`${i}:${c}`,getOwnPropertyDescriptor:(y,c)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,c)),has:(y,c)=>typeof c=="symbol"?Reflect.has(y,c):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,a("a"),a("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&S(d.effectiveWhere)===r&&S(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Z extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:T(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},n=await this.requestRelayMessage(this.roleId.ownerKey,o);if(n===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let a;try{a=await n.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(a.error!==void 0)return a.error;if(a.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await z(e);for(const l of a.frames)x(e,l);return this.recordRelayShapeMemo(e,t,a.cursor??0,a.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,t){const{connectionId:s}=this.host.readAttachment(e);s===void 0||!this.canAddressSiblings()||await this.postRelayMessage(this.roleId.ownerKey,{connectionId:s,relayIndex:this.roleId.relayIndex,...t===void 0?{}:{subId:t},type:"relay_shape_unsubscribe"})}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=b(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:n}=o,a=this.shapeRelayMemos.get(r);if(!(n===void 0||a===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(n)){const d=a.get(l);if(b(i.name,i.args)!==t||!V(d,e))continue;const m=P([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of m)x(r,y);a.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const he=h=>{const e=h.doName();if(e===void 0)return;const t=K(e);return t===void 0?new Q(h,e):new Z(h,t.ownerKey,t.relayIndex)};export{X as DEFAULT_MAX_RELAYS,Q as OwnerRelay,Z as RelayMember,he as createRelayLink};
|
|
@@ -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-CSJKu_ID.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-D6KN5_7y.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
package/dist/packem_shared/{DurableStreamRunner-C3NUyv3s.mjs → DurableStreamRunner-Ds3cmo3F.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-UyQIjlyN.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|