@lunora/shard-engine 1.0.0-alpha.3 → 1.0.0-alpha.5
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 +28 -7
- package/dist/index.d.ts +28 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs +31 -0
- package/dist/packem_shared/NotUniqueError-C8DLoXSK.mjs +1 -0
- package/dist/packem_shared/{ReactiveCache-CF21t8IB.mjs → ReactiveCache-DSGtSVGZ.mjs} +1 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-BefTibvY.mjs → defineEngineContractSuite--yaJW9mT.mjs} +1 -1
- package/dist/packem_shared/{mergeChangedKeys-CvSHlkv-.mjs → mergeChangedKeys-BXtUgIPW.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +0 -31
- package/dist/packem_shared/NotUniqueError-iGKd9wRR.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DIjFVgeO.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite--yaJW9mT.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -359,9 +359,21 @@ interface GeoFilterBuilderLike {
|
|
|
359
359
|
};
|
|
360
360
|
}) => GeoFilterBuilderLike;
|
|
361
361
|
}
|
|
362
|
+
type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
|
|
363
|
+
interface GeoScoredDocument {
|
|
364
|
+
distanceMeters: null | number;
|
|
365
|
+
document: Record<string, unknown>;
|
|
366
|
+
score?: never;
|
|
367
|
+
}
|
|
368
|
+
interface SearchScoredDocument {
|
|
369
|
+
distanceMeters?: never;
|
|
370
|
+
document: Record<string, unknown>;
|
|
371
|
+
score: number;
|
|
372
|
+
}
|
|
362
373
|
interface TableReaderLike {
|
|
363
374
|
[Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
|
|
364
375
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
376
|
+
collectWithScores: () => Promise<ScoredDocument[]>;
|
|
365
377
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
|
|
366
378
|
first: () => Promise<Record<string, unknown> | null>;
|
|
367
379
|
order: (direction: "asc" | "desc") => TableReaderLike;
|
|
@@ -911,7 +923,11 @@ declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
|
|
|
911
923
|
type MigrationDirection = "down" | "up";
|
|
912
924
|
type MigrationStatus = "completed" | "failed" | "in_progress";
|
|
913
925
|
type DataMigrationDocument = Record<string, unknown>;
|
|
914
|
-
type
|
|
926
|
+
type DataMigrationReader = Pick<DatabaseWriterLike, "count" | "findFirst" | "findMany" | "get">;
|
|
927
|
+
interface DataMigrationContext {
|
|
928
|
+
db: DataMigrationReader;
|
|
929
|
+
}
|
|
930
|
+
type DataMigrationTransform = (document: DataMigrationDocument, context: DataMigrationContext) => DataMigrationDocument | Promise<DataMigrationDocument | undefined> | undefined;
|
|
915
931
|
interface DataMigrationLike {
|
|
916
932
|
readonly batchSize?: number;
|
|
917
933
|
readonly down?: DataMigrationTransform;
|
|
@@ -1103,6 +1119,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1103
1119
|
readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
|
|
1104
1120
|
readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
|
|
1105
1121
|
readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
|
|
1122
|
+
readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
|
|
1106
1123
|
readonly getLogs: "__lunora_admin__:getLogs";
|
|
1107
1124
|
readonly getMetrics: "__lunora_admin__:getMetrics";
|
|
1108
1125
|
readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
|
|
@@ -1195,6 +1212,9 @@ interface TableIndexInfo {
|
|
|
1195
1212
|
interface TableIndexesResult {
|
|
1196
1213
|
indexes: TableIndexInfo[];
|
|
1197
1214
|
}
|
|
1215
|
+
interface TablesIndexesResult {
|
|
1216
|
+
indexesByTable: Record<string, TableIndexInfo[]>;
|
|
1217
|
+
}
|
|
1198
1218
|
interface ColumnMeta {
|
|
1199
1219
|
isStorage?: boolean;
|
|
1200
1220
|
name: string;
|
|
@@ -1225,12 +1245,13 @@ interface AdvisoriesResult {
|
|
|
1225
1245
|
advisories: AdvisoryFinding[];
|
|
1226
1246
|
}
|
|
1227
1247
|
interface AdvisorProcedure {
|
|
1228
|
-
|
|
1248
|
+
analyzableBody?: boolean;
|
|
1249
|
+
callsMail?: boolean;
|
|
1229
1250
|
emitsEvent?: boolean;
|
|
1230
1251
|
exempt?: boolean;
|
|
1231
1252
|
exemptReason?: string;
|
|
1232
1253
|
exportName: string;
|
|
1233
|
-
fanOut
|
|
1254
|
+
fanOut?: boolean;
|
|
1234
1255
|
file: string;
|
|
1235
1256
|
handlesErrors?: boolean;
|
|
1236
1257
|
hasEmailArg?: boolean;
|
|
@@ -1238,15 +1259,15 @@ interface AdvisorProcedure {
|
|
|
1238
1259
|
reachesOutbound?: boolean;
|
|
1239
1260
|
runsAiGeneration?: boolean;
|
|
1240
1261
|
throwsBareError?: boolean;
|
|
1241
|
-
unboundedAiGeneration
|
|
1262
|
+
unboundedAiGeneration?: boolean;
|
|
1242
1263
|
usesCaptcha: boolean;
|
|
1243
1264
|
usesEmailGate: boolean;
|
|
1244
|
-
usesInsertManyUnsafe
|
|
1265
|
+
usesInsertManyUnsafe?: boolean;
|
|
1245
1266
|
usesMask: boolean;
|
|
1246
1267
|
usesRateLimit: boolean;
|
|
1247
1268
|
usesRls: boolean;
|
|
1248
1269
|
visibility: "internal" | "public";
|
|
1249
|
-
writesUserTable
|
|
1270
|
+
writesUserTable?: boolean;
|
|
1250
1271
|
}
|
|
1251
1272
|
interface AdvisorProceduresResult {
|
|
1252
1273
|
procedures: AdvisorProcedure[];
|
|
@@ -1973,4 +1994,4 @@ interface WhereSqlStrategy {
|
|
|
1973
1994
|
serialize: SerializeValue;
|
|
1974
1995
|
}
|
|
1975
1996
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
1976
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
1997
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -359,9 +359,21 @@ interface GeoFilterBuilderLike {
|
|
|
359
359
|
};
|
|
360
360
|
}) => GeoFilterBuilderLike;
|
|
361
361
|
}
|
|
362
|
+
type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
|
|
363
|
+
interface GeoScoredDocument {
|
|
364
|
+
distanceMeters: null | number;
|
|
365
|
+
document: Record<string, unknown>;
|
|
366
|
+
score?: never;
|
|
367
|
+
}
|
|
368
|
+
interface SearchScoredDocument {
|
|
369
|
+
distanceMeters?: never;
|
|
370
|
+
document: Record<string, unknown>;
|
|
371
|
+
score: number;
|
|
372
|
+
}
|
|
362
373
|
interface TableReaderLike {
|
|
363
374
|
[Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
|
|
364
375
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
376
|
+
collectWithScores: () => Promise<ScoredDocument[]>;
|
|
365
377
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
|
|
366
378
|
first: () => Promise<Record<string, unknown> | null>;
|
|
367
379
|
order: (direction: "asc" | "desc") => TableReaderLike;
|
|
@@ -911,7 +923,11 @@ declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
|
|
|
911
923
|
type MigrationDirection = "down" | "up";
|
|
912
924
|
type MigrationStatus = "completed" | "failed" | "in_progress";
|
|
913
925
|
type DataMigrationDocument = Record<string, unknown>;
|
|
914
|
-
type
|
|
926
|
+
type DataMigrationReader = Pick<DatabaseWriterLike, "count" | "findFirst" | "findMany" | "get">;
|
|
927
|
+
interface DataMigrationContext {
|
|
928
|
+
db: DataMigrationReader;
|
|
929
|
+
}
|
|
930
|
+
type DataMigrationTransform = (document: DataMigrationDocument, context: DataMigrationContext) => DataMigrationDocument | Promise<DataMigrationDocument | undefined> | undefined;
|
|
915
931
|
interface DataMigrationLike {
|
|
916
932
|
readonly batchSize?: number;
|
|
917
933
|
readonly down?: DataMigrationTransform;
|
|
@@ -1103,6 +1119,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1103
1119
|
readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
|
|
1104
1120
|
readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
|
|
1105
1121
|
readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
|
|
1122
|
+
readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
|
|
1106
1123
|
readonly getLogs: "__lunora_admin__:getLogs";
|
|
1107
1124
|
readonly getMetrics: "__lunora_admin__:getMetrics";
|
|
1108
1125
|
readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
|
|
@@ -1195,6 +1212,9 @@ interface TableIndexInfo {
|
|
|
1195
1212
|
interface TableIndexesResult {
|
|
1196
1213
|
indexes: TableIndexInfo[];
|
|
1197
1214
|
}
|
|
1215
|
+
interface TablesIndexesResult {
|
|
1216
|
+
indexesByTable: Record<string, TableIndexInfo[]>;
|
|
1217
|
+
}
|
|
1198
1218
|
interface ColumnMeta {
|
|
1199
1219
|
isStorage?: boolean;
|
|
1200
1220
|
name: string;
|
|
@@ -1225,12 +1245,13 @@ interface AdvisoriesResult {
|
|
|
1225
1245
|
advisories: AdvisoryFinding[];
|
|
1226
1246
|
}
|
|
1227
1247
|
interface AdvisorProcedure {
|
|
1228
|
-
|
|
1248
|
+
analyzableBody?: boolean;
|
|
1249
|
+
callsMail?: boolean;
|
|
1229
1250
|
emitsEvent?: boolean;
|
|
1230
1251
|
exempt?: boolean;
|
|
1231
1252
|
exemptReason?: string;
|
|
1232
1253
|
exportName: string;
|
|
1233
|
-
fanOut
|
|
1254
|
+
fanOut?: boolean;
|
|
1234
1255
|
file: string;
|
|
1235
1256
|
handlesErrors?: boolean;
|
|
1236
1257
|
hasEmailArg?: boolean;
|
|
@@ -1238,15 +1259,15 @@ interface AdvisorProcedure {
|
|
|
1238
1259
|
reachesOutbound?: boolean;
|
|
1239
1260
|
runsAiGeneration?: boolean;
|
|
1240
1261
|
throwsBareError?: boolean;
|
|
1241
|
-
unboundedAiGeneration
|
|
1262
|
+
unboundedAiGeneration?: boolean;
|
|
1242
1263
|
usesCaptcha: boolean;
|
|
1243
1264
|
usesEmailGate: boolean;
|
|
1244
|
-
usesInsertManyUnsafe
|
|
1265
|
+
usesInsertManyUnsafe?: boolean;
|
|
1245
1266
|
usesMask: boolean;
|
|
1246
1267
|
usesRateLimit: boolean;
|
|
1247
1268
|
usesRls: boolean;
|
|
1248
1269
|
visibility: "internal" | "public";
|
|
1249
|
-
writesUserTable
|
|
1270
|
+
writesUserTable?: boolean;
|
|
1250
1271
|
}
|
|
1251
1272
|
interface AdvisorProceduresResult {
|
|
1252
1273
|
procedures: AdvisorProcedure[];
|
|
@@ -1973,4 +1994,4 @@ interface WhereSqlStrategy {
|
|
|
1973
1994
|
serialize: SerializeValue;
|
|
1974
1995
|
}
|
|
1975
1996
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
1976
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
1997
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-iGKd9wRR.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-CF21t8IB.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DIjFVgeO.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-CvSHlkv-.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C8DLoXSK.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-DSGtSVGZ.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,M=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??N),1,M),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(b=>b.name),_=a.search?.trim()??"",i=b=>{if(a.refs===void 0)return b;const I={};for(const R of b.columns){const $=a.refs[R];$!==void 0&&(I[R]=$)}return Object.keys(I).length>0?{...b,refs:I}:b},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??M),1,M),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,M).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new h("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=C(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,M);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,M as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{LunoraError as O}from"@lunora/errors";const o="__lunora_migrations",y=100,D=3e4,$=1e4,c=(r,t,...e)=>r.exec.call(r,t,...e),w=r=>{c(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
direction TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL,
|
|
5
|
+
cursor TEXT,
|
|
6
|
+
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
started_at REAL,
|
|
9
|
+
updated_at REAL,
|
|
10
|
+
error TEXT
|
|
11
|
+
)`)},N=(r,t)=>{const e=c(r,`SELECT * FROM "${o}" WHERE id = ?`,t).toArray()[0];if(e)return{changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,startedAt:typeof e.started_at=="number"?e.started_at:void 0,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}},U=(r,t)=>{c(r,`DELETE FROM "${o}" WHERE id = ?`,t)},R=(r,t)=>{c(r,`INSERT INTO "${o}"
|
|
12
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
+
direction = excluded.direction,
|
|
16
|
+
status = excluded.status,
|
|
17
|
+
cursor = excluded.cursor,
|
|
18
|
+
processed = excluded.processed,
|
|
19
|
+
changed = excluded.changed,
|
|
20
|
+
updated_at = excluded.updated_at,
|
|
21
|
+
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},b=(r,t,e,a)=>(c(r,`INSERT INTO "${o}"
|
|
22
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
+
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
+
status = 'in_progress',
|
|
26
|
+
updated_at = excluded.updated_at
|
|
27
|
+
WHERE
|
|
28
|
+
"${o}".direction <> excluded.direction
|
|
29
|
+
OR "${o}".status <> 'in_progress'
|
|
30
|
+
OR "${o}".updated_at IS NULL
|
|
31
|
+
OR "${o}".updated_at <= excluded.updated_at - ${String(D)}`,t,e,a,a),c(r,"SELECT changes() AS changed").one().changed>0),x=(r,t)=>{c(r,`UPDATE "${o}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},M=(r,t,e)=>{c(r,`UPDATE "${o}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,e,t)},F=(r,t)=>{if(c(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",o).toArray().length===0)return[];const e=t===void 0?" ORDER BY id":" WHERE id = ?",a=t===void 0?[]:[t];return c(r,`SELECT * FROM "${o}"${e}`,...a).toArray().map(d=>({changed:d.changed,cursor:typeof d.cursor=="string"?d.cursor:null,direction:d.direction==="down"?"down":"up",error:typeof d.error=="string"?d.error:null,id:d.id,processed:d.processed,startedAt:typeof d.started_at=="number"?d.started_at:null,status:d.status==="completed"||d.status==="failed"?d.status:"in_progress",updatedAt:typeof d.updated_at=="number"?d.updated_at:null}))},H=async r=>{const{migration:t,sql:e,writer:a}=r,d=r.direction??"up",n=r.dryRun??!1,g=r.clock??(()=>Date.now()),m=r.maxBatches??Number.POSITIVE_INFINITY,S=r.batchSize??t.batchSize??y,L=d==="up"?t.up:t.down;if(!L)throw new O("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const I={db:{count:a.count.bind(a),findFirst:a.findFirst.bind(a),findMany:a.findMany.bind(a),get:a.get.bind(a)}};let u=null,l=0,T=0,_=g();if(!n){w(e);const s=N(e,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:n,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&U(e,t.id),!b(e,t.id,d,g())){const E=N(e,t.id);return{changed:E?.changed??0,cursor:E?.cursor??u,direction:d,dryRun:n,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const i=s?.direction===d?s:void 0;i&&(u=i.cursor,l=i.processed,T=i.changed,_=i.startedAt??_)}let p=!1,A=0,h=_;try{for(;!p&&A<m;){const s=await a.findMany(t.table,{cursor:u,limit:S});for(const i of s.page){l+=1;const E=await L(i,I);if(E!==void 0&&(T+=1,n||await a.replace(String(i._id),{...E,_creationTime:i._creationTime,_id:i._id},void 0,{allowExplicitId:!0})),!n){const f=g();f-h>=$&&(M(e,t.id,f),h=f)}}if(u=s.continueCursor,p=s.isDone,A+=1,!n){const i=g();R(e,{changed:T,cursor:p?null:u,direction:d,error:null,id:t.id,processed:l,startedAt:_,status:p?"completed":"in_progress",updatedAt:i}),h=i;try{await r.onBatch?.({batches:A,changed:T,processed:l})}catch{}}}}catch(s){throw n||R(e,{changed:T,cursor:u,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:l,startedAt:_,status:"failed",updatedAt:g()}),s}if(!n&&!p)try{x(e,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:T,cursor:p?null:u,direction:d,dryRun:n,id:t.id,processed:l,status:p?"completed":"in_progress"}};export{o as DATA_MIGRATION_STATE_TABLE,F as readMigrationStatus,H as runDataMigration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{n as Et,A as Ue,T as Se,y as Nt,c as St}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Tt,throwingScheduler as _t}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ce,readAggregateValue as Me,aggregateTableName as Le}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Rt,selectIndexForCount as At,selectIndexForAggregate as vt}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as It}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as pr,backfillRankIndexes as mr,backfillSearchIndexes as wr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as xt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as $r,applyCdcChanges as yr,bumpCdcEpoch as br,minCdcSeq as Er,readCdcChanges as Nr,readCdcCursor as Sr,readCdcEpoch as Tr,trimCdcChanges as _r}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as Ct}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Xe}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Mt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as Q,rowToDocument as le,tableColumns as ht,isFtsAvailable as Lt,tryRowToDocument as pt,geoTableName as kt,qualifiedJsonPathSql as Ze}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Dt,boundingBoxGeohashes as Ot,pointInBoundingBox as Wt,haversineMeters as Ft}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as qt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Bt,buildSeekWhere as mt,decodeCursor as Fe,applySelect as et,encodeCursor as qe,softDeleteScope as de,buildSeekBeforeWhere as Ut}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as tt,resolveRankPartition as Pt,encodePartitionKey as Ht,RANK_TIEBREAK as jt,rankTableName as nt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Gt,buildIndexRange as Kt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as rt}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as it,applyOnDelete as Jt,fanOutScalarCounts as Qt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as zt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Vt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as we}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Yt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Ar,advanceClientWatermark as vr,migrateClientWatermark as Ir,readClientWatermark as xr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Mr,deleteGlobalShapeSnapshot as Lr,deleteGlobalShapeSnapshotsForConnection as kr,migrateGlobalShapeSnapshot as Dr,readGlobalShapeSnapshot as Or,writeGlobalShapeSnapshot as Wr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as qr,readIdempotent as Br,trimIdempotent as Ur,writeIdempotent as Pr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as jr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Kr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Qr,selectShapeRows as zr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const Xt=i=>{const o=new TextEncoder().encode(i);let t="";for(const d of o)t+=String.fromCodePoint(d);return btoa(t)},Zt=i=>{const o=atob(i),t=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},en=()=>new y("BAD_REQUEST","invalid cursor"),ot=16,at=8,Z=1024,Pe=(i,o)=>o.query(i),tn=(i,o,t)=>{const d=Et(i,t);if(d.length===0)return 0;let f=0;for(const[p,w]of o.entries()){const R=p===o.length-1;let S=0;for(const g of d)(R?g.startsWith(w):g===w)&&(S+=1);if(S===0)return 0;f+=S}return f},nn=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=i.codePointAt(i.length-1)??0,d=i.slice(0,Math.max(0,i.length-String.fromCodePoint(t).length));return{exact:!1,lower:i,upper:d+String.fromCodePoint(t+1)}},rn=(i,o,t)=>{const d={eq:(f,p)=>{if(!i.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=at)throw new y("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(at)} .eq() filters are supported per search query`);return i.filters.push({field:f,value:p}),d},search:(f,p)=>{const w=i;if(f!==w.definition.field)throw new y("INTERNAL",`search index "${w.indexName}" on table "${o}" indexes "${w.definition.field}", not "${f}"`);const R=Pe(p,t).length;if(R>ot)throw new y("BAD_REQUEST",`search index "${w.indexName}" on table "${o}": at most ${String(ot)} search terms are supported (got ${String(R)})`);return w.field=f,w.query=p,w.hasQuery=!0,d}};return d},on=i=>{if(i.length>Z)throw new y("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},an=i=>Math.min(i.offset+i.numItems+1,Z),sn=i=>Xt(`search:${String(i)}`),dn=i=>{let o;try{o=Zt(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ln=i=>{if(typeof i.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?dn(i.cursor):0;if(t===void 0)throw en();if(t+o>Z)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},cn=(i,o)=>{const t=o.offset+o.numItems,d=o.numItems>0&&i.length>t;return{continueCursor:d?sn(t):null,isDone:!d,page:i.slice(o.offset,t)}},un=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new y("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,hn=i=>{if(!fn.test(i))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},st=50,wt=500,pn=128,se=(i,o,t)=>{const d=o??wt;if(i>d)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},mn=i=>{const o={eq:(t,d)=>(i.sqlConditions.push({comparator:"=",field:t,value:d}),o),gt:(t,d)=>(i.sqlConditions.push({comparator:">",field:t,value:d}),o),gte:(t,d)=>(i.sqlConditions.push({comparator:">=",field:t,value:d}),o),lt:(t,d)=>(i.sqlConditions.push({comparator:"<",field:t,value:d}),o),lte:(t,d)=>(i.sqlConditions.push({comparator:"<=",field:t,value:d}),o)};return o},wn=i=>Math.max(i,Z),gn=(i,o,t,d,f)=>{const p=Pe(t.query,Ue(t.definition.language));if(p.length===0)return[];const w=St(o,t.indexName),R=`${w}__vocab`,S=p.length-1,g=p.map((M,k)=>{const H=nn(M,k===S),U=H.exact?n`${n.identifier("term")} = ${H.lower}`:n`${n.identifier("term")} >= ${H.lower} AND ${n.identifier("term")} < ${H.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),b=p.map((M,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(b,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier(w)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(b.map(M=>n`${M} > 0`),n` AND `)}`,_=[];for(const M of t.filters)_.push(n`${Q(M.field)} = ${re(M.value)}`);f&&_.push(f);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const D=[];for(const M of B(i,C)){const k=pt(M);if(k){const H=M.__score__;D.push({document:k,score:typeof H=="number"?H:Number(H??0)})}}return D},$n=(i,o,t,d,f)=>{const p=Ue(t.definition.language),w=Pe(t.query,p);if(w.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${Q(E.field)} = ${re(E.value)}`);f&&R.push(f);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(wn(d)))}`;const g=B(i,S).toArray(),b=[];for(const E of g){const _=pt(E);if(!_)continue;const C=tn(Nt(_,t.definition),w,p);C>0&&b.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return b.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),b.slice(0,d).map(E=>({document:E.doc,score:E.score}))},yn=(i,o)=>{const t=i,d={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},d},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},bn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},En=(i,o)=>{const t=bn(i,o.definition.field);if(!t)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const f=Ft(o.near.point,t);return f<=o.near.radiusMeters?{creationTime:d,distance:f}:void 0}return Wt(t,o.within)?{creationTime:d,distance:0}:void 0},gt=(i,o,t,d)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const f=t.near?Dt(t.near.point,t.near.radiusMeters):Ot(t.within),p=kt(o,t.indexName),w=f.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(w,n` OR `)})`];d&&R.push(d);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,g=B(i,S).toArray(),b=[];for(const E of g){const _=le(E),C=_?En(_,t):void 0;_&&C&&b.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return b.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),b},Nn=(i,o,t,d,f,p=()=>{})=>{const w=gt(i,o,t,f).map(R=>R.doc);return p(w.length),typeof d=="number"?w.slice(0,Math.max(0,Math.floor(d))):w},Sn=(i,o,t,d,f,p=()=>{})=>{const w=t.within!==void 0,R=gt(i,o,t,f).map(S=>({distanceMeters:w?null:S.distance,document:S.doc}));return p(R.length),R},Tn=(i,o,t,d,f,p=()=>{})=>{const{geo:w}=t;if(!w)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Nn(i,o,w,R?void 0:f,d,p);if(!R)return S;const g=[];for(const b of S)if(t.inMemoryFilters.every(E=>E(b))&&(g.push(b),typeof f=="number"&&g.length>=f))break;return g},_n=(i,o,t,d,f,p=()=>{})=>{const{geo:w}=t;if(!w)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Sn(i,o,w,R?void 0:f,d,p);if(!R)return S;const g=[];for(const b of S)t.inMemoryFilters.every(E=>E(b.document))&&g.push(b);return g},Rn=(i,o,t,d,f,p,w=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${Q(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);d&&R.push(d);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(i,S).toArray();w(g.length);const b=[];for(const E of g){const _=le(E);if(_&&t.inMemoryFilters.every(C=>C(_))&&(b.push(_),typeof p=="number"&&b.length>=p))break}return b},oe={fieldRef:Q,serialize:re},An=i=>{let o=0;const t=[],d={fieldRef:Q,relationExists:f=>{const{childWhere:p,negated:w,parentTable:R,relation:S}=f,g=`__rel_${String(o)}`,b=t.at(-1)??R;o+=1,i(S.table,q);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,C=n`${Ze(g,_)} = ${Ze(b,E)}`;t.push(g);const D=ne(p,d);t.pop();const M=D?n`${C} AND ${D}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier(g)} WHERE ${M})`;return w?n`NOT ${k}`:k},serialize:re};return d},$t=i=>{const o=i.map(t=>n`${Q(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${Q("id")} ASC`),n.join(o,n`, `)},vn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},xn=(i,o,t,d)=>{const f=i.sqlConditions.map(p=>({[p.field]:{[vn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(mt(o,Fe(t))),d&&f.push(Ut(o,Fe(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Cn=(i,o,t)=>{const d=[];for(const f of i){const p=le(f);if(p&&o.every(w=>w(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Mn=(i,o,t,d,f,p=()=>{})=>{const w=Math.max(0,Math.floor(d.numItems)),R=In(t),S=typeof d.endCursor=="string",g=ne(xn(t,R,d.cursor,d.endCursor),oe),b=f&&g?n`${g} AND ${f}`:f??g;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;b&&(E=n`${E} WHERE ${b}`),E=n`${E} ORDER BY ${$t(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(w+1))}`);const C=B(i,E).toArray();p(C.length);const D=Cn(C,t.inMemoryFilters,_||S?void 0:w);if(S){const U=D.length>=2?D[Math.floor(D.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:D,splitCursor:U?qe(U,R):null}}const M=D.length>w,k=M?D.slice(0,w):D,H=k.at(-1);return{continueCursor:M&&H?qe(H,R):null,isDone:!M,page:k}};class Ln extends y{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const kn=/\s/u,Dn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new y("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||kn.test(t)||t.includes(Dn)?null:t},On=(i,o,t,d=()=>{},f=()=>{},p=()=>{})=>{const w=o.tables[t];if(!w)throw new y("INTERNAL",`unknown table: ${t}`);const R=de(w.softDeleteMode,void 0),S=R?ne(R,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let b=0;const E=N=>{const{search:x}=g;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");It(i,t,w);const I=g.inMemoryFilters.length>0,L=un(I?void 0:N),j=Lt(i)?gn(i,t,x,L,S):$n(i,t,x,L,S);if(!I)return N===void 0&&on(j),j;const X=[];b=j.length;for(const ce of j)if(g.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(x=>x.document),C=N=>{const x=ln(N);return cn(_(an(x)),x)},D=()=>{const N=g.indexFields.length>0?g.indexFields:["_creationTime"],x=g.order==="desc"?"DESC":"ASC";return n.join(N.map(I=>n`${Q(I)} ${n.raw(x)}`),n`, `)},M=()=>{if(g.search||g.geo||g.indexName===void 0){f(void 0);return}f(Kt(t,g.indexName,g.indexFields,g.sqlConditions,re))},k=N=>{M();let x=0;const I=(()=>{if(g.search){const L=_(N);return x=b,L}return g.geo?Tn(i,t,g,S,N,L=>{x=L}):Rn(i,t,g,S,D(),N,L=>{x=L})})();return p(Math.max(x,I.length)),I},H=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);M();let N=0;const x=(()=>{if(g.search){const I=E(void 0);return N=b,I}return _n(i,t,g,S,void 0,I=>{N=I})})();return p(Math.max(N,x.length)),x},U={async*[Symbol.asyncIterator](){const N=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const I=await U.paginate({cursor:x??null,numItems:pn});for(const L of I.page)N.every(j=>j(L))&&(yield L);if(I.isDone||I.continueCursor===null)return;x=I.continueCursor}}finally{g.inMemoryFilters=N}},async collect(){return k(void 0)},async collectWithScores(){return H()},filter(N){return g.inMemoryFilters.push(N),U},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return g.order=N==="desc"?"desc":"asc",U},async paginate(N){let x=0;if(M(),g.search){const L=C(N);return p(L.page.length),L}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Mn(i,t,g,N,S,L=>{x=L});return p(Math.max(x,I.page.length)),I},async take(N){return k(N)},async unique(){const N=k(g.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Ln(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,x){const I=(w.geoIndexes??[]).find(j=>j.name===N);if(!I)throw new y("INTERNAL",`unknown geo index "${N}" on table "${t}"`);d(t,N,"geo");const L={definition:I,indexName:N};if(g.geo=L,x(yn(L,t)),!L.near&&!L.within)throw new y("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,x){const I=w.indexes.find(L=>L.name===N);if(!I)throw new y("INTERNAL",`unknown index "${N}" on table "${t}"`);return d(t,N,"index"),g.indexName=N,g.indexFields=I.fields,x&&x(mn(g)),U},withSearchIndex(N,x){const I=(w.searchIndexes??[]).find(j=>j.name===N);if(!I)throw new y("INTERNAL",`unknown search index "${N}" on table "${t}"`);d(t,N,"search");const L={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:N,query:""};if(g.search=L,x(rn(L,t,Ue(I.language))),!L.hasQuery)throw new y("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},lt=(i,o,t)=>{const d={...o};for(const[f,p]of ht(i)){if(p.serverDefault){d[f]=p.serverDefault({auth:t});continue}d[f]===void 0&&(p.defaultFn?d[f]=p.defaultFn():"defaultValue"in p&&(d[f]=p.defaultValue))}return d},ct=(i,o,t,d)=>{const f=t;for(const[p,w]of ht(i)){if(w.serverDefault){p in o&&(f[p]=w.serverDefault({auth:d}));continue}w.onUpdateFn&&!(p in o)&&(f[p]=w.onUpdateFn())}},ut=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new y("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Wn=/unique constraint failed/i,Fn=i=>i instanceof Error&&Wn.test(i.message),Be=(i,o,t)=>{try{B(i,t)}catch(d){throw Fn(d)?new we(`unique constraint violation on "${o}"`,"unique"):d}},Ae=(i,o,t)=>{if(Be(i,o,t),B(i,n`SELECT changes() AS changed`).one().changed===0)throw new we(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ft=(i,o,t,d,f,p,w)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let k=0;k<E;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[E],D=d[E];if(C!==void 0&&D!==void 0){const k=D.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[E]}`)}else _.push(n`${n.identifier(jt)} < ${w}`);const[M]=_;R.push(_.length===1&&M!==void 0?M:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),g=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${f} AND (${S})`).one(),b=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${f}`).one();return{before:g.c,total:b.c}},ur=i=>{const{sql:o}=i,{schema:t}=i,d=i.broadcast??(()=>{}),f=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const u of r)u&&h.push(...Gt(a,u,re));return h.length>0?h:void 0},{headroom:p}=i;let w=!1;const R=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},S=i.onRead??(()=>{}),g=i.onReadRange??(e=>{S(e.table,q)}),b=(e,r)=>{r!==void 0&&r!==q&&!w&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:D}=i,M=i.clock??(()=>Date.now()),k=i.idGenerator??(()=>crypto.randomUUID()),H=i.scheduler??_t,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},x=i.cdc??!1,I=H,L=Vt({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:i.storage}),j=(e,r,a,h)=>{x&&xt(o,M(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new y("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return F},ue=e=>ce(e,"cascade"),z=(e,r)=>{if(X(e)){if(!U)throw new y("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,ve=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&b(e,q),ve(e,r)),yt=e=>!X(e.table),je=i.relationExistsPushDown??"auto",Ge=je!=="never",{maxRelationKeys:Ke}=i,ge=(e,r,a)=>rt(e,{fetcher:He,maxRelationKeys:Ke,relationBaseWhere:a,schema:t,tableName:r}),Je=async(e,r,a,h)=>{const u=z(e,"relation grouped count");if(u)return b(e,q),Qt((v,K)=>u.count(v,K),e,r,a,h);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);b(e,q);const s=de(l.softDeleteMode,void 0),c={[r]:{in:a}},m=J(J(c,h),s),T=await ge(m,e,void 0),$=ne(T,oe),A=Q(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;$&&(W=n`${W} WHERE ${$}`),W=n`${W} GROUP BY ${A}`;const O=B(o,W).toArray();return new Map(O.map(v=>[v.__fk__,v.count]))};let $e=0;const Qe=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Qe.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Qe.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if($e+=1,$e>st)throw $e-=1,new we(`trigger recursion exceeded ${String(st)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Yt({ctx:bt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ie,ensureRankBackfilled:xe,ensureRankBackfilledForTable:pe,syncAggregates:ye,syncCompanionsForInsert:ze,syncGeo:be,syncRanks:me,syncSearch:Ee}=Ct({broadcast:d,indexKeysFor:(e,r)=>f(e,r),invalidateCache:(e,r,a)=>D?.invalidate(e,r,f(e,a)),recordCdc:j,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),u=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[l]=B(o,u).toArray();if(!l)return;const s=l.__t__,c=le(l);if(typeof s!="string"||!c)return;const m=l[P];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:c,tableName:s}},Ye={assertRankPartitionLocal:Ve,ensureRankBackfilled:xe,onRead:b,rowToDocument:le,schema:t,sql:o},F={system:L,async aggregate(e,r){const a=z(e,"aggregate");if(a)return b(e,q),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return F.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);b(e,q);const u=de(h.softDeleteMode,void 0),l=J(J(r.baseWhere,r.where),u),s=await ge(l,e,r.relationBaseWhere),c=s!==l;if(h.aggregateIndexes&&!r.baseWhere&&!c&&!u){const O=vt(h.aggregateIndexes,r.op,r.field,r.where);if(O){Ie(e,O.index);const v=Ce(O.index.by??[],O.key),K=Le(e,O.index.name),V=B(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${v}`).toArray()[0];return Me(r.op,V)}}const m=ne(s,oe),T=Te(r.op),$=Q(r.field);let A=n`SELECT ${n.raw(T)}(${$}) AS value FROM ${n.identifier(e)}`;return m&&(A=n`${A} WHERE ${m}`),B(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(t,e,r);if(a===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return b(e,q),a.count(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Tt(r);if(u.restrictsCounts)throw new ke(e);b(e,q);const l=de(h.softDeleteMode,void 0),s=J(J(u.baseWhere,u.where),l),c=await ge(s,e,u.relationBaseWhere),m=c!==s;if(h.aggregateIndexes&&!u.baseWhere&&!m&&!l){const A=At(h.aggregateIndexes,u.where);if(A){Ie(e,A.index);const W=Ce(A.index.by??[],A.key),O=Le(e,A.index.name),v=B(o,n`SELECT ${_e} AS value FROM ${n.identifier(O)} WHERE ${Re} = ${W}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(c,oe);let $=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&($=n`${$} WHERE ${T}`),B(o,$).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const $=r===void 0?fe():void 0;$&&await $.delete(e,void 0,a);return}const{docJson:u,row:l,tableName:s}=h,c=t.tables[s],m=a?.hard===!0,T=!m&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:l,table:s}),await Jt({deletedId:e,deletedReference:$=>l[$],findHolders:async($,A,W)=>(await ue($).findMany($,{includeDeleted:m,where:{[A]:W}})).page,onCascade:($,A)=>ue($).delete(A,void 0,a),onRestrict:$=>{throw new we($,"restrict")},onSetNull:($,A,W)=>ue($).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const $={...l,[T]:M(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify($)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,$,l),be(s,e,void 0),ye(s,l,$),me(s,e,l,void 0),D?.invalidate(s,e,f(s,l,$)),j(s,e,"update",$),d({indexKeys:f(s,l,$),key:e,op:"update",row:$,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:s}),await C({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,void 0),be(s,e,void 0),ye(s,l,void 0),me(s,e,l,void 0),D?.invalidate(s,e,f(s,l)),j(s,e,"delete"),d({indexKeys:f(s,l),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??wt),h=r?.hard===void 0?void 0:{hard:r.hard},u=X(e)?void 0:e;let l=0;return await R(async()=>{for(;;){const s=(await F.findMany(e,{limit:a})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await F.delete(c,u,h),l+=1;if(s.length<a)break}}),{deleted:l}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await F.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=z(e,"deleteWhere");let u;if(h)u=(await h.findMany(e,{where:r})).page.map(l=>String(l._id));else{if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r})).page.map(l=>String(l._id))}if(se(u.length,a?.limit,"deleteWhere"),F.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return F.deleteMany(u,a)},async findFirst(e,r={}){return(await F.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await F.findFirst(e,r);if(a===null)throw new qt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return b(e,q),a.findMany(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=!r.where&&!r.baseWhere;u?b(e,q):b(e);const l=Bt(r.orderBy),s=r.cursor?mt(l,Fe(r.cursor)):void 0;let c=J(r.baseWhere,r.where);c=J(c,de(h.softDeleteMode,r.includeDeleted)),c=await rt(c,{canPushExists:Ge?yt:void 0,existsPushMode:je==="always"?"always":"auto",fetcher:He,maxRelationKeys:Ke,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const m=Ge?An(b):oe,T=ne(c,m);let $=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&($=n`${$} WHERE ${T}`),$=n`${$} ORDER BY ${$t(l)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&($=n`${$} LIMIT ${n.raw(String(A+1))}`);const W=B(o,$).toArray();u&&!w&&p?.recordRead(W.length);const O=[];for(const Y of W){const G=le(Y);G&&(O.push(G),!u&&typeof G._id=="string"&&b(e,G._id))}if(A===void 0)return r.with&&await it({groupedCounter:Je,fetcher:ve,parents:O,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:et(O,r.select,r.with)};const v=O.length>A,K=v?O.slice(0,A):O,V=K.at(-1);return r.with&&await it({fetcher:ve,groupedCounter:Je,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:v&&V?qe(V,l):null,isDone:!v,page:et(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return b(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(b(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return b(e,q),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);b(e,q);const u=r.agg??{op:"count"};if(Te(u.op),u.op!=="count"&&!u.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);const l=de(h.softDeleteMode,void 0),s=J(J(r.baseWhere,r.where),l),c=await ge(s,e,r.relationBaseWhere),m=c!==s;if(h.aggregateIndexes&&!r.baseWhere&&!m&&!l){const v=Rt(h.aggregateIndexes,u.op,u.field,r.by,r.where);if(v){Ie(e,v.index);const K=Le(e,v.index.name),V=Object.keys(v.partial),Y=[];if(V.length===(v.index.by??[]).length&&V.length>0){const ae=Ce(v.index.by??[],v.partial),Ne=B(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&Y.push({key:{...v.partial},value:Me(u.op,Ne[0])}),Y}const G=B(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);Y.push({key:Ne,value:Me(u.op,ae)})}return Y}}const T=ne(c,oe),$=r.by.map(v=>n`${Q(v)} AS ${n.identifier(v)}`);if(u.op==="count")$.push(n`COUNT(*) AS value`);else{const{field:v}=u;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);$.push(n`${n.raw(Te(u.op))}(${Q(v)}) AS value`)}let A=n`SELECT ${n.join($,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(v=>Q(v)),n`, `)}`;const W=B(o,A).toArray(),O=[];for(const v of W){const K={};for(const Y of r.by)K[Y]=v[Y]??null;const{value:V}=v;O.push({key:K,value:V==null?null:Number(V)})}return O},async insert(e,r,a){const h=z(e,"insert");if(h){const T=await h.insert(e,r,a);return w||p?.recordWrite(r),d({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=lt(u,r,N);We(u,l);let s;a?.clientId!==void 0?(hn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof l._id=="string"?s=l._id:s=k();const c=a?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:M(),m={...l,_creationTime:c,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...m},id:s,op:"insert",table:e}),he(e),pe(e),Be(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${c}, ${JSON.stringify(m)})`),ze(e,s,m),ee(e,"after","insert")&&await te("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=z(e,"insert");if(h){const c=[];for(const m of r){const T=await h.insert(e,m,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite(m),d({key:T,op:"insert",row:{...m,_id:T},table:e}),c.push(T)}return c}const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const l=r.map(c=>{const m=lt(u,c,N),T=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:k(),$=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:M();return{creationTime:$,document:{...m,_creationTime:$,_id:T},id:T}});if(!w)for(const c of l)p?.recordWrite(c.document);const s=n.join(l.map(c=>n`(${c.id}, ${c.creationTime}, ${JSON.stringify(c.document)})`),n`, `);Be(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:c,id:m}of l)ze(e,m,c),await _({doc:c,id:m,op:"insert",table:e});return l.map(c=>c.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,u=[];for(const l of r)try{u.push(await F.insert(e,l))}catch(s){if(h&&s instanceof we&&s.kind==="unique")u.push(null);else throw s}return u},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:l,tableName:s}=h,c=t.tables[s];if(!c)throw new y("INTERNAL",`unknown table: ${s}`);b(s,e),ut("patch",r);const m={...l,...r,_id:e};ct(c,r,m,N),We(c,m,!0),ee(s,"before","update")&&await te("before","update",{doc:{...m},id:e,op:"update",previous:l,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,m,l),be(s,e,m),ye(s,l,m),me(s,e,l,m),D?.invalidate(s,e,f(s,l,m)),j(s,e,"update",m),d({indexKeys:f(s,l,m),key:e,op:"update",row:m,table:s}),ee(s,"after","update")&&await te("after","update",{doc:m,id:e,op:"update",previous:l,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await F.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=z(e,"patchWhere");let u;if(h)u=(await h.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}));else{if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}))}if(se(u.length,a?.limit,"patchWhere"),F.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await F.patchMany(u,a),{patched:u.length}},query(e){const r=z(e,"query");return r?(b(e,q),r.query(e)):On(o,t,e,E,a=>{a?g(a):b(e,q)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const h=z(e,"rank");if(h)return b(e,q),h.rank(e,r,a);E(e,r,"rank");const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=u.rankIndexes?.find(G=>G.name===r);if(!l)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,u,l),a.restrictsCounts)throw new ke(e);b(e,q),xe(e,l);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const c=nt(e,l.name),m=l.sortBy.map((G,ae)=>tt(ae)),T=m.map(G=>Mt(G)).join(", "),$=B(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(c)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let W=A.__partition__;const O=J(a.baseWhere,a.where);Oe(O,t,e,"rank");const v=Pt(l,O);if(v){const G=Ht(l.partitionBy??[],v);if(G!==W)return null;W=G}const K=m.map(G=>A[G]),{before:V,total:Y}=ft(o,c,m,l.sortBy,W,K,s);return{position:V+1,total:Y}},async rankBefore(e,r,a){if(X(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(m=>m.name===r);if(!u)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new ke(e);b(e,q),xe(e,u);const l=nt(e,u.name),s=u.sortBy.map((m,T)=>tt(T)),c=u.sortBy.map((m,T)=>re(a.sortValues[T]??null));return ft(o,l,s,u.sortBy,a.partitionKey,c,a.rowId)},async rankPage(e,r,a={}){Oe(J(a.baseWhere,a.where),t,e,"rankPage");const h=z(e,"rankPage");if(h)return b(e,q),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:u,hasMore:l,rows:s}=Xe(Ye,e,r,a);return{continueCursor:u,isDone:!l,page:s.map(c=>c.doc)}},async rankPageRows(e,r,a={}){Oe(J(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:u,rows:l}=Xe(Ye,e,r,a);return{directions:h,hasMore:u,rows:l}},async restore(e,r){const a=ie(e,r);if(!a){const l=r===void 0?fe():void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new y("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const u=a.row[h]!==null&&a.row[h]!==void 0;await F.patch(e,{[h]:null},r),u&&me(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const u=ie(e,a);if(!u){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:s,tableName:c}=u,m=t.tables[c];if(!m)throw new y("INTERNAL",`unknown table: ${c}`);ut("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:M(),$={...r,_creationTime:T,_id:e};ct(m,r,$,N),We(m,$),ee(c,"before","update")&&await te("before","update",{doc:{...$},id:e,op:"update",previous:s,table:c}),he(c),pe(c),Ae(o,c,n`UPDATE ${n.identifier(c)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify($)} WHERE id = ${e} AND ${n.identifier(P)} = ${l}`),Ee(c,e,$,s),be(c,e,$),ye(c,s,$),me(c,e,s,$),D?.invalidate(c,e,f(c,s,$)),j(c,e,"update",$),d({indexKeys:f(c,s,$),key:e,op:"update",row:$,table:c}),ee(c,"after","update")&&await te("after","update",{doc:$,id:e,op:"update",previous:s,table:c}),await C({doc:$,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([c,m])=>r.has(c)||a!==void 0&&!a.includes(c)?!1:m.shardMode?.kind!=="global").map(([c])=>c);if(a!==void 0){for(const c of a)if(!t.tables[c])throw new y("INTERNAL",`wipeShard: unknown table: ${c}`)}const u={};let l=0;const{deleteAll:s}=F;if(s===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of h){const m=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});u[c]=m.deleted,l+=m.deleted}return{deleted:l,tables:u}}},bt={db:F,scheduler:H};return i.enforceRls===!0?zt(F,t,(e,r)=>ie(e,r)?.tableName):F};export{$r as CDC_LOG_TABLE,Ar as CLIENT_WATERMARK_TABLE,Mr as GLOBAL_SHAPE_SNAPSHOT_TABLE,qr as IDEMPOTENCY_TABLE,Ln as NotUniqueError,Kr as SEARCH_STATE_TABLE,vr as advanceClientWatermark,yr as applyCdcChanges,hn as assertValidClientId,pr as backfillAggregateIndexes,mr as backfillRankIndexes,wr as backfillSearchIndexes,br as bumpCdcEpoch,ur as createShardCtxDb,Lr as deleteGlobalShapeSnapshot,kr as deleteGlobalShapeSnapshotsForConnection,Ir as migrateClientWatermark,Dr as migrateGlobalShapeSnapshot,Er as minCdcSeq,dt as normalizeIdStructurally,Nr as readCdcChanges,Sr as readCdcCursor,Tr as readCdcEpoch,xr as readClientWatermark,Or as readGlobalShapeSnapshot,Br as readIdempotent,jr as runShardMigrations,Qr as selectShapeMemberIds,zr as selectShapeRows,_r as trimCdcChanges,Ur as trimIdempotent,Wr as writeGlobalShapeSnapshot,Pr as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{r as p}from"./estimate-bytes-DzD3PdCc.mjs";import{keysTouchRanges as x}from"./buildIndexRange-
|
|
1
|
+
import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{r as p}from"./estimate-bytes-DzD3PdCc.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as R}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),a=e(),c=p(h,this.maxBytes),f={bytes:c,deps:s,ranges:a,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const o of s){let r=this.tableIndex.get(o);r||(r=new Set,this.tableIndex.set(o,r)),r.add(t)}for(const o of a){let r=this.rangeIndex.get(o.table);r||(r=new Map,this.rangeIndex.set(o.table,r));let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,y),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const a of h){const c=this.entries.get(a);c&&(this.dropEntry(a,c),i.push(a))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,R as stableStringify,g as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const v=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let r=o.getUint32(0,!1),e=o.getUint32(4,!1);return(r&2147483648)===0?r=(r^2147483648)>>>0:(r=~r>>>0,e=~e>>>0),r.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},g=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},c=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${v(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${g(t)}`},d=t=>{const o=[];for(const r of t){const e=c(r);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),h=(t,o,r,e)=>{const i=o.comparator==="=",n=p.has(o.comparator)||x.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},w=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,a){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},f=(t,o)=>{const r=c(o);if(r!==void 0)return t===""?r:t+"!"+r},y=(t,o,r,e,i)=>{if(r.length===0)return;const n=w(r,e,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"!":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+""}if(!(a>=l))return{hi:l,index:o,lo:a,table:t}},E=(t,o,r)=>{const e=[];for(const i of t){const n=d(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},m=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>m(e,n))})};export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,m as rangeContains};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-C8DLoXSK.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{keysTouchRanges as g}from"./buildIndexRange-
|
|
1
|
+
import{keysTouchRanges as g}from"./buildIndexRange-DFsdtPjD.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.5",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.11",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.2",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,b=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??N),1,b),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(h=>h.name),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const C={};for(const R of h.columns){const $=a.refs[R];$!==void 0&&(C[R]=$)}return Object.keys(C).length>0?{...h,refs:C}:h},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??b),1,b),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,b).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new M("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=I(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,b);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{LunoraError as I}from"@lunora/errors";const o="__lunora_migrations",O=100,y=3e4,D=1e4,i=(r,t,...e)=>r.exec.call(r,t,...e),$=r=>{i(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
direction TEXT NOT NULL,
|
|
4
|
-
status TEXT NOT NULL,
|
|
5
|
-
cursor TEXT,
|
|
6
|
-
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
-
started_at REAL,
|
|
9
|
-
updated_at REAL,
|
|
10
|
-
error TEXT
|
|
11
|
-
)`)},R=(r,t)=>{const e=i(r,`SELECT * FROM "${o}" WHERE id = ?`,t).toArray()[0];if(e)return{changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,startedAt:typeof e.started_at=="number"?e.started_at:void 0,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}},w=(r,t)=>{i(r,`DELETE FROM "${o}" WHERE id = ?`,t)},f=(r,t)=>{i(r,`INSERT INTO "${o}"
|
|
12
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
-
direction = excluded.direction,
|
|
16
|
-
status = excluded.status,
|
|
17
|
-
cursor = excluded.cursor,
|
|
18
|
-
processed = excluded.processed,
|
|
19
|
-
changed = excluded.changed,
|
|
20
|
-
updated_at = excluded.updated_at,
|
|
21
|
-
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},U=(r,t,e,n)=>(i(r,`INSERT INTO "${o}"
|
|
22
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
-
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
-
status = 'in_progress',
|
|
26
|
-
updated_at = excluded.updated_at
|
|
27
|
-
WHERE
|
|
28
|
-
"${o}".direction <> excluded.direction
|
|
29
|
-
OR "${o}".status <> 'in_progress'
|
|
30
|
-
OR "${o}".updated_at IS NULL
|
|
31
|
-
OR "${o}".updated_at <= excluded.updated_at - ${String(y)}`,t,e,n,n),i(r,"SELECT changes() AS changed").one().changed>0),x=(r,t)=>{i(r,`UPDATE "${o}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},C=(r,t,e)=>{i(r,`UPDATE "${o}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,e,t)},b=(r,t)=>{if(i(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",o).toArray().length===0)return[];const e=t===void 0?" ORDER BY id":" WHERE id = ?",n=t===void 0?[]:[t];return i(r,`SELECT * FROM "${o}"${e}`,...n).toArray().map(d=>({changed:d.changed,cursor:typeof d.cursor=="string"?d.cursor:null,direction:d.direction==="down"?"down":"up",error:typeof d.error=="string"?d.error:null,id:d.id,processed:d.processed,startedAt:typeof d.started_at=="number"?d.started_at:null,status:d.status==="completed"||d.status==="failed"?d.status:"in_progress",updatedAt:typeof d.updated_at=="number"?d.updated_at:null}))},F=async r=>{const{migration:t,sql:e,writer:n}=r,d=r.direction??"up",c=r.dryRun??!1,g=r.clock??(()=>Date.now()),m=r.maxBatches??Number.POSITIVE_INFINITY,S=r.batchSize??t.batchSize??O,N=d==="up"?t.up:t.down;if(!N)throw new I("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);let u=null,l=0,T=0,_=g();if(!c){$(e);const s=R(e,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:c,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&w(e,t.id),!U(e,t.id,d,g())){const E=R(e,t.id);return{changed:E?.changed??0,cursor:E?.cursor??u,direction:d,dryRun:c,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const a=s?.direction===d?s:void 0;a&&(u=a.cursor,l=a.processed,T=a.changed,_=a.startedAt??_)}let p=!1,A=0,h=_;try{for(;!p&&A<m;){const s=await n.findMany(t.table,{cursor:u,limit:S});for(const a of s.page){l+=1;const E=N(a);if(E!==void 0&&(T+=1,c||await n.replace(String(a._id),{...E,_creationTime:a._creationTime,_id:a._id},void 0,{allowExplicitId:!0})),!c){const L=g();L-h>=D&&(C(e,t.id,L),h=L)}}if(u=s.continueCursor,p=s.isDone,A+=1,!c){const a=g();f(e,{changed:T,cursor:p?null:u,direction:d,error:null,id:t.id,processed:l,startedAt:_,status:p?"completed":"in_progress",updatedAt:a}),h=a;try{await r.onBatch?.({batches:A,changed:T,processed:l})}catch{}}}}catch(s){throw c||f(e,{changed:T,cursor:u,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:l,startedAt:_,status:"failed",updatedAt:g()}),s}if(!c&&!p)try{x(e,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:T,cursor:p?null:u,direction:d,dryRun:c,id:t.id,processed:l,status:p?"completed":"in_progress"}};export{o as DATA_MIGRATION_STATE_TABLE,b as readMigrationStatus,F as runDataMigration};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{n as gt,A as Be,T as Ee,y as bt,c as yt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as Et,throwingScheduler as Nt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ie,readAggregateValue as xe,aggregateTableName as Ce}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as G,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Tt,selectIndexForCount as At,selectIndexForAggregate as St}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as _t}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as dr,backfillRankIndexes as cr,backfillSearchIndexes as ur}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Rt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as hr,applyCdcChanges as pr,bumpCdcEpoch as mr,minCdcSeq as $r,readCdcChanges as wr,readCdcCursor as gr,readCdcEpoch as br,trimCdcChanges as yr}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as vt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ve}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as q}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as U,quoteIdentifier as It,AGG_VALUE as Te,AGG_COUNT as Me,AGG_KEY as Ae,jsonPathSql as K,rowToDocument as se,tableColumns as ut,isFtsAvailable as xt,tryRowToDocument as ft,geoTableName as Ct,qualifiedJsonPathSql as Ye}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as Dt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ot}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Wt,buildSeekWhere as ht,decodeCursor as Oe,applySelect as Xe,encodeCursor as We,softDeleteScope as ae,buildSeekBeforeWhere as Ft}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ze,resolveRankPartition as Bt,encodePartitionKey as qt,RANK_TIEBREAK as Ut,rankTableName as et}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Ht,buildIndexRange as Pt}from"./buildIndexRange-DIjFVgeO.mjs";import{assertFlatPredicate as Le,resolveRelationPredicates as tt}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as De,resolveWith as nt,applyOnDelete as jt,fanOutScalarCounts as Gt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Kt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Qt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ee}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Nr,advanceClientWatermark as Tr,migrateClientWatermark as Ar,readClientWatermark as Sr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Rr,deleteGlobalShapeSnapshot as vr,deleteGlobalShapeSnapshotsForConnection as Ir,migrateGlobalShapeSnapshot as xr,readGlobalShapeSnapshot as Cr,writeGlobalShapeSnapshot as kr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Lr,readIdempotent as Dr,trimIdempotent as Or,writeIdempotent as Wr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Br}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Ur}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Pr,selectShapeRows as jr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as te}from"./serializeSqlValue-DnpyaLcw.mjs";const zt=o=>{const a=new TextEncoder().encode(o);let n="";for(const d of a)n+=String.fromCodePoint(d);return btoa(n)},Vt=o=>{const a=atob(o),n=Uint8Array.from(a,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Yt=()=>new y("BAD_REQUEST","invalid cursor"),rt=16,ot=8,Y=1024,qe=(o,a)=>a.query(o),Xt=(o,a,n)=>{const d=gt(o,n);if(d.length===0)return 0;let h=0;for(const[$,N]of a.entries()){const R=$===a.length-1;let p=0;for(const w of d)(R?w.startsWith(N):w===N)&&(p+=1);if(p===0)return 0;h+=p}return h},Zt=(o,a)=>{if(!a)return{exact:!0,lower:o,upper:o};const n=o.codePointAt(o.length-1)??0,d=o.slice(0,Math.max(0,o.length-String.fromCodePoint(n).length));return{exact:!1,lower:o,upper:d+String.fromCodePoint(n+1)}},en=(o,a,n)=>{const d={eq:(h,$)=>{if(!o.definition.filterFields?.includes(h))throw new y("INTERNAL",`field "${h}" is not a filter field of search index "${o.indexName}" on table "${a}"`);if(o.filters.length>=ot)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${a}": at most ${String(ot)} .eq() filters are supported per search query`);return o.filters.push({field:h,value:$}),d},search:(h,$)=>{const N=o;if(h!==N.definition.field)throw new y("INTERNAL",`search index "${N.indexName}" on table "${a}" indexes "${N.definition.field}", not "${h}"`);const R=qe($,n).length;if(R>rt)throw new y("BAD_REQUEST",`search index "${N.indexName}" on table "${a}": at most ${String(rt)} search terms are supported (got ${String(R)})`);return N.field=h,N.query=$,N.hasQuery=!0,d}};return d},tn=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},nn=o=>Math.min(o.offset+o.numItems+1,Y),rn=o=>zt(`search:${String(o)}`),on=o=>{let a;try{a=Vt(o)}catch{return}if(!a.startsWith("search:"))return;const n=Number(a.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},an=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const a=Math.max(0,Math.floor(o.numItems)),n=o.cursor?on(o.cursor):0;if(n===void 0)throw Yt();if(n+a>Y)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(Y)}-document limit (offset ${String(n)} + ${String(a)} requested) — narrow the query or the filters instead`);return{numItems:a,offset:n}},sn=(o,a)=>{const n=a.offset+a.numItems,d=a.numItems>0&&o.length>n;return{continueCursor:d?rn(n):null,isDone:!d,page:o.slice(a.offset,n)}},ln=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const a=Math.max(0,Math.floor(o));if(a>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(a)}) — narrow the query or paginate instead`);return a},dn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cn=o=>{if(!dn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,pt=500,un=128,ie=(o,a,n)=>{const d=a??pt;if(o>d)throw new y("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},fn=o=>{const a={eq:(n,d)=>(o.sqlConditions.push({comparator:"=",field:n,value:d}),a),gt:(n,d)=>(o.sqlConditions.push({comparator:">",field:n,value:d}),a),gte:(n,d)=>(o.sqlConditions.push({comparator:">=",field:n,value:d}),a),lt:(n,d)=>(o.sqlConditions.push({comparator:"<",field:n,value:d}),a),lte:(n,d)=>(o.sqlConditions.push({comparator:"<=",field:n,value:d}),a)};return a},hn=o=>Math.max(o,Y),pn=(o,a,n,d,h)=>{const $=qe(n.query,Be(n.definition.language));if($.length===0)return[];const N=yt(a,n.indexName),R=`${N}__vocab`,p=$.length-1,w=$.map((I,S)=>{const b=Zt(I,S===p),x=b.exact?t`${t.identifier("term")} = ${b.lower}`:t`${t.identifier("term")} >= ${b.lower} AND ${t.identifier("term")} < ${b.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(S))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(R)} WHERE ${x} GROUP BY ${t.identifier("doc")}`}),D=$.map((I,S)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(S))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),T=t`SELECT f.${t.identifier(Ee)} AS ${t.identifier(Ee)}, ${t.join(D,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(w,t` UNION ALL `)}) u JOIN ${t.identifier(N)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(Ee)} HAVING ${t.join(D.map(I=>t`${I} > 0`),t` AND `)}`,A=[];for(const I of n.filters)A.push(t`${K(I.field)} = ${te(I.value)}`);h&&A.push(h);let k=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM (${T}) s JOIN ${t.identifier(a)} m ON m.id = s.${t.identifier(Ee)}`;A.length>0&&(k=t`${k} WHERE ${t.join(A,t` AND `)}`),k=t`${k} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const C=[];for(const I of q(o,k)){const S=ft(I);S&&C.push(S)}return C},mn=(o,a,n,d,h)=>{const $=Be(n.definition.language),N=qe(n.query,$);if(N.length===0)return[];const R=[];for(const T of n.filters)R.push(t`${K(T.field)} = ${te(T.value)}`);h&&R.push(h);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(hn(d)))}`;const w=q(o,p).toArray(),D=[];for(const T of w){const A=ft(T);if(!A)continue;const k=Xt(bt(A,n.definition),N,$);k>0&&D.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:k})}return D.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),D.slice(0,d).map(T=>T.doc)},$n=(o,a)=>{const n=o,d={near:(h,$)=>{if(n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.near={point:{lat:h.lat,lng:h.lng},radiusMeters:$},d},within:h=>{if(n.near)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.within={ne:{lat:h.ne.lat,lng:h.ne.lng},sw:{lat:h.sw.lat,lng:h.sw.lng}},d}};return d},wn=(o,a)=>{const n=o[a];if(n===null||typeof n!="object")return;const{lat:d,lng:h}=n;return typeof d=="number"&&typeof h=="number"?{lat:d,lng:h}:void 0},gn=(o,a)=>{const n=wn(o,a.definition.field);if(!n)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(a.near){const h=Dt(a.near.point,n);return h<=a.near.radiusMeters?{creationTime:d,distance:h}:void 0}return Lt(n,a.within)?{creationTime:d,distance:0}:void 0},bn=(o,a,n,d,h,$=()=>{})=>{if(!n.near&&!n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near(point, radius) or .within(box)`);const N=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),R=Ct(a,n.indexName),p=N.map(C=>t`(g.${t.identifier("__geohash__")} >= ${C} AND g.${t.identifier("__geohash__")} < ${`${C}{`})`),w=[t`(${t.join(p,t` OR `)})`];h&&w.push(h);const D=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM ${t.identifier(R)} g JOIN ${t.identifier(a)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)}`,T=q(o,D).toArray(),A=[];for(const C of T){const I=se(C),S=I?gn(I,n):void 0;I&&S&&A.push({creationTime:S.creationTime,distance:S.distance,doc:I})}A.sort((C,I)=>C.distance-I.distance||I.creationTime-C.creationTime);const k=A.map(C=>C.doc);return $(k.length),typeof d=="number"?k.slice(0,Math.max(0,Math.floor(d))):k},yn=(o,a,n,d,h,$=()=>{})=>{const{geo:N}=n;if(!N)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const R=n.inMemoryFilters.length>0,p=bn(o,a,N,R?void 0:h,d,$);if(!R)return p;const w=[];for(const D of p)if(n.inMemoryFilters.every(T=>T(D))&&(w.push(D),typeof h=="number"&&w.length>=h))break;return w},En=(o,a,n,d,h,$,N=()=>{})=>{const R=[];for(const T of n.sqlConditions)R.push(t`${K(T.field)} ${t.raw(T.comparator)} ${te(T.value)}`);d&&R.push(d);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY ${h}`,typeof $=="number"&&n.inMemoryFilters.length===0&&(p=t`${p} LIMIT ${t.raw(String(Math.max(0,Math.floor($))))}`);const w=q(o,p).toArray();N(w.length);const D=[];for(const T of w){const A=se(T);if(A&&n.inMemoryFilters.every(k=>k(A))&&(D.push(A),typeof $=="number"&&D.length>=$))break}return D},re={fieldRef:K,serialize:te},Nn=o=>{let a=0;const n=[],d={fieldRef:K,relationExists:h=>{const{childWhere:$,negated:N,parentTable:R,relation:p}=h,w=`__rel_${String(a)}`,D=n.at(-1)??R;a+=1,o(p.table,B);const T=p.kind==="one"?p.field:p.references,A=p.kind==="one"?p.references:p.field,k=t`${Ye(w,A)} = ${Ye(D,T)}`;n.push(w);const C=ee($,d);n.pop();const I=C?t`${k} AND ${C}`:k,S=t`EXISTS (SELECT 1 FROM ${t.identifier(p.table)} AS ${t.identifier(w)} WHERE ${I})`;return N?t`NOT ${S}`:S},serialize:te};return d},mt=o=>{const a=o.map(n=>t`${K(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||a.push(t`${K("id")} ASC`),t.join(a,t`, `)},Tn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},An=o=>{const a=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:a,field:n})):[{direction:a,field:"_creationTime"}]},Sn=(o,a,n,d)=>{const h=o.sqlConditions.map($=>({[$.field]:{[Tn[$.comparator]??"eq"]:$.value}}));if(n&&h.push(ht(a,Oe(n))),d&&h.push(Ft(a,Oe(d))),h.length!==0)return h.length===1?h[0]:{AND:h}},_n=(o,a,n)=>{const d=[];for(const h of o){const $=se(h);if($&&a.every(N=>N($))&&(d.push($),n!==void 0&&d.length>n))break}return d},Rn=(o,a,n,d,h,$=()=>{})=>{const N=Math.max(0,Math.floor(d.numItems)),R=An(n),p=typeof d.endCursor=="string",w=ee(Sn(n,R,d.cursor,d.endCursor),re),D=h&&w?t`${w} AND ${h}`:h??w;let T=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;D&&(T=t`${T} WHERE ${D}`),T=t`${T} ORDER BY ${mt(R)}`;const A=n.inMemoryFilters.length>0;!A&&!p&&(T=t`${T} LIMIT ${t.raw(String(N+1))}`);const k=q(o,T).toArray();$(k.length);const C=_n(k,n.inMemoryFilters,A||p?void 0:N);if(p){const x=C.length>=2?C[Math.floor(C.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:C,splitCursor:x?We(x,R):null}}const I=C.length>N,S=I?C.slice(0,N):C,b=S.at(-1);return{continueCursor:I&&b?We(b,R):null,isDone:!I,page:S}};class vn extends y{constructor(a="unique() found more than one matching document"){super("NOT_UNIQUE",a,{name:"NotUniqueError"})}}const In=/\s/u,xn=String.fromCodePoint(0),at=(o,a,n)=>{if(!o.tables[a])throw new y("INTERNAL",`unknown table: ${a}`);return typeof n!="string"||n.length===0||In.test(n)||n.includes(xn)?null:n},Cn=(o,a,n,d=()=>{},h=()=>{},$=()=>{})=>{const N=a.tables[n];if(!N)throw new y("INTERNAL",`unknown table: ${n}`);const R=ae(N.softDeleteMode,void 0),p=R?ee(R,re):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let D=0;const T=b=>{const{search:x}=w;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");_t(o,n,N);const M=w.inMemoryFilters.length>0,L=ln(M?void 0:b),H=xt(o)?pn(o,n,x,L,p):mn(o,n,x,L,p);if(!M)return b===void 0&&tn(H),H;const V=[];D=H.length;for(const le of H)if(w.inMemoryFilters.every(de=>de(le))&&(V.push(le),typeof b=="number"&&V.length>=b))break;return V},A=b=>{const x=an(b);return sn(T(nn(x)),x)},k=()=>{const b=w.indexFields.length>0?w.indexFields:["_creationTime"],x=w.order==="desc"?"DESC":"ASC";return t.join(b.map(M=>t`${K(M)} ${t.raw(x)}`),t`, `)},C=()=>{if(w.search||w.geo||w.indexName===void 0){h(void 0);return}h(Pt(n,w.indexName,w.indexFields,w.sqlConditions,te))},I=b=>{C();let x=0;const M=(()=>{if(w.search){const L=T(b);return x=D,L}return w.geo?yn(o,n,w,p,b,L=>{x=L}):En(o,n,w,p,k(),b,L=>{x=L})})();return $(Math.max(x,M.length)),M},S={async*[Symbol.asyncIterator](){const b=[...w.inMemoryFilters];let x;w.inMemoryFilters=[];try{for(;;){const M=await S.paginate({cursor:x??null,numItems:un});for(const L of M.page)b.every(H=>H(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;x=M.continueCursor}}finally{w.inMemoryFilters=b}},async collect(){return I(void 0)},filter(b){return w.inMemoryFilters.push(b),S},async first(){return I(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(b){return w.order=b==="desc"?"desc":"asc",S},async paginate(b){let x=0;if(C(),w.search){const L=A(b);return $(L.page.length),L}if(w.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Rn(o,n,w,b,p,L=>{x=L});return $(Math.max(x,M.page.length)),M},async take(b){return I(b)},async unique(){const b=I(w.inMemoryFilters.length>0?void 0:2);if(b.length>1)throw new vn(`unique() on table "${n}" matched ${String(b.length)} documents; expected at most one`);return b[0]??null},withGeoIndex(b,x){const M=(N.geoIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown geo index "${b}" on table "${n}"`);d(n,b,"geo");const L={definition:M,indexName:b};if(w.geo=L,x($n(L,n)),!L.near&&!L.within)throw new y("INTERNAL",`geo index "${b}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return S},withIndex(b,x){const M=N.indexes.find(L=>L.name===b);if(!M)throw new y("INTERNAL",`unknown index "${b}" on table "${n}"`);return d(n,b,"index"),w.indexName=b,w.indexFields=M.fields,x&&x(fn(w)),S},withSearchIndex(b,x){const M=(N.searchIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown search index "${b}" on table "${n}"`);d(n,b,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:b,query:""};if(w.search=L,x(en(L,n,Be(M.language))),!L.hasQuery)throw new y("INTERNAL",`search index "${b}" on table "${n}" requires a .search(field, query) call`);return S}};return S},st=(o,a,n)=>{const d={...a};for(const[h,$]of ut(o)){if($.serverDefault){d[h]=$.serverDefault({auth:n});continue}d[h]===void 0&&($.defaultFn?d[h]=$.defaultFn():"defaultValue"in $&&(d[h]=$.defaultValue))}return d},lt=(o,a,n,d)=>{const h=n;for(const[$,N]of ut(o)){if(N.serverDefault){$ in a&&(h[$]=N.serverDefault({auth:d}));continue}N.onUpdateFn&&!($ in a)&&(h[$]=N.onUpdateFn())}},dt=(o,a)=>{for(const n of Object.keys(a))if(a[n]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},kn=/unique constraint failed/i,Mn=o=>o instanceof Error&&kn.test(o.message),Fe=(o,a,n)=>{try{q(o,n)}catch(d){throw Mn(d)?new pe(`unique constraint violation on "${a}"`,"unique"):d}},Se=(o,a,n)=>{if(Fe(o,a,n),q(o,t`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${a}" — the row changed during this mutation; refetch and retry`,"occ")},ct=(o,a,n,d,h,$,N)=>{const R=[];for(let T=0;T<n.length+1;T+=1){const A=[];for(let S=0;S<T;S+=1)A.push(t`${t.identifier(n[S])} IS ${$[S]}`);const k=n[T],C=d[T];if(k!==void 0&&C!==void 0){const S=C.direction==="desc"?">":"<";A.push(t`${t.identifier(k)} ${t.raw(S)} ${$[T]}`)}else A.push(t`${t.identifier(Ut)} < ${N}`);const[I]=A;R.push(A.length===1&&I!==void 0?I:t`(${t.join(A,t` AND `)})`)}const p=t.join(R,t` OR `),w=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h} AND (${p})`).one(),D=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h}`).one();return{before:w.c,total:D.c}},ar=o=>{const{sql:a}=o,{schema:n}=o,d=o.broadcast??(()=>{}),h=(e,...r)=>{const i=n.tables[e]?.indexes;if(!i||i.length===0)return;const f=[];for(const u of r)u&&f.push(...Ht(i,u,te));return f.length>0?f:void 0},{headroom:$}=o,N=o.onRead??(()=>{}),R=o.onReadRange??(e=>{N(e.table,B)}),p=(e,r)=>{r!==void 0&&r!==B&&$?.recordRead(1),N(e,r)},w=o.onIndexUse??(()=>{}),D=o.onWrite??(()=>{}),T=async e=>{$?.recordWrite(e.doc),await D(e)},{cache:A}=o,k=o.clock??(()=>Date.now()),C=o.idGenerator??(()=>crypto.randomUUID()),I=o.scheduler??Nt,{globalDb:S}=o,b=o.auth??{identity:null,userId:null},x=o.cdc??!1,M=I,L=Jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:o.storage}),H=(e,r,i,f)=>{x&&Rt(a,k(),e,r,i,f)},V=e=>n.tables[e]?.shardMode?.kind==="global",le=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}return F},de=e=>le(e,"cascade"),J=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}},ce=()=>S,_e=(e,r)=>le(e,"relation load").findMany(e,r),Ue=(e,r)=>(V(e)&&p(e,B),_e(e,r)),$t=e=>!V(e.table),He=o.relationExistsPushDown??"auto",Pe=He!=="never",{maxRelationKeys:je}=o,me=(e,r,i)=>tt(e,{fetcher:Ue,maxRelationKeys:je,relationBaseWhere:i,schema:n,tableName:r}),Ge=async(e,r,i,f)=>{const u=J(e,"relation grouped count");if(u)return p(e,B),Gt((v,j)=>u.count(v,j),e,r,i,f);const l=n.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const s=ae(l.softDeleteMode,void 0),c={[r]:{in:i}},m=G(G(c,f),s),E=await me(m,e,void 0),g=ee(E,re),_=K(r);let W=t`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(W=t`${W} WHERE ${g}`),W=t`${W} GROUP BY ${_}`;const O=q(a,W).toArray();return new Map(O.map(v=>[v.__fk__,v.count]))};let $e=0;const Ke=new Set;for(const[e,r]of Object.entries(n.tables))for(const i of Object.values(r.triggerMap??{}))Ke.add(`${e} ${i.timing} ${i.op}`);const X=(e,r,i)=>Ke.has(`${e} ${r} ${i}`),Z=async(e,r,i)=>{if($e+=1,$e>it)throw $e-=1,new pe(`trigger recursion exceeded ${String(it)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qt({ctx:wt,event:i,op:r,schema:n,tableName:i.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Re,ensureRankBackfilled:ve,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Je,syncGeo:ge,syncRanks:he,syncSearch:be}=vt({broadcast:d,indexKeysFor:(e,r)=>h(e,r),invalidateCache:(e,r,i)=>A?.invalidate(e,r,h(e,i)),recordCdc:H,schema:n,sql:a}),Qe=(e,r,i)=>{const{shardMode:f}=r;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(i.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ne=(e,r)=>{const i=Object.entries(n.tables).filter(([,E])=>E.shardMode?.kind!=="global").map(([E])=>E).filter(E=>r===void 0||E===r);if(i.length===0)return;const f=i.map(E=>t`SELECT ${t.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(E)} WHERE id = ${e}`),u=t`${t.join(f,t` UNION ALL `)} LIMIT 1`,[l]=q(a,u).toArray();if(!l)return;const s=l.__t__,c=se(l);if(typeof s!="string"||!c)return;const m=l[U];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:c,tableName:s}},ze={assertRankPartitionLocal:Qe,ensureRankBackfilled:ve,onRead:p,rowToDocument:se,schema:n,sql:a},F={system:L,async aggregate(e,r){const i=J(e,"aggregate");if(i)return p(e,B),i.aggregate(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return F.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);p(e,B);const u=ae(f.softDeleteMode,void 0),l=G(G(r.baseWhere,r.where),u),s=await me(l,e,r.relationBaseWhere),c=s!==l;if(f.aggregateIndexes&&!r.baseWhere&&!c&&!u){const O=St(f.aggregateIndexes,r.op,r.field,r.where);if(O){Re(e,O.index);const v=Ie(O.index.by??[],O.key),j=Ce(e,O.index.name),Q=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${v}`).toArray()[0];return xe(r.op,Q)}}const m=ee(s,re),E=Ne(r.op),g=K(r.field);let _=t`SELECT ${t.raw(E)}(${g}) AS value FROM ${t.identifier(e)}`;return m&&(_=t`${_} WHERE ${m}`),q(a,_).toArray()[0]?.value??null},asId(e,r){const i=at(n,e,r);if(i===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,r){const i=J(e,"count");if(i)return p(e,B),i.count(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=Et(r);if(u.restrictsCounts)throw new ke(e);p(e,B);const l=ae(f.softDeleteMode,void 0),s=G(G(u.baseWhere,u.where),l),c=await me(s,e,u.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!u.baseWhere&&!m&&!l){const _=At(f.aggregateIndexes,u.where);if(_){Re(e,_.index);const W=Ie(_.index.by??[],_.key),O=Ce(e,_.index.name),v=q(a,t`SELECT ${Te} AS value FROM ${t.identifier(O)} WHERE ${Ae} = ${W}`).toArray();return v[0]===void 0?0:v[0].value??0}}const E=ee(c,re);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return E&&(g=t`${g} WHERE ${E}`),q(a,g).one().count},async delete(e,r,i){const f=ne(e,r);if(!f){const g=r===void 0?ce():void 0;g&&await g.delete(e,void 0,i);return}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s],m=i?.hard===!0,E=!m&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(E&&l[E]!==null&&l[E]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:l,table:s}),await jt({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,_,W)=>(await de(g).findMany(g,{includeDeleted:m,where:{[_]:W}})).page,onCascade:(g,_)=>de(g).delete(_,void 0,i),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,_,W)=>de(g).patch(_,{[W]:null}),schema:n,tableName:s}),ue(s),fe(s),E){const g={...l,[E]:k(),_id:e};Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,g,l),ge(s,e,void 0),we(s,l,g),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l,g)),H(s,e,"update",g),d({indexKeys:h(s,l,g),key:e,op:"update",row:g,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s});return}Se(a,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,void 0),ge(s,e,void 0),we(s,l,void 0),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l)),H(s,e,"delete"),d({indexKeys:h(s,l),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const i=Math.max(1,r?.chunkSize??pt),f=r?.hard===void 0?void 0:{hard:r.hard},u=V(e)?void 0:e;let l=0;for(;;){const s=(await F.findMany(e,{limit:i})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await F.delete(c,u,f),l+=1;if(s.length<i)break}return{deleted:l}},async deleteMany(e,r,i){ie(e.length,r?.limit,"deleteMany");for(const f of e)await F.delete(f,i);return{deleted:e.length}},async deleteWhere(e,r,i){const f=J(e,"deleteWhere");let u;if(f)u=(await f.findMany(e,{where:r})).page.map(l=>String(l._id));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r})).page.map(l=>String(l._id))}if(ie(u.length,i?.limit,"deleteWhere"),F.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return F.deleteMany(u,i)},async findFirst(e,r={}){return(await F.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const i=await F.findFirst(e,r);if(i===null)throw new Ot(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,r={}){const i=J(e,"findMany");if(i)return p(e,B),i.findMany(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=!r.where&&!r.baseWhere;u?p(e,B):p(e);const l=Wt(r.orderBy),s=r.cursor?ht(l,Oe(r.cursor)):void 0;let c=G(r.baseWhere,r.where);c=G(c,ae(f.softDeleteMode,r.includeDeleted)),c=await tt(c,{canPushExists:Pe?$t:void 0,existsPushMode:He==="always"?"always":"auto",fetcher:Ue,maxRelationKeys:je,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const m=Pe?Nn(p):re,E=ee(c,m);let g=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(e)}`;E&&(g=t`${g} WHERE ${E}`),g=t`${g} ORDER BY ${mt(l)}`;const _=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;_!==void 0&&(g=t`${g} LIMIT ${t.raw(String(_+1))}`);const W=q(a,g).toArray();u&&$?.recordRead(W.length);const O=[];for(const z of W){const P=se(z);P&&(O.push(P),!u&&typeof P._id=="string"&&p(e,P._id))}if(_===void 0)return r.with&&await nt({groupedCounter:Ge,fetcher:_e,parents:O,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Xe(O,r.select,r.with)};const v=O.length>_,j=v?O.slice(0,_):O,Q=j.at(-1);return r.with&&await nt({fetcher:_e,groupedCounter:Ge,parents:j,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&Q?We(Q,l):null,isDone:!v,page:Xe(j,r.select,r.with)}},async get(e,r){const i=ne(e,r);if(!i){const f=r===void 0?ce():void 0;return f?f.get(e):null}return p(i.tableName,e),i.row},async lookupById(e,r){const i=ne(e,r);return i?(p(i.tableName,e),{row:i.row,tableName:i.tableName}):null},async groupBy(e,r){const i=J(e,"groupBy");if(i)return p(e,B),i.groupBy(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const u=r.agg??{op:"count"};if(Ne(u.op),u.op!=="count"&&!u.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);const l=ae(f.softDeleteMode,void 0),s=G(G(r.baseWhere,r.where),l),c=await me(s,e,r.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!r.baseWhere&&!m&&!l){const v=Tt(f.aggregateIndexes,u.op,u.field,r.by,r.where);if(v){Re(e,v.index);const j=Ce(e,v.index.name),Q=Object.keys(v.partial),z=[];if(Q.length===(v.index.by??[]).length&&Q.length>0){const oe=Ie(v.index.by??[],v.partial),ye=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${oe}`).toArray();return ye.length>0&&z.push({key:{...v.partial},value:xe(u.op,ye[0])}),z}const P=q(a,t`SELECT ${Ae} AS key, ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)}`).toArray();for(const oe of P){const ye=JSON.parse(oe.key);z.push({key:ye,value:xe(u.op,oe)})}return z}}const E=ee(c,re),g=r.by.map(v=>t`${K(v)} AS ${t.identifier(v)}`);if(u.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=u;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw(Ne(u.op))}(${K(v)}) AS value`)}let _=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;E&&(_=t`${_} WHERE ${E}`),_=t`${_} GROUP BY ${t.join(r.by.map(v=>K(v)),t`, `)}`;const W=q(a,_).toArray(),O=[];for(const v of W){const j={};for(const z of r.by)j[z]=v[z]??null;const{value:Q}=v;O.push({key:j,value:Q==null?null:Number(Q)})}return O},async insert(e,r,i){const f=J(e,"insert");if(f){const E=await f.insert(e,r,i);return $?.recordWrite(r),d({key:E,op:"insert",row:{...r,_id:E},table:e}),E}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=st(u,r,b);De(u,l);let s;i?.clientId!==void 0?(cn(i.clientId),s=i.clientId):i?.allowExplicitId&&typeof l._id=="string"?s=l._id:s=C();const c=i?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:k(),m={...l,_creationTime:c,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ue(e),fe(e),Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES (${s}, ${c}, ${JSON.stringify(m)})`),Je(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await T({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,i){if(ie(r.length,i?.limit,"insertManyUnsafe"),r.length===0)return[];const f=J(e,"insert");if(f){const c=[];for(const m of r){const E=await f.insert(e,m,{allowExplicitId:i?.allowExplicitId});$?.recordWrite(m),d({key:E,op:"insert",row:{...m,_id:E},table:e}),c.push(E)}return c}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=r.map(c=>{const m=st(u,c,b),E=i?.allowExplicitId===!0&&typeof m._id=="string"?m._id:C(),g=i?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:k();return{creationTime:g,document:{...m,_creationTime:g,_id:E},id:E}});for(const c of l)$?.recordWrite(c.document);const s=t.join(l.map(c=>t`(${c.id}, ${c.creationTime}, ${JSON.stringify(c.document)})`),t`, `);Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES ${s}`);for(const{document:c,id:m}of l)Je(e,m,c),await D({doc:c,id:m,op:"insert",table:e});return l.map(c=>c.id)},async insertMany(e,r,i){ie(r.length,i?.limit,"insertMany");const f=i?.skipDuplicates===!0,u=[];for(const l of r)try{u.push(await F.insert(e,l))}catch(s){if(f&&s instanceof pe&&s.kind==="unique")u.push(null);else throw s}return u},normalizeId(e,r){return at(n,e,r)},async patch(e,r,i){const f=ne(e,i);if(!f){const E=i===void 0?ce():void 0;if(E){await E.patch(e,r);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s];if(!c)throw new y("INTERNAL",`unknown table: ${s}`);p(s,e),dt("patch",r);const m={...l,...r,_id:e};lt(c,r,m,b),De(c,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:l,table:s}),ue(s),fe(s),Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,m,l),ge(s,e,m),we(s,l,m),he(s,e,l,m),A?.invalidate(s,e,h(s,l,m)),H(s,e,"update",m),d({indexKeys:h(s,l,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:l,table:s}),await T({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,i){ie(e.length,r?.limit,"patchMany");for(const f of e)await F.patch(f.id,f.patch,i);return{patched:e.length}},async patchWhere(e,r,i){const f=J(e,"patchWhere");let u;if(f)u=(await f.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}))}if(ie(u.length,i?.limit,"patchWhere"),F.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await F.patchMany(u,i),{patched:u.length}},query(e){const r=J(e,"query");return r?(p(e,B),r.query(e)):Cn(a,n,e,w,i=>{i?R(i):p(e,B)},i=>$?.recordRead(i))},async rank(e,r,i){const f=J(e,"rank");if(f)return p(e,B),f.rank(e,r,i);w(e,r,"rank");const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=u.rankIndexes?.find(P=>P.name===r);if(!l)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Qe(e,u,l),i.restrictsCounts)throw new ke(e);p(e,B),ve(e,l);const s=typeof i.row=="string"?i.row:i.row._id;if(!s)return null;const c=et(e,l.name),m=l.sortBy.map((P,oe)=>Ze(oe)),E=m.map(P=>It(P)).join(", "),g=q(a,t`SELECT ${t.identifier("__partition__")}, ${t.raw(E)} FROM ${t.identifier(c)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[_]=g;if(_===void 0)return null;let W=_.__partition__;const O=G(i.baseWhere,i.where);Le(O,n,e,"rank");const v=Bt(l,O);if(v){const P=qt(l.partitionBy??[],v);if(P!==W)return null;W=P}const j=m.map(P=>_[P]),{before:Q,total:z}=ct(a,c,m,l.sortBy,W,j,s);return{position:Q+1,total:z}},async rankBefore(e,r,i){if(V(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=f.rankIndexes?.find(m=>m.name===r);if(!u)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(i.restrictsCounts)throw new ke(e);p(e,B),ve(e,u);const l=et(e,u.name),s=u.sortBy.map((m,E)=>Ze(E)),c=u.sortBy.map((m,E)=>te(i.sortValues[E]??null));return ct(a,l,s,u.sortBy,i.partitionKey,c,i.rowId)},async rankPage(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage");const f=J(e,"rankPage");if(f)return p(e,B),f.rankPage(e,r,i);w(e,r,"rank");const{continueCursor:u,hasMore:l,rows:s}=Ve(ze,e,r,i);return{continueCursor:u,isDone:!l,page:s.map(c=>c.doc)}},async rankPageRows(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage"),w(e,r,"rank");const{directions:f,hasMore:u,rows:l}=Ve(ze,e,r,i);return{directions:f,hasMore:u,rows:l}},async restore(e,r){const i=ne(e,r);if(!i){const l=r===void 0?ce():void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const f=n.tables[i.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const u=i.row[f]!==null&&i.row[f]!==void 0;await F.patch(e,{[f]:null},r),u&&he(i.tableName,e,void 0,i.row)},async replace(e,r,i,f){const u=ne(e,i);if(!u){const _=i===void 0?ce():void 0;if(_){await _.replace(e,r,void 0,f);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:s,tableName:c}=u,m=n.tables[c];if(!m)throw new y("INTERNAL",`unknown table: ${c}`);dt("replace",r);const E=f?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:k(),g={...r,_creationTime:E,_id:e};lt(m,r,g,b),De(m,g),X(c,"before","update")&&await Z("before","update",{doc:{...g},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),Se(a,c,t`UPDATE ${t.identifier(c)} SET _creationTime = ${E}, ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${l}`),be(c,e,g,s),ge(c,e,g),we(c,s,g),he(c,e,s,g),A?.invalidate(c,e,h(c,s,g)),H(c,e,"update",g),d({indexKeys:h(c,s,g),key:e,op:"update",row:g,table:c}),X(c,"after","update")&&await Z("after","update",{doc:g,id:e,op:"update",previous:s,table:c}),await T({doc:g,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),i=e?.tables,f=Object.entries(n.tables).filter(([c,m])=>r.has(c)||i!==void 0&&!i.includes(c)?!1:m.shardMode?.kind!=="global").map(([c])=>c);if(i!==void 0){for(const c of i)if(!n.tables[c])throw new y("INTERNAL",`wipeShard: unknown table: ${c}`)}const u={};let l=0;const{deleteAll:s}=F;if(s===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of f){const m=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});u[c]=m.deleted,l+=m.deleted}return{deleted:l,tables:u}}},wt={db:F,scheduler:I};return o.enforceRls===!0?Kt(F,n,(e,r)=>ne(e,r)?.tableName):F};export{hr as CDC_LOG_TABLE,Nr as CLIENT_WATERMARK_TABLE,Rr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Lr as IDEMPOTENCY_TABLE,vn as NotUniqueError,Ur as SEARCH_STATE_TABLE,Tr as advanceClientWatermark,pr as applyCdcChanges,cn as assertValidClientId,dr as backfillAggregateIndexes,cr as backfillRankIndexes,ur as backfillSearchIndexes,mr as bumpCdcEpoch,ar as createShardCtxDb,vr as deleteGlobalShapeSnapshot,Ir as deleteGlobalShapeSnapshotsForConnection,Ar as migrateClientWatermark,xr as migrateGlobalShapeSnapshot,$r as minCdcSeq,at as normalizeIdStructurally,wr as readCdcChanges,gr as readCdcCursor,br as readCdcEpoch,Sr as readClientWatermark,Cr as readGlobalShapeSnapshot,Dr as readIdempotent,Br as runShardMigrations,Pr as selectShapeMemberIds,jr as selectShapeRows,yr as trimCdcChanges,Or as trimIdempotent,kr as writeGlobalShapeSnapshot,Wr as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v=e=>{const r=new DataView(new ArrayBuffer(8));r.setFloat64(0,e,!1);let t=r.getUint32(0,!1),o=r.getUint32(4,!1);return(t&2147483648)===0?t=(t^2147483648)>>>0:(t=~t>>>0,o=~o>>>0),t.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")},x=e=>{const r=new TextEncoder().encode(e);let t="";for(const o of r)t+=o.toString(16).padStart(2,"0");return t},c=e=>{if(e===null)return"0";if(typeof e=="number")return Number.isFinite(e)?`1${v(e===0?0:e)}`:void 0;if(typeof e=="string")return`2${x(e)}`},d=e=>{const r=[];for(const t of e){const o=c(t);if(o===void 0)return;r.push(o)}return r.join("!")};const p=new Set([">",">="]),g=new Set(["<","<="]),h=(e,r,t,o)=>{const i=r.comparator==="=",n=p.has(r.comparator)||g.has(r.comparator);return!i&&!n||e.indexOf(r.field)!==t?!1:o===void 0?!0:!i&&o===r.field},m=(e,r,t)=>{const o={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of r){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(e,n,o.equalities.length,i))return;if(s){o.equalities.push(t(n.value));continue}if(i=n.field,a){if(o.lower!==void 0)return;o.lower=t(n.value),o.lowerExclusive=n.comparator===">"}else{if(o.upper!==void 0)return;o.upper=t(n.value),o.upperExclusive=n.comparator==="<"}}return o},f=(e,r)=>{const t=c(r);if(t!==void 0)return e===""?t:e+"!"+t},y=(e,r,t,o,i)=>{if(t.length===0)return;const n=m(t,o,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+""}if(!(a>=l))return{hi:l,index:r,lo:a,table:e}},E=(e,r,t)=>{const o=[];for(const i of e){const n=d(i.fields.map(s=>t(r[s])));n!==void 0&&o.push({index:i.name,key:n})}return o},w=(e,r)=>e.index===r.index&&r.key>=e.lo&&r.key<e.hi,S=(e,r)=>!e||e.length===0||!r||r.length===0?!0:e.some(t=>{const o=r.filter(i=>i.index===t.index);return o.length===0?!0:o.some(i=>w(t,i))});export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,w as rangeContains};
|