@lunora/shard-engine 1.0.0-alpha.16 → 1.0.0-alpha.17
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 +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +8 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs → DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-AcHLNxha.mjs → DEFAULT_MAX_RELAYS-CPBmX1FO.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs → DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs → DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-BItFDsAw.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-D541BOFR.mjs → RANK_TIEBREAK-DYDRmLKH.mjs} +1 -1
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +1 -0
- package/dist/packem_shared/{ReactiveCache-iWA9VRqk.mjs → ReactiveCache-Cu8IfE1M.mjs} +1 -1
- package/dist/packem_shared/aggregateTableName-DV-K7ft2.mjs +1 -0
- package/dist/packem_shared/{applyOnDelete-fMu_5DR5.mjs → applyOnDelete-BB6tr2G0.mjs} +1 -1
- package/dist/packem_shared/applySelect-i17LYhIU.mjs +1 -0
- package/dist/packem_shared/{awaitWsDrain-DKycCSBS.mjs → awaitWsDrain-Bp2jKzIb.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-tK0jrl43.mjs +1 -0
- package/dist/packem_shared/base64-fKomMf5D.mjs +1 -0
- package/dist/packem_shared/{buildPokeFrames-CCxYXd2V.mjs → buildPokeFrames-CqxaN8_H.mjs} +1 -1
- package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-B7U6t1fW.mjs → computeRankPage-CRFgJbuz.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-Gp-AesYj.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-CAJOSdN-.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-LKRHlQwE.mjs → defineEngineContractSuite-CZccUN4c.mjs} +1 -1
- package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-doD_8AwX.mjs → isSoftDeleted-Bo-y3DOe.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-BR8MvZTz.mjs → materializeExternalRows-DcCENzpV.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-n2dKcH5E.mjs +5 -0
- package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +1 -0
- package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +1 -0
- package/dist/packem_shared/sql-projection-jfoe331H.mjs +1 -0
- package/dist/packem_shared/{stableWireKey-C4JfdJ_e.mjs → stableWireKey-l3cjIt-9.mjs} +1 -1
- package/dist/packem_shared/wire-codec-Dsy70M3Q.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-B0Pb1nQZ.mjs +0 -1
- package/dist/packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs +0 -8
- package/dist/packem_shared/NotUniqueError-C32BFrv1.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DKo6dwBP.mjs +0 -1
- package/dist/packem_shared/applySelect-BjgwvZmI.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Dym8huD9.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-7fIu-E2H.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DhZLG0bn.mjs +0 -5
- package/dist/packem_shared/selectExpiredIds-DxFEwNlT.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-BD3JiZn-.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
- package/dist/packem_shared/wire-codec-D_fiax9d.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CZccUN4c.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -1892,6 +1892,12 @@ declare class RelayMember extends RelayLink {
|
|
|
1892
1892
|
private deliverShapePoke;
|
|
1893
1893
|
}
|
|
1894
1894
|
declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
|
|
1895
|
+
declare const REPROJECTION_MIGRATION_PREFIX = "__lunora_reproject__";
|
|
1896
|
+
declare const reprojectionMigrationId: (table: string) => string;
|
|
1897
|
+
declare const reprojectableFields: (definition: TableDefinitionLike) => string[];
|
|
1898
|
+
declare const reprojectionTables: (schema: SchemaLike) => string[];
|
|
1899
|
+
declare const countLegacyRows: (sql: SqlExec, table: string, fields: ReadonlyArray<string>) => number;
|
|
1900
|
+
declare const buildReprojectionMigration: (id: string, schema: SchemaLike, sql: SqlExec) => DataMigrationLike | undefined;
|
|
1895
1901
|
declare const RLS_UNWRAP_SYMBOL: symbol;
|
|
1896
1902
|
declare class RlsRequiredError extends LunoraError {
|
|
1897
1903
|
readonly table: string;
|
|
@@ -2007,4 +2013,4 @@ interface WhereSqlStrategy {
|
|
|
2007
2013
|
serialize: SerializeValue;
|
|
2008
2014
|
}
|
|
2009
2015
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2010
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, 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, relationHooks, 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 };
|
|
2016
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type 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, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, 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, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -1892,6 +1892,12 @@ declare class RelayMember extends RelayLink {
|
|
|
1892
1892
|
private deliverShapePoke;
|
|
1893
1893
|
}
|
|
1894
1894
|
declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
|
|
1895
|
+
declare const REPROJECTION_MIGRATION_PREFIX = "__lunora_reproject__";
|
|
1896
|
+
declare const reprojectionMigrationId: (table: string) => string;
|
|
1897
|
+
declare const reprojectableFields: (definition: TableDefinitionLike) => string[];
|
|
1898
|
+
declare const reprojectionTables: (schema: SchemaLike) => string[];
|
|
1899
|
+
declare const countLegacyRows: (sql: SqlExec, table: string, fields: ReadonlyArray<string>) => number;
|
|
1900
|
+
declare const buildReprojectionMigration: (id: string, schema: SchemaLike, sql: SqlExec) => DataMigrationLike | undefined;
|
|
1895
1901
|
declare const RLS_UNWRAP_SYMBOL: symbol;
|
|
1896
1902
|
declare class RlsRequiredError extends LunoraError {
|
|
1897
1903
|
readonly table: string;
|
|
@@ -2007,4 +2013,4 @@ interface WhereSqlStrategy {
|
|
|
2007
2013
|
serialize: SerializeValue;
|
|
2008
2014
|
}
|
|
2009
2015
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2010
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, 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, relationHooks, 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 };
|
|
2016
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type 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, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, 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, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, 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 s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.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-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-DKo6dwBP.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C32BFrv1.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,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-D__2M4gX.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{k as ie}from"./packem_shared/ctx-db-companions-7fIu-E2H.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-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-B7U6t1fW.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-BD3JiZn-.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.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-B6rnz3so.mjs";import{AGG_COUNT as Ve,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,rowToDocument as tr,tableColumns as nr,tryRowToDocument as lr}from"./packem_shared/AGG_COUNT-B0Pb1nQZ.mjs";import{param as ir,renderSql as mr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as pr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as hr,runExternalSourceTick as Ar}from"./packem_shared/materializeExternalRows-BR8MvZTz.mjs";import{isSoftDeleted as Cr,isSourceDue as Ir,pullExternalSourceIncrementalTick as _r,pullExternalSourceTick as Rr}from"./packem_shared/isSoftDeleted-doD_8AwX.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Fr,haversineMeters as Or,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Pr,ADMIN_FUNCTION_PREFIX as Br,DEFAULT_FANOUT_TOPIC_LIMIT as Gr,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Hr,recordFanoutPass as Vr,selectMatchingIds as Xr,summarizeFanoutTopics as Qr,summarizeSubscriptions as Yr}from"./packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as lo,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as mo,buildSeekBeforeWhere as po,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-BjgwvZmI.mjs";import{QUEUE_TABLE as go,clearQueueMessages as ho,isLossyBody as Ao,readQueueMessageById as Eo,readQueueMessages as Co,recordQueueMessages as Io}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as Ro,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Fo}from"./packem_shared/RANK_TIEBREAK-D541BOFR.mjs";import{ReactiveCache as Do,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-iWA9VRqk.mjs";import{createReadFootprint as Bo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Ho,isRelationPredicate as Vo,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs";import{applyOnDelete as Yo,distinctValues as jo,fanOutScalarCounts as Jo,relationHooks as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-fMu_5DR5.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-BdmnUGLO.mjs";import{DEFAULT_MAX_RELAYS as ia,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-CCxYXd2V.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as ka}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-DKycCSBS.mjs";import{mergeChangedKeys as Va,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-BH5q0Ror.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-DxFEwNlT.mjs";import{compileWhereSql as it}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{quoteIdentifier as ct}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ut}from"./packem_shared/runShardMigrations-DhZLG0bn.mjs";import{stableStringify as ft}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as gt}from"./packem_shared/stableWireKey-C4JfdJ_e.mjs";export{Pr as ADMIN_FUNCTIONS,Br as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,Gr as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,ia as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,to as NotFoundError,k as NotUniqueError,ma as OwnerRelay,go as QUEUE_TABLE,Ro as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Do 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,V as appendCdcChange,X as applyCdcChanges,Yo as applyOnDelete,mo as applySelect,lo as armRestore,vo as assertFlatPredicate,Ga as assertReadonly,zo as assertShapeShardable,P as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,ba as buildPokeFrames,po as buildSeekBeforeWhere,co as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,$r as clearCapturedMail,ho as clearQueueMessages,T as coerceAggregateNumber,it as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Bo as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,So as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,pr as diffExternalSource,ya as diffGlobalMembership,jo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Fr as encodeGeohash,Lo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Or as haversineMeters,_e as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Ao as isLossyBody,Vo as isRelationPredicate,Cr as isSoftDeleted,Ir as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Ua as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,Va 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,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Dr as pointInBoundingBox,Ma as projectColumns,_r as pullExternalSourceIncrementalTick,Rr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,ct as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,Pe as readMigrationStatus,Eo as readQueueMessageById,Co as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,oo as recordCapturedMail,Xa as recordChangedKeys,Vr as recordFanoutPass,Io as recordQueueMessages,Aa as recordSchemaVersion,Zo as relationHooks,na as relayCountFor,mr as renderSql,Mo as resolveRankPartition,Xo as resolveRelationPredicates,$o as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Ar as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ut as runShardMigrations,ka as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,s as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,fo as softDeleteScope,Fo as sortColumnName,ft as stableStringify,gt as stableWireKey,va as subscriptionListDeltas,Qr as summarizeFanoutTopics,Yr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,lr as tryRowToDocument,za as trySendFrame,i 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 s,selectExportTables as l,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as A}from"./packem_shared/aggregateTableName-DV-K7ft2.mjs";import{CountRlsUnsupportedError as I,mergeWhere as C,planAggregateLookup as R,selectIndexForAggregate as _,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-BItFDsAw.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-tK0jrl43.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{k as ie}from"./packem_shared/ctx-db-companions-CAJOSdN-.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as Ae,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Ce,hydrateDocsById as Re}from"./packem_shared/computeRankPage-CRFgJbuz.mjs";import{SEARCH_STATE_TABLE as be,migrateSearchState as Le,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-BdBcbrUP.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.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-B6rnz3so.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as sr}from"./packem_shared/do-sql-1Yi1_Yq0.mjs";import{param as ir,renderSql as mr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as dr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as Er,runExternalSourceTick as Ar}from"./packem_shared/materializeExternalRows-DcCENzpV.mjs";import{isSoftDeleted as Ir,isSourceDue as Cr,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as _r}from"./packem_shared/isSoftDeleted-Bo-y3DOe.mjs";import{GEO_DEFAULT_PRECISION as Lr,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Or,haversineMeters as Fr,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as kr,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Br,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Hr,recordFanoutPass as Vr,selectMatchingIds as Xr,summarizeFanoutTopics as jr,summarizeSubscriptions as Qr}from"./packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as so,readBookmark as lo}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as mo,buildSeekBeforeWhere as po,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-i17LYhIU.mjs";import{QUEUE_TABLE as go,clearQueueMessages as Eo,isLossyBody as Ao,readQueueMessageById as ho,readQueueMessages as Io,recordQueueMessages as Co}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as _o,encodePartitionKey as bo,matchesRankStaticWhere as Lo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-DYDRmLKH.mjs";import{ReactiveCache as Do,reactiveCacheKey as Po}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Ho,isRelationPredicate as Vo,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs";import{applyOnDelete as Qo,distinctValues as Yo,fanOutScalarCounts as Jo,relationHooks as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-BB6tr2G0.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as sa}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ia,OwnerRelay as ma,RelayMember as pa,createRelayLink as da}from"./packem_shared/DEFAULT_MAX_RELAYS-CPBmX1FO.mjs";import{buildReprojectionMigration as Sa,countLegacyRows as ua,reprojectableFields as xa,reprojectionTables as fa}from"./packem_shared/buildReprojectionMigration-Ctl4r84d.mjs";import{RLS_UNWRAP_SYMBOL as ga,RlsRequiredError as Ea,guardWriter as Aa}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ia,readSchemaHistory as Ca,readSchemaVersion as Ra,recordSchemaVersion as _a}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as La}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as Na,isDevEnvironment as Ma}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Fa,diffGlobalMembership as Da,encodeRowsPatch as Pa,projectColumns as ka}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as Ba}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as wa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as qa,assertReadonly as Wa,lintReadonlySql as va,runReadonlySql as za}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Va,sendDeltaFrames as Xa,subscriptionListDeltas as ja,trySendFrame as Qa}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as Ja,recordChangedKeys as Za,writeTouchesMemo as $a}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as rt}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as at}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as nt,TransactionHeadroomTracker as st}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs";import{hasTrigger as it,runTriggers as mt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as dt}from"./packem_shared/selectExpiredIds-C6nQK7E2.mjs";import{compileWhereSql as St}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as xt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Tt,reprojectionMigrationId as gt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as At}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as It}from"./packem_shared/runShardMigrations-n2dKcH5E.mjs";import{stableStringify as Rt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as bt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{kr as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,at as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Br as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,ia as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,nt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,Lr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,qa as MAX_SQL_ROWS,to as NotFoundError,P as NotUniqueError,ma as OwnerRelay,go as QUEUE_TABLE,_o as RANK_TIEBREAK,xt as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,Tt as REPROJECTION_MIGRATION_PREFIX,ga as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,pa as RelayMember,Ea as RlsRequiredError,Ue as SCAN_DEP,Ia as SCHEMA_HISTORY_MAX_VERSIONS,be as SEARCH_STATE_TABLE,Ba as ShardRunner,st as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Qo as applyOnDelete,mo as applySelect,so as armRestore,vo as assertFlatPredicate,Wa as assertReadonly,zo as assertShapeShardable,k as assertValidClientId,Va as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,Fa as buildPokeFrames,Sa as buildReprojectionMigration,po as buildSeekBeforeWhere,co as buildSeekWhere,Na as buildSettings,j as bumpCdcEpoch,aa as clampPromotionThresholds,$r as clearCapturedMail,Eo as clearQueueMessages,T as coerceAggregateNumber,St as compileWhereSql,Ce as computeRankPage,Ho as containsRelationPredicate,ua as countLegacyRows,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,da as createRelayLink,G as createShardCtxDb,rt as createSystemReader,So as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,dr as diffExternalSource,Da as diffGlobalMembership,Yo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Pa as encodeRowsPatch,O as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,E as foldAggregateTally,Ze as geoTableName,Aa as guardWriter,it as hasTrigger,Fr as haversineMeters,Re as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,Ma as isDevEnvironment,$e as isFtsAvailable,Ao as isLossyBody,Vo as isRelationPredicate,Ir as isSoftDeleted,Cr as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,va as lintReadonlySql,zr as listTables,Lo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,Ja as mergeChangedKeys,C as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,Le as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,s as parseImportShardArgs,R as planAggregateLookup,Dr as pointInBoundingBox,ka as projectColumns,Rr as pullExternalSourceIncrementalTick,_r as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,At as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,Po as reactiveCacheKey,A as readAggregateValue,F as readAuditLog,lo as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Er as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,ho as readQueueMessageById,Io as readQueueMessages,Ca as readSchemaHistory,Ra as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,oo as recordCapturedMail,Za as recordChangedKeys,Vr as recordFanoutPass,Co as recordQueueMessages,_a as recordSchemaVersion,Zo as relationHooks,na as relayCountFor,mr as renderSql,xa as reprojectableFields,gt as reprojectionMigrationId,fa as reprojectionTables,Mo as resolveRankPartition,Xo as resolveRelationPredicates,$o as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,Ar as runExternalSourceTick,za as runReadonlySql,ea as runRowValidators,It as runShardMigrations,wa as runSocketPool,ze as runSql,mt as runTriggers,dt as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,Xr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,Xa as sendDeltaFrames,La as serializeSqlValue,sa as shapeRoutingKey,fo as softDeleteScope,Oo as sortColumnName,Rt as stableStringify,bt as stableWireKey,ja as subscriptionListDeltas,jr as summarizeFanoutTopics,Qr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,sr as tryRowToDocument,Qa as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,$a as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{j as L,s as O}from"./do-sql-1Yi1_Yq0.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},U=50,f=500,D=30,q=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[O]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],i=typeof _=="string"?k(_):void 0;if(i===void 0)return{columns:e,rows:t};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...u,...W(i)})}const r=e.filter(s=>s!==m),n=[],o=new Set(r);for(const s of a)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...r,...n],rows:a}},R=e=>e.replaceAll(/[\\%_]/g,t=>`\\${t}`),E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,t,a)=>Math.min(Math.max(e,t),a),w=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},ne=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)E(r)||a.push({name:r,rowCount:w(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:n}=a;return e.operator==="contains"?{params:[...n,`%${R(B(e.value))}%`],sql:String.raw`CAST(${r} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),n=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||n!==void 0&&(n<1||n>31)||a<100)return;const o=Date.UTC(a,(r??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(a,(r??1)-1,n+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:o,to:s}},C=(e,t,a)=>{const r=[],n=[];if(t!==""&&e.length>0){const o=`%${R(t)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=X(t);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);r.push(`(${s.join(" OR ")})`)}for(const o of a??[]){const s=H(o,e);s!==void 0&&(r.push(`(${s.sql})`),n.push(...s.params))}return r.length===0?void 0:{parameters:n,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},oe=(e,t)=>{const{table:a}=t;A(e,a);const r=I(Math.trunc(t.limit??U),1,f),n=Math.max(0,Math.trunc(t.offset??0)),o=d(a),s=b(e,o),_=t.search?.trim()??"",i=h=>{if(t.refs===void 0)return h;const S={};for(const $ of h.columns){const y=t.refs[$];y!==void 0&&(S[$]=y)}return Object.keys(S).length>0?{...h,refs:S}:h},u=C(s,_,t.filters),l=K(t.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],N=l?.params??[];let v;t.skipCount||(v=u===void 0?w(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${o}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,n).toArray();return i({...j(s,F),total:v})},_e=(e,t)=>{const{table:a}=t;A(e,a);const r=I(Math.trunc(t.limit??f),1,f),n=d(a),o=b(e,n),s=t.search?.trim()??"",_=C(o,s,t.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),u=i.length>r,l=i.slice(0,r).map(c=>c.id);return{hasMore:u,ids:l}},Y=(e,t,a)=>{const r=new Set(a.filter(o=>o!==m));if(!a.includes(m))return r;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:o}of n){const s=typeof o=="string"?k(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;A(e,r);const n=d(r),o=b(e,n);if(!Y(e,n,o).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,o);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=I(Math.trunc(t.limit??D),1,q),i=t.search?.trim()??"",u=C(o,i,t.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],p=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();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},n=a.slice(0,f);for(const s of n)r[s]=[];if(n.length===0)return{references:r,storageColumns:t};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(E(s)||!x(e,s))continue;const i=d(s),u=b(e,i);for(const l of _){const c=M(l,u);if(c===void 0)continue;const p=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 p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,n)=>{const o=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:n,subscriptions:o}}),a=t.reduce((r,n)=>r+n.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of o.whispers??[])r.set(s,(r.get(s)??0)+1)}const n=[...[...a].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...r].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,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,ne as listTables,oe as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-1Yi1_Yq0.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dsy70M3Q.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{L as C,g as l}from"./do-sql-1Yi1_Yq0.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`)},m=(t,i,r,E,s,c)=>{const o=c===void 0?null:C(c);a(t,e`INSERT INTO ${e.identifier(d)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${r}, ${E}, ${s}, ${o})`)},q=(t,i={})=>{const r=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),s=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(o=>e`${o}`),e`, `)})`:e``,c=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(d)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${E}`).toArray().map(o=>{const T={id:o.id,op:o.op,seq:o.seq,table:o.table,ts:o.ts};return o.doc===null?T:{...T,doc:l(o.doc)}});return{changes:c,cursor:c.at(-1)?.seq??r}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(d)} WHERE seq <= ${i}`)},S=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${d}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??0},h=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},u=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${r})`),r},M=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},$=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const r=i.doc??{};try{await t.insert(i.table,r,{allowExplicitId:!0})}catch(E){if(!(E instanceof L))throw E;const s={...r};delete s._id,await t.replace(i.id,s,void 0,{allowExplicitId:!0})}},b=async(t,i)=>{for(const r of i)await $(t,r)};export{d as CDC_LOG_TABLE,n as CDC_META_TABLE,m as appendCdcChange,b as applyCdcChanges,M as bumpCdcEpoch,I as migrateCdcLog,p as migrateCdcMeta,h as minCdcSeq,q as readCdcChanges,S as readCdcCursor,u as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-BB6tr2G0.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-AcHLNxha.mjs → DEFAULT_MAX_RELAYS-CPBmX1FO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{a as E,s as g}from"./wire-codec-D_fiax9d.mjs";import{relayName as y,nextPromotionState as k,shapeRoutingKey as f,parseRelayName as L,clampPromotionThresholds as N,DEFAULT_PROMOTION_THRESHOLDS as R}from"./DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";import{encodeRowsPatch as C,buildPokeFrames as A}from"./buildPokeFrames-CCxYXd2V.mjs";import{awaitWsDrain as O,trySendFrame as w}from"./awaitWsDrain-DKycCSBS.mjs";import{stableWireKey as p}from"./stableWireKey-C4JfdJ_e.mjs";const T=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},D=2,F=8,$="LUNORA_RELAY_SECRET",I="x-lunora-relay-sig",b=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},_=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},m=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class v{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=b(this.host.env());if(s!==void 0){const a=e.headers.get(I),o=await _(s,t);if(a===null||!T(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),u();case"relay_detach":return this.onDetach(r.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),u();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:g(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),u()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:g(r.args)}));default:return U(r)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",F)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=b(this.host.env());n!==void 0&&(o[I]=await _(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends v{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",R.tUp),s=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",R.tDown);if(this.promotionState=k(this.promotionState,e,N(t,s)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",D);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(y(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,t)}catch{return}if(o===void 0||o.global===!0||!s.has(o.table))return;const n=e,h=n.cursor,c=this.host.buildShapeDiff(o,h,r);if(c.length!==0)return n.cursor=r,{args:E(e.args),checkpoint:r,epoch:a,fromCursor:h,name:e.name,rowsPatch:C(c),type:"relay_shape_poke"}}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const n=this.buildShapePoke(o,S,e,t,r);if(n)for(const h of s)a.push(this.postRelayMessage(y(this.roleId.ownerKey,h),n))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,t,s);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:l}=P(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:l.code,message:l.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let l=this.relayShapeRegistry.get(d);l===void 0&&(l={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,l)),h=l.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const c=A([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:c}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=p(s.effectiveWhere),a=p(s.columns);let o=!1;const n=h=>{const c={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(c,{get:(d,l)=>typeof l=="symbol"||l in d?Reflect.get(d,l):`${h}:${l}`,getOwnPropertyDescriptor:(d,l)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,l)),has:(d,l)=>typeof l=="symbol"?Reflect.has(d,l):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let c;try{c=this.host.resolveShape(e,t,h)}catch{return!1}return c!==void 0&&c.global!==!0&&c.table===s.table&&p(c.effectiveWhere)===r&&p(c.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends v{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:E(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await O(e);for(const h of n.frames)w(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,c]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(c.name,c.args)!==t)continue;const l=A([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const x of l)w(r,x);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const X=i=>{const e=i.doName();if(e===void 0)return;const t=L(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{F as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,X as createRelayLink};
|
|
1
|
+
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{a as E,s as g}from"./wire-codec-Dsy70M3Q.mjs";import{relayName as y,nextPromotionState as k,shapeRoutingKey as f,parseRelayName as L,clampPromotionThresholds as N,DEFAULT_PROMOTION_THRESHOLDS as R}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{encodeRowsPatch as C,buildPokeFrames as A}from"./buildPokeFrames-CqxaN8_H.mjs";import{awaitWsDrain as O,trySendFrame as w}from"./awaitWsDrain-Bp2jKzIb.mjs";import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";const T=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},D=2,F=8,$="LUNORA_RELAY_SECRET",I="x-lunora-relay-sig",b=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},_=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},m=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class v{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=b(this.host.env());if(s!==void 0){const a=e.headers.get(I),o=await _(s,t);if(a===null||!T(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),u();case"relay_detach":return this.onDetach(r.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),u();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:g(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),u()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:g(r.args)}));default:return U(r)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",F)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=b(this.host.env());n!==void 0&&(o[I]=await _(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends v{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",R.tUp),s=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",R.tDown);if(this.promotionState=k(this.promotionState,e,N(t,s)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",D);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(y(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,t)}catch{return}if(o===void 0||o.global===!0||!s.has(o.table))return;const n=e,h=n.cursor,c=this.host.buildShapeDiff(o,h,r);if(c.length!==0)return n.cursor=r,{args:E(e.args),checkpoint:r,epoch:a,fromCursor:h,name:e.name,rowsPatch:C(c),type:"relay_shape_poke"}}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const n=this.buildShapePoke(o,S,e,t,r);if(n)for(const h of s)a.push(this.postRelayMessage(y(this.roleId.ownerKey,h),n))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,t,s);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:l}=P(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:l.code,message:l.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let l=this.relayShapeRegistry.get(d);l===void 0&&(l={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,l)),h=l.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const c=A([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:c}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=p(s.effectiveWhere),a=p(s.columns);let o=!1;const n=h=>{const c={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(c,{get:(d,l)=>typeof l=="symbol"||l in d?Reflect.get(d,l):`${h}:${l}`,getOwnPropertyDescriptor:(d,l)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,l)),has:(d,l)=>typeof l=="symbol"?Reflect.has(d,l):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let c;try{c=this.host.resolveShape(e,t,h)}catch{return!1}return c!==void 0&&c.global!==!0&&c.table===s.table&&p(c.effectiveWhere)===r&&p(c.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends v{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:E(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await O(e);for(const h of n.frames)w(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,c]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(c.name,c.args)!==t)continue;const l=A([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const x of l)w(r,x);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const X=i=>{const e=i.doName();if(e===void 0)return;const t=L(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{F as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,X as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-l3cjIt-9.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{o as e}from"./estimate-bytes-Drp8rhPs.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){this.writtenRows+=1;const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{n as xt,k as It,x as Pe,T as ye,y as vt,c as Ct}from"./ctx-db-companions-CAJOSdN-.mjs";import{sql as n}from"drizzle-orm";import{s as kt}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Ne,normalizeCountArgument as Mt,throwingScheduler as Lt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ve,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-DV-K7ft2.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Me,selectIndexForGroupBy as Dt,selectIndexForCount as Ft,selectIndexForAggregate as Ot}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Wt}from"./backfillAggregateIndexes-tK0jrl43.mjs";import{backfillAggregateIndexes as Tr,backfillRankIndexes as _r,backfillSearchIndexes as Rr}from"./backfillAggregateIndexes-tK0jrl43.mjs";import{appendCdcChange as Bt}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{CDC_LOG_TABLE as xr,applyCdcChanges as Ir,bumpCdcEpoch as vr,minCdcSeq as Cr,readCdcChanges as kr,readCdcCursor as Mr,readCdcEpoch as Lr,trimCdcChanges as Dr}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{computeRankPage as tt}from"./computeRankPage-CRFgJbuz.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{a as P,L as se,p as Se,T as Le,c as Te,N as Y,E as ce,I as wt,C as qt,D as gt,h as Ut,O as nt}from"./do-sql-1Yi1_Yq0.mjs";import{coveringGeohashes as Pt,boundingBoxGeohashes as Ht,pointInBoundingBox as jt,haversineMeters as Kt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as Gt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Qt,buildSeekWhere as bt,decodeCursor as Be,applySelect as rt,encodeCursor as qe,softDeleteScope as le,buildSeekBeforeWhere as zt}from"./applySelect-i17LYhIU.mjs";import{sortColumnName as ot,resolveRankPartition as Vt,encodePartitionKey as Yt,RANK_TIEBREAK as Jt,rankTableName as it}from"./RANK_TIEBREAK-DYDRmLKH.mjs";import{indexKeysForRow as Xt,buildIndexRange as Zt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as De,resolveRelationPredicates as at}from"./DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs";import{runRowValidators as Fe,resolveWith as st,relationHooks as dt,applyOnDelete as en,fanOutScalarCounts as tn}from"./applyOnDelete-BB6tr2G0.mjs";import{guardWriter as nn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as rn}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as on}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as an}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as Or,advanceClientWatermark as Wr,migrateClientWatermark as Br,readClientWatermark as qr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Pr,deleteGlobalShapeSnapshot as Hr,deleteGlobalShapeSnapshotsForConnection as jr,migrateGlobalShapeSnapshot as Kr,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Qr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Vr,readIdempotent as Yr,trimIdempotent as Jr,writeIdempotent as Xr}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as eo}from"./runShardMigrations-n2dKcH5E.mjs";import{SEARCH_STATE_TABLE as no}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as oo,selectShapeRows as io}from"./selectShapeMemberIds-BdBcbrUP.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as sn}from"./quoteIdentifier-CObIFRhb.mjs";const dn=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},ln=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},cn=()=>new b("BAD_REQUEST","invalid cursor"),lt=16,ct=8,X=1024,He=(o,i)=>i.query(o),un=(o,i,t)=>{const d=xt(o,t);if(d.length===0)return 0;let c=0;for(const[p,w]of i.entries()){const A=p===i.length-1;let y=0;for(const g of d)(A?g.startsWith(w):g===w)&&(y+=1);if(y===0)return 0;c+=y}return c},fn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const c=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:c+String.fromCodePoint(d)}},hn=(o,i,t)=>{const d={eq:(c,p)=>{if(!o.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=ct)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(ct)} .eq() filters are supported per search query`);return o.filters.push({field:c,value:p}),d},search:(c,p)=>{const w=o;if(c!==w.definition.field)throw new b("INTERNAL",`search index "${w.indexName}" on table "${i}" indexes "${w.definition.field}", not "${c}"`);const A=He(p,t).length;if(A>lt)throw new b("BAD_REQUEST",`search index "${w.indexName}" on table "${i}": at most ${String(lt)} search terms are supported (got ${String(A)})`);return w.field=c,w.query=p,w.hasQuery=!0,d}};return d},pn=o=>{if(o.length>X)throw new b("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},mn=o=>Math.min(o.offset+o.numItems+1,X),$n=o=>dn(`search:${String(o)}`),wn=o=>{let i;try{i=ln(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},gn=o=>{if(typeof o.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?wn(o.cursor):0;if(t===void 0)throw cn();if(t+i>X)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?$n(t):null,isDone:!d,page:o.slice(i.offset,t)}},En=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new b("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Nn=o=>{if(!yn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},ut=50,Et=500,Sn=128,de=(o,i,t)=>{const d=i??Et;if(o>d)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Tn=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},_n=o=>Math.max(o,X),yt=(o,i)=>{const t=o.filters.map(d=>n`${Y(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Rn=(o,i,t,d,c)=>{const p=He(t.query,Pe(t.definition.language));if(p.length===0)return[];const w=Ct(i,t.indexName),A=`${w}__vocab`,y=p.length-1,g=p.map((L,M)=>{const H=fn(L,M===y),W=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(M))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${W} GROUP BY ${n.identifier("doc")}`}),N=p.map((L,M)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(M))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(ye)} AS ${n.identifier(ye)}, ${n.join(N,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(ye)} HAVING ${n.join(N.map(L=>n`${L} > 0`),n` AND `)}`,_=yt(t,c);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(ye)}`;_.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 F=[];for(const L of B(o,C)){const M=gt(L);if(M){const H=L.__score__;F.push({document:M,score:typeof H=="number"?H:Number(H??0)})}}return F},An=(o,i,t,d,c)=>{const p=Pe(t.definition.language),w=He(t.query,p);if(w.length===0)return[];const A=yt(t,c);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(_n(d)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=gt(S);if(!_)continue;const C=un(vt(_,t.definition),w,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,d).map(S=>({document:S.doc,score:S.score}))},Oe=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},xn=(o,i)=>{const t=o,d={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(c,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},d},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(c.sw,".within() sw corner",i,t.indexName),Oe(c.ne,".within() ne corner",i,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},d}};return d},In=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:c}=t;return typeof d=="number"&&typeof c=="number"?{lat:d,lng:c}:void 0},vn=(o,i)=>{const t=In(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const c=Kt(i.near.point,t);return c<=i.near.radiusMeters?{creationTime:d,distance:c}:void 0}return jt(t,i.within)?{creationTime:d,distance:0}:void 0},Cn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=t.near?Pt(t.near.point,t.near.radiusMeters):Ht(t.within),p=Ut(i,t.indexName),w=c.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),A=[n`(${n.join(w,n` OR `)})`];d&&A.push(d);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=ce(S),C=_?vn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},Nt=(o,i,t,d)=>{const c=[];for(const p of o)if(i.every(w=>w(d(p)))&&(c.push(p),typeof t=="number"&&c.length>=t))break;return c},kn=(o,i,t,d,c,p=()=>{})=>{const w=t.within!==void 0,A=Cn(o,i,t,c).map(y=>({distanceMeters:w?null:y.distance,document:y.doc}));return p(A.length),typeof d=="number"?A.slice(0,Math.max(0,Math.floor(d))):A},St=(o,i,t,d,c,p=()=>{})=>{const{geo:w}=t;if(!w)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=kn(o,i,w,A?void 0:c,d,p);return A?Nt(y,t.inMemoryFilters,c,g=>g.document):y},Mn=(o,i,t,d,c,p=()=>{})=>St(o,i,t,d,c,p).map(w=>w.document),Ln=(o,i,t,d,c,p,w=()=>{})=>{const A=[];for(const S of t.sqlConditions)A.push(n`${Y(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);d&&A.push(d);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();w(g.length);const N=[];for(const S of g){const _=ce(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:Y,serialize:ie},We=(o,i,t)=>{const d=o.shape[i];if(d&&rn(d))throw new b("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Dn=o=>{let i=0;const t=[],d={fieldRef:Y,relationExists:c=>{const{childWhere:p,negated:w,parentTable:A,relation:y}=c,g=`__rel_${String(i)}`,N=t.at(-1)??A;i+=1,o(y.table,U);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${nt(g,_)} = ${nt(N,S)}`;t.push(g);const F=ne(p,d);t.pop();const L=F?n`${C} AND ${F}`:C,M=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${L})`;return w?n`NOT ${M}`:M},serialize:ie};return d},Tt=o=>{const i=o.map(t=>n`${Y(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${Y("id")} ASC`),n.join(i,n`, `)},Fn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},On=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Wn=(o,i,t,d)=>{const c=o.sqlConditions.map(p=>({[p.field]:{[Fn[p.comparator]??"eq"]:p.value}}));if(t&&c.push(bt(i,Be(t))),d&&c.push(zt(i,Be(d))),c.length!==0)return c.length===1?c[0]:{AND:c}},Bn=(o,i,t)=>{const d=[];for(const c of o){const p=ce(c);if(p&&i.every(w=>w(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},qn=(o,i,t,d,c,p=()=>{})=>{const w=Math.max(0,Math.floor(d.numItems)),A=On(t),y=typeof d.endCursor=="string",g=ne(Wn(t,A,d.cursor,d.endCursor),oe),N=c&&g?n`${g} AND ${c}`:c??g;let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${Tt(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String(w+1))}`);const C=B(o,S).toArray();p(C.length);const F=Bn(C,t.inMemoryFilters,_||y?void 0:w);if(y){const W=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:F,splitCursor:W?qe(W,A):null}}const L=F.length>w,M=L?F.slice(0,w):F,H=M.at(-1);return{continueCursor:L&&H?qe(H,A):null,isDone:!L,page:M}};class Un extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Pn=/\s/u,Hn=String.fromCodePoint(0),ft=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Pn.test(t)||t.includes(Hn)?null:t},jn=(o,i,t,d=()=>{},c=()=>{},p=()=>{})=>{const w=i.tables[t];if(!w)throw new b("INTERNAL",`unknown table: ${t}`);const A=le(w.softDeleteMode,void 0),y=A?ne(A,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Wt(o,t,w);const I=g.inMemoryFilters.length>0,k=En(I?void 0:E),j=qt(o)?Rn(o,t,v,k,y):An(o,t,v,k,y);return I?(N=j.length,Nt(j,g.inMemoryFilters,E,te=>te.document)):(E===void 0&&pn(j),j)},_=E=>S(E).map(v=>v.document),C=E=>{const v=gn(E);return bn(_(mn(v)),v)},F=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${Y(I)} ${n.raw(v)}`),n`, `)},L=()=>{if(g.search||g.geo||g.indexName===void 0){c(void 0);return}c(Zt(t,g.indexName,g.indexFields,g.sqlConditions,ie))},M=E=>{L();let v=0;const I=(()=>{if(g.search){const k=_(E);return v=N,k}return g.geo?Mn(o,t,g,y,E,k=>{v=k}):Ln(o,t,g,y,F(),E,k=>{v=k})})();return p(Math.max(v,I.length)),I},H=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return St(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},W={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await W.paginate({cursor:v??null,numItems:Sn});for(const k of I.page)E.every(j=>j(k))&&(yield k);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return H()},filter(E){return g.inMemoryFilters.push(E),W},async first(){return M(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",W},async paginate(E){let v=0;if(L(),g.search){const k=C(E);return p(k.page.length),k}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=qn(o,t,g,E,y,k=>{v=k});return p(Math.max(v,I.page.length)),I},async take(E){return M(E)},async unique(){const E=M(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Un(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=(w.geoIndexes??[]).find(j=>j.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:I,indexName:E};if(g.geo=k,v(xn(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return W},withIndex(E,v){const I=w.indexes.find(k=>k.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(Tn(g)),W},withSearchIndex(E,v){const I=(w.searchIndexes??[]).find(j=>j.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=k,v(hn(k,t,Pe(I.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return W}};return W},ht=(o,i,t)=>{const d={...i};for(const[c,p]of wt(o)){if(p.serverDefault){d[c]=p.serverDefault({auth:t});continue}d[c]===void 0&&(p.defaultFn?d[c]=p.defaultFn():"defaultValue"in p&&(d[c]=p.defaultValue))}return d},pt=(o,i,t,d)=>{const c=t;for(const[p,w]of wt(o)){if(w.serverDefault){p in i&&(c[p]=w.serverDefault({auth:d}));continue}w.onUpdateFn&&!(p in i)&&(c[p]=w.onUpdateFn())}},mt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Kn=/unique constraint failed/i,Gn=o=>o instanceof Error&&Kn.test(o.message),Ue=(o,i,t)=>{try{B(o,t)}catch(d){throw Gn(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},_e=(o,i,t)=>{if(Ue(o,i,t),B(o,n`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},$t=(o,i,t,d,c,p,w)=>{const A=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let M=0;M<S;M+=1)_.push(n`${n.identifier(t[M])} IS ${p[M]}`);const C=t[S],F=d[S];if(C!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(M)} ${p[S]}`)}else _.push(n`${n.identifier(Jt)} < ${w}`);const[L]=_;A.push(_.length===1&&L!==void 0?L:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:g.c,total:N.c}},yr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const l=[];for(const h of r)h&&l.push(...Xt(a,h,ie));return l.length>0?l:void 0},{headroom:p}=o;let w=!1;const A=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,U)}),N=(e,r)=>{r!==void 0&&r!==U&&!w&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:F}=o,L=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),H=o.scheduler??Lt,{globalDb:W}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=H,k=on({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),j=(e,r,a,l)=>{v&&Bt(i,L(),e,r,a,l)},te=e=>t.tables[e]?.shardMode?.kind==="global",je=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}return q},Re=e=>je(e,"cascade"),z=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}},Ae=(e,r)=>je(e,"relation load").findMany(e,r),Ke=(e,r)=>(te(e)&&N(e,U),Ae(e,r)),_t=e=>!te(e.table),Ge=o.relationExistsPushDown??"auto",Qe=Ge!=="never",{maxRelationKeys:ze}=o,me=(e,r,a)=>at(e,{fetcher:Ke,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Ve=async(e,r,a,l)=>{const h=z(e,"relation grouped count");if(h)return N(e,U),tn((x,G)=>h.count(x,G),e,r,a,l);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(f.softDeleteMode,void 0),u={[r]:{in:a}},m=Q(Q(u,l),s),T=await me(m,e,void 0),$=ne(T,oe),R=Y(r);let O=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;$&&(O=n`${O} WHERE ${$}`),O=n`${O} GROUP BY ${R}`;const D=B(i,O).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let $e=0;const Ye=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ye.add(`${e} ${a.timing} ${a.op}`);const Z=(e,r,a)=>Ye.has(`${e} ${r} ${a}`),ee=async(e,r,a)=>{if($e+=1,$e>ut)throw $e-=1,new pe(`trigger recursion exceeded ${String(ut)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await an({ctx:At,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:xe,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Je,syncGeo:ge,syncRanks:he,syncSearch:be}=It({broadcast:d,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>F?.invalidate(e,r,c(e,a)),recordCdc:j,schema:t,sql:i}),Xe=(e,r,a)=>{const{shardMode:l}=r;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(a.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${l.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})},Ze=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=Ze(r);if(a.length===0)return;const l=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),h=n`${n.join(l,n` UNION ALL `)} LIMIT 1`,[f]=B(i,h).toArray();if(!f)return;const s=f.__t__,u=ce(f);if(typeof s!="string"||!u)return;const m=f[P];return{docJson:typeof m=="string"?m:se(m??{}),row:u,tableName:s}},Rt=(e,r)=>{const a=[...new Set(e)],l=new Map;if(a.length===0)return l;const h=Ze(r);if(h.length===0)return l;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const u=a.slice(s,s+f),m=n.join(u.map(R=>n`${R}`),n`, `),T=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${m})`),$=n.join(T,n` UNION ALL `);for(const R of B(i,$)){const{id:O,__t__:D}=R;typeof D=="string"&&typeof O=="string"&&l.set(O,D)}}return l},et={assertRankPartitionLocal:Xe,ensureRankBackfilled:Ie,onRead:N,rowToDocument:ce,schema:t,sql:i},q={system:k,async aggregate(e,r){const a=z(e,"aggregate");if(a)return N(e,U),a.aggregate(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(l.softDeleteMode,void 0),f=Q(Q(r.baseWhere,r.where),h),s=await me(f,e,r.relationBaseWhere),u=s!==f;if(l.aggregateIndexes&&!r.baseWhere&&!u&&!h){const D=Ot(l.aggregateIndexes,r.op,r.field,r.where);if(D){xe(e,D.index);const x=ve(D.index.by??[],D.key),G=ke(e,D.index.name),V=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(G)} WHERE ${Te} = ${x}`).toArray()[0];return Ce(r.op,V)}}We(l,r.field,`aggregate(${e}, { op: "${r.op}", field: "${r.field}" })`);const m=ne(s,oe),T=Ne(r.op),$=Y(r.field);let R=n`SELECT ${n.raw(T)}(${$}) AS value FROM ${n.identifier(e)}`;return m&&(R=n`${R} WHERE ${m}`),B(i,R).toArray()[0]?.value??null},asId(e,r){const a=ft(t,e,r);if(a===null)throw new b("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 N(e,U),a.count(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=Mt(r);if(h.restrictsCounts)throw new Me(e);N(e,U);const f=le(l.softDeleteMode,void 0),s=Q(Q(h.baseWhere,h.where),f),u=await me(s,e,h.relationBaseWhere),m=u!==s;if(l.aggregateIndexes&&!h.baseWhere&&!m&&!f){const R=Ft(l.aggregateIndexes,h.where);if(R){xe(e,R.index);const O=ve(R.index.by??[],R.key),D=ke(e,R.index.name),x=B(i,n`SELECT ${Se} AS value FROM ${n.identifier(D)} WHERE ${Te} = ${O}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(u,oe);let $=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&($=n`${$} WHERE ${T}`),B(i,$).one().count},async delete(e,r,a){const l=re(e,r);if(!l){const $=r===void 0?W:void 0;$&&await $.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s],m=a?.hard===!0,T=!m&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&f[T]!==null&&f[T]!==void 0)){if(Z(s,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:s}),await en({deletedId:e,deletedReference:$=>f[$],findHolders:async($,R,O)=>(await Re($).findMany($,{includeDeleted:m,where:{[R]:O}})).page,onCascade:($,R)=>Re($).delete(R,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,R,O)=>Re($).patch(R,{[O]:null}),schema:t,tableName:s}),ue(s),fe(s),T){const $={...f,[T]:L(),_id:e};_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se($)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,$,f),ge(s,e,void 0),we(s,f,$),he(s,e,f,void 0),F?.invalidate(s,e,c(s,f,$)),j(s,e,"update",$),d({indexKeys:c(s,f,$),key:e,op:"update",row:$,table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}_e(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,f,void 0),he(s,e,f,void 0),F?.invalidate(s,e,c(s,f)),j(s,e,"delete"),d({indexKeys:c(s,f),key:e,op:"delete",table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??Et),l=r?.hard===void 0?void 0:{hard:r.hard},h=te(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,h,l),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){de(e.length,r?.limit,"deleteMany");for(const l of e)await q.delete(l,a);return{deleted:e.length}},async deleteWhere(e,r,a){const l=(await(z(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(de(l.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(l,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Gt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return N(e,U),a.findMany(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,U):N(e);const f=Qt(r.orderBy),s=r.cursor?bt(f,Be(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,le(l.softDeleteMode,r.includeDeleted)),u=await at(u,{canPushExists:Qe?_t:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:Ke,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const m=Qe?Dn(N):oe,T=ne(u,m);let $=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&($=n`${$} WHERE ${T}`),$=n`${$} ORDER BY ${Tt(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&($=n`${$} LIMIT ${n.raw(String(R+1))}`);const O=B(i,$).toArray();h&&!w&&p?.recordRead(O.length);const D=[];for(const J of O){const K=ce(J);K&&(D.push(K),!h&&typeof K._id=="string"&&N(e,K._id))}if(R===void 0)return r.with&&await st({groupedCounter:Ve,fetcher:Ae,parents:D,...dt(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:rt(D,r.select,r.with)};const x=D.length>R,G=x?D.slice(0,R):D,V=G.at(-1);return r.with&&await st({fetcher:Ae,groupedCounter:Ve,parents:G,...dt(r),schema:t,tableName:e,with:r.with}),{continueCursor:x&&V?qe(V,f):null,isDone:!x,page:rt(G,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const l=r===void 0?W:void 0;return l?l.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return N(e,U),a.groupBy(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const h=r.agg??{op:"count"};if(Ne(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=le(l.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),f),u=await me(s,e,r.relationBaseWhere),m=u!==s;if(l.aggregateIndexes&&!r.baseWhere&&!m&&!f){const x=Dt(l.aggregateIndexes,h.op,h.field,r.by,r.where);if(x){xe(e,x.index);const G=ke(e,x.index.name),V=Object.keys(x.partial),J=[];if(V.length===(x.index.by??[]).length&&V.length>0){const ae=ve(x.index.by??[],x.partial),Ee=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(G)} WHERE ${Te} = ${ae}`).toArray();return Ee.length>0&&J.push({key:{...x.partial},value:Ce(h.op,Ee[0])}),J}const K=B(i,n`SELECT ${Te} AS key, ${Se} AS value, ${Le} AS count FROM ${n.identifier(G)}`).toArray();for(const ae of K){const Ee=kt(JSON.parse(ae.key));J.push({key:Ee,value:Ce(h.op,ae)})}return J}}for(const x of r.by)We(l,x,`groupBy(${e}, { by: [..."${x}"] })`);h.field!==void 0&&We(l,h.field,`groupBy(${e}, { agg: { op: "${h.op}", field: "${h.field}" } })`);const T=ne(u,oe),$=r.by.map(x=>n`${Y(x)} AS ${n.identifier(x)}`);if(h.op==="count")$.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);$.push(n`${n.raw(Ne(h.op))}(${Y(x)}) AS value`)}let R=n`SELECT ${n.join($,n`, `)} FROM ${n.identifier(e)}`;T&&(R=n`${R} WHERE ${T}`),R=n`${R} GROUP BY ${n.join(r.by.map(x=>Y(x)),n`, `)}`;const O=B(i,R).toArray(),D=[];for(const x of O){const G={};for(const J of r.by)G[J]=x[J]??null;const{value:V}=x;D.push({key:G,value:V==null?null:Number(V)})}return D},async insert(e,r,a){const l=z(e,"insert");if(l){const T=await l.insert(e,r,a);return w||p?.recordWrite(r),d({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=ht(h,r,E);Fe(h,f);let s;a?.clientId!==void 0?(Nn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=M();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:L(),m={...f,_creationTime:u,_id:s};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ue(e),fe(e),Ue(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${se(m)})`),Je(e,s,m),Z(e,"after","insert")&&await ee("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(de(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const l=z(e,"insert");if(l){const u=[];for(const m of r){const T=await l.insert(e,m,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite(m),d({key:T,op:"insert",row:{...m,_id:T},table:e}),u.push(T)}return u}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const f=r.map(u=>{const m=ht(h,u,E),T=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:M(),$=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:L();return{creationTime:$,document:{...m,_creationTime:$,_id:T},id:T}});if(!w)for(const u of f)p?.recordWrite(u.document);const s=n.join(f.map(u=>n`(${u.id}, ${u.creationTime}, ${se(u.document)})`),n`, `);Ue(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:m}of f)Je(e,m,u),await _({doc:u,id:m,op:"insert",table:e});return f.map(u=>u.id)},async insertMany(e,r,a){de(r.length,a?.limit,"insertMany");const l=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(l&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return ft(t,e,r)},async patch(e,r,a){const l=re(e,a);if(!l){const T=a===void 0?W:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),mt("patch",r);const m={...f,...r,_id:e};pt(u,r,m,E),Fe(u,m,!0),Z(s,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:f,table:s}),ue(s),fe(s),_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,m,f),ge(s,e,m),we(s,f,m),he(s,e,f,m),F?.invalidate(s,e,c(s,f,m)),j(s,e,"update",m),d({indexKeys:c(s,f,m),key:e,op:"update",row:m,table:s}),Z(s,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:f,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){de(e.length,r?.limit,"patchMany");for(const l of e)await q.patch(l.id,l.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const l=(await(z(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(de(l.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(l,a),{patched:l.length}},query(e){const r=z(e,"query");return r?(N(e,U),r.query(e)):jn(i,t,e,S,a=>{a?g(a):N(e,U)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const l=z(e,"rank");if(l)return N(e,U),l.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(K=>K.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Xe(e,h,f),a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=it(e,f.name),m=f.sortBy.map((K,ae)=>ot(ae)),T=m.map(K=>sn(K)).join(", "),$=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=$;if(R===void 0)return null;let O=R.__partition__;const D=Q(a.baseWhere,a.where);De(D,t,e,"rank");const x=Vt(f,D);if(x){const K=Yt(f.partitionBy??[],x);if(K!==O)return null;O=K}const G=m.map(K=>R[K]),{before:V,total:J}=$t(i,u,m,f.sortBy,O,G,s);return{position:V+1,total:J}},async rankBefore(e,r,a){if(te(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=l.rankIndexes?.find(m=>m.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,h);const f=it(e,h.name),s=h.sortBy.map((m,T)=>ot(T)),u=h.sortBy.map((m,T)=>ie(a.sortValues[T]??null));return $t(i,f,s,h.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){De(Q(a.baseWhere,a.where),t,e,"rankPage");const l=z(e,"rankPage");if(l)return N(e,U),l.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=tt(et,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){De(Q(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:l,hasMore:h,rows:f}=tt(et,e,r,a);return{directions:l,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?W:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const l=t.tables[a.tableName]?.softDeleteMode?.field;if(!l)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[l]!==null&&a.row[l]!==void 0;await q.patch(e,{[l]:null},r),h&&he(a.tableName,e,void 0,a.row)},async replace(e,r,a,l){const h=re(e,a);if(!h){const R=a===void 0?W:void 0;if(R){await R.replace(e,r,void 0,l);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:u}=h,m=t.tables[u];if(!m)throw new b("INTERNAL",`unknown table: ${u}`);mt("replace",r);const T=l?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),$={...r,_creationTime:T,_id:e};pt(m,r,$,E),Fe(m,$),Z(u,"before","update")&&await ee("before","update",{doc:{...$},id:e,op:"update",previous:s,table:u}),ue(u),fe(u),_e(i,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${T}, ${n.identifier(P)} = ${se($)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),be(u,e,$,s),ge(u,e,$),we(u,s,$),he(u,e,s,$),F?.invalidate(u,e,c(u,s,$)),j(u,e,"update",$),d({indexKeys:c(u,s,$),key:e,op:"update",row:$,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:$,id:e,op:"update",previous:s,table:u}),await C({doc:$,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,l=Object.entries(t.tables).filter(([u,m])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:m.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of l){const m=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=m.deleted,f+=m.deleted}return{deleted:f,tables:h}}},At={db:q,scheduler:H};return o.enforceRls===!0?nn(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>Rt(e,r)):q};export{xr as CDC_LOG_TABLE,Or as CLIENT_WATERMARK_TABLE,Pr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Vr as IDEMPOTENCY_TABLE,Un as NotUniqueError,no as SEARCH_STATE_TABLE,Wr as advanceClientWatermark,Ir as applyCdcChanges,Nn as assertValidClientId,Tr as backfillAggregateIndexes,_r as backfillRankIndexes,Rr as backfillSearchIndexes,vr as bumpCdcEpoch,yr as createShardCtxDb,Hr as deleteGlobalShapeSnapshot,jr as deleteGlobalShapeSnapshotsForConnection,Br as migrateClientWatermark,Kr as migrateGlobalShapeSnapshot,Cr as minCdcSeq,ft as normalizeIdStructurally,kr as readCdcChanges,Mr as readCdcCursor,Lr as readCdcEpoch,qr as readClientWatermark,Gr as readGlobalShapeSnapshot,Yr as readIdempotent,eo as runShardMigrations,oo as selectShapeMemberIds,io as selectShapeRows,Dr as trimCdcChanges,Jr as trimIdempotent,Qr as writeGlobalShapeSnapshot,Xr as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-
|
|
1
|
+
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-DV-K7ft2.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-BR4UOWoP.mjs";const n=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:n}return r},u=(r,t)=>{if(r.length===0)return"";const o={};for(const s of r.toSorted(c))o[s]=t[s]??null;return JSON.stringify(o)},h="__id__",k=r=>`__sort_k${String(r)}__`,S=(r,t)=>{const o=r.partitionBy??[],s=t??{};for(const e of Object.keys(s))if(e==="AND"||e==="OR"||e==="NOT")return;const i={};for(const e of o)if(e in s){const a=m(s[e]);if(a===n)return;i[e]=a}else if(r.where&&e in r.where)i[e]=r.where[e];else return;return i},d=(r,t)=>`${r}__rank_${t}`,b=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),g=l;export{h as RANK_TIEBREAK,u as encodePartitionKey,g as matchesRankStaticWhere,b as rankKeyFromDoc,d as rankTableName,S as resolveRankPartition,k as sortColumnName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="__lunora_reproject__",o=r=>`${t}${r}`,i=r=>{if(!r.startsWith(t))return;const e=r.slice(t.length);return e===""?void 0:e};export{t as REPROJECTION_MIGRATION_PREFIX,o as reprojectionMigrationId,i as reprojectionMigrationTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableWireKey as p}from"./stableWireKey-
|
|
1
|
+
import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";import{depKey as l,SCAN_DEP as f}from"./SCAN_DEP-D_yR9EeV.mjs";import{o as m}from"./estimate-bytes-Drp8rhPs.mjs";import{keysTouchRanges as u}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const c=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},x=1e3,g=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??x,this.maxBytes=t.maxBytes??g,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){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 r=await s(),h=m(r);if(h===void 0)return r;const d=i(),b={bytes:h,deps:e,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of e)c(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const y=c(this.rangeIndex,a.table,()=>new Map);c(y,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,e,s){const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,f),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}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 e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)u([n],e)&&this.dropKeys(r,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),n=i?.get(s);n?.delete(t),i&&n?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const E=(o,t,e)=>`${e??"\0anon"}\0${o}:${p(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,p as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-Dsy70M3Q.mjs";const n=BigInt(Number.MAX_SAFE_INTEGER),i=(e,t)=>e<t?-1:e>t?1:0,d=(e,t)=>`${e}__agg_${t}`,c=e=>{if(typeof e=="bigint"){if(e>n||e<-n)throw new l("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER and cannot be aggregated exactly — aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},f=(e,t,o,a)=>{const r=e.get(t)??{count:0,value:null};if(o.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const u=c(a[o.field??""]);if(o.op==="sum"||o.op==="avg"){u!==void 0&&(r.value=(r.value??0)+u,r.count+=1),e.set(t,r);return}r.count+=1,u!==void 0&&(r.value===null?r.value=u:r.value=o.op==="min"?Math.min(r.value,u):Math.max(r.value,u)),e.set(t,r)},s=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,b=(e,t)=>{if(e.length===0)return"";const o={};for(const a of e.toSorted(i))o[a]=t[a]??null;return JSON.stringify(g(o))};export{d as aggregateTableName,c as coerceAggregateNumber,i as compareStrings,b as encodeAggregateKey,f as foldAggregateTally,s as readAggregateValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{applySelect as
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{applySelect as v}from"./applySelect-i17LYhIU.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?v(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},B=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new D("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new D("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=B(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=B(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],R=w.get(h);R?R.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},_=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=B(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await _(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},A=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new D("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await A(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,B as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-Dsy70M3Q.mjs";const g="id",y=new Set(["_id","id"]),E=t=>{const e=[];for(const o of t??[])for(const[r,s]of Object.entries(o))e.push({direction:s,field:r});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},w=t=>{const e=new TextEncoder().encode(t);let o="";for(const r of e)o+=String.fromCodePoint(r);return btoa(o)},b=t=>{const e=atob(t),o=Uint8Array.from(e,r=>r.codePointAt(0)??0);return new TextDecoder().decode(o)},T=(t,e)=>{const o=e.map(r=>t[r.field]);return o.push(t._id),w(JSON.stringify(S(o)))},a=()=>new h("BAD_REQUEST","invalid cursor"),k=t=>{let e;try{e=m(JSON.parse(b(t)))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(t,e,o)=>{const r=t.some(n=>y.has(n.field))?t:[...t,{direction:"asc",field:g}],s=[];for(const[n,i]of r.entries()){const c=[];for(const[u,p]of r.slice(0,n).entries())c.push({[p.field]:{eq:e[u]}});const l=o(i.direction,n===r.length-1);c.push({[i.field]:{[l]:e[n]}});const[d]=c;s.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:s}},v=(t,e)=>f(t,e,o=>o==="desc"?"lt":"gt"),A=(t,e)=>t==="desc"?e?"gte":"gt":e?"lte":"lt",B=(t,e)=>f(t,e,A),O=["_id","_creationTime"],C=(t,e,o)=>{if(!e)return t;const r=new Set([...e,...O,...o?Object.keys(o):[]]);return t.map(s=>{const n={};for(const i of r)i in s&&(n[i]=s[i]);return n})},N=(t,e)=>t&&e!==!0?{[t.field]:{isNull:!0}}:void 0;export{C as applySelect,B as buildSeekBeforeWhere,v as buildSeekWhere,k as decodeCursor,T as encodeCursor,b as fromBase64,a as invalidCursor,E as normalizeOrderKeys,N as softDeleteScope,w as toBase64};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as l}from"./wire-codec-
|
|
1
|
+
import{a as l}from"./wire-codec-Dsy70M3Q.mjs";const c="_id",p="__lunora__",b=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const r=e[c];return typeof r=="string"?r:void 0},y=e=>{const r=new Map,o=[];for(const s of e){const t=b(s);if(t===void 0||r.has(t))return;r.set(t,s),o.push(t)}return{byId:r,order:o}},g=(e,r)=>{const o=e.order.filter(t=>r.byId.has(t)),s=r.order.filter(t=>e.byId.has(t));return o.length!==s.length?!1:o.every((t,n)=>s[n]===t)},h=(e,r,o,s)=>{const t=[];for(const n of e.order)r.byId.has(n)||t.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return t},m=(e,r,o,s)=>{const t=[];for(const n of r.order){const a=r.byId.get(n),i=e.byId.get(n),f=JSON.stringify(l(a)),d=i===void 0?void 0:JSON.stringify(i);if(d===f)continue;const u=d===void 0?"insert":"update";t.push({delta:{key:n,op:u,row:a,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return t},S=(e,r,o,s)=>{let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||!Array.isArray(r))return;const n=y(t),a=y(r);if(n===void 0||a===void 0||!g(n,a))return;const i=o===""?p:o,f=JSON.stringify(i),d=[...h(n,a,i,f),...m(n,a,i,f)];if(!(d.length>a.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(e,r)=>{try{return e.send(r),!0}catch{return!1}},I=(e,r,o,s,t)=>{const n=JSON.stringify(r),a=t===void 0?"":`,"lastMutationId":${String(t)}`;let i=!0;for(const f of o)$(e,`{"type":"delta","id":${n},"delta":${f}${a}${s}}`)||(i=!1);return i},w=async e=>{let r=0;for(;r<100;){r+=1;const{bufferedAmount:o}=e;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O as R,q as x,x as O,T as S,l as k,y as M,c as w}from"./ctx-db-companions-CAJOSdN-.mjs";import"@lunora/errors";import{sql as i}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as y}from"./aggregateTableName-DV-K7ft2.mjs";import{migrateSearchState as F,readSearchBackfillState as N,writeSearchBackfillState as D}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as d}from"./runDrizzle-B6rnz3so.mjs";import{C as T,E as u,c as j,p as q,T as v,a as m,D as B}from"./do-sql-1Yi1_Yq0.mjs";import{matchesRankStaticWhere as W,rankTableName as _}from"./RANK_TIEBREAK-DYDRmLKH.mjs";const H=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},I=(e,n)=>d(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(n)}`).one().count>0,b=(e,n)=>d(e,i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)}`).toArray(),U=(e,n,o)=>{const r=y(n,o.name);if(I(e,r))return;const t=o.by??[],a=new Map,c=b(e,n);for(const s of c){const f=u(s);if(!f||o.where&&!A(f,o.where))continue;const l=L(t,f);C(a,l,o,f)}for(const[s,f]of a)d(e,i`INSERT INTO ${i.identifier(r)} (${j}, ${q}, ${v}) VALUES (${s}, ${f.value}, ${f.count})`)},ee=(e,n)=>{for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const t of r.aggregateIndexes)U(e,o,t)},V=(e,n,o)=>{const r=_(n,o.name);if(I(e,r))return;const t=R(o),a=b(e,n);for(const c of a){const s=u(c);!s||o.where&&!W(s,o.where)||x(e,r,o,t,s._id,s)}},re=(e,n)=>{for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const t of r.rankIndexes)V(e,o,t)},g=500,p=(e,n,o)=>{const r=w(n,o.name),{profile:t}=O(o.language),a=H(N(e,r),t);if(a.finished)return!0;a.wipe&&d(e,i`DELETE FROM ${i.identifier(r)}`);const{cursor:c}=a,s=d(e,c===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)} ORDER BY id ASC LIMIT ${i.raw(String(g))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)} WHERE id > ${c} ORDER BY id ASC LIMIT ${i.raw(String(g))}`).toArray();let f=c;for(const E of s){const{id:$}=E;if(typeof $!="string")continue;f=$,d(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(S)} = ${$}`);const h=B(E);h&&d(e,i`INSERT INTO ${i.identifier(r)} (${i.identifier(k)}, ${i.identifier(S)}) VALUES (${M(h,o)}, ${$})`)}const l=s.length<g;return D(e,r,f,l,t),l},ie=(e,n,o)=>{if(T(e))for(const r of o.searchIndexes??[])r.staged||p(e,n,r)},ne=(e,n)=>{if(T(e)){F(e);for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.searchIndexes))for(const t of r.searchIndexes){let a=!1;for(;!a;)a=p(e,o,t)}}};export{ee as backfillAggregateIndexes,re as backfillRankIndexes,ne as backfillSearchIndexes,ie as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=n=>{let r="";for(let t=0;t<n.length;t+=32768)r+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(r)},a=n=>{const r=atob(n),t=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)t[o]=r.codePointAt(o)??0;return t};export{e as a,a as o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./wire-codec-
|
|
1
|
+
import{a as u}from"./wire-codec-Dsy70M3Q.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{L as u,a as l,j as m}from"./do-sql-1Yi1_Yq0.mjs";import{quoteIdentifier as a}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as j}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as _,reprojectionMigrationId as x}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as b}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as f}from"./runDrizzle-B6rnz3so.mjs";import{y as d}from"./sql-projection-jfoe331H.mjs";const E=b(0n)[0],$=r=>r.shardMode?.kind==="global"?[]:Object.entries(r.shape).filter(([,t])=>d(t)).map(([t])=>t),L=r=>Object.entries(r.tables).filter(([,t])=>$(t).length>0).map(([t])=>t),g=r=>{const t=r.map(()=>`(json_extract(${a(l)}, ?) = ? AND json_extract(${a(l)}, ?) IN (?, ?))`);return{params:r.flatMap(o=>[`$.${m(o)}[0]`,E,`$.${m(o)}[1]`,"bigint","bytes"]),sql:t.join(" OR ")}},S=(r,t,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=g(o);return f(r,`SELECT COUNT(*) AS count FROM ${a(t)} WHERE ${n}`,...e).toArray()[0]?.count??0},R=(r,t,o,e)=>{const{params:n,sql:i}=g(o);return f(r,`SELECT 1 FROM ${a(t)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},A=(r,t,o)=>{const e=j(r);if(e===void 0)return;const n=t.tables[e];if(!n)return;const i=$(n);if(i.length!==0)return{id:r,table:e,up:s=>{const c=s._id;if(!(typeof c!="string"||!R(o,e,i,c))){try{u(s)}catch(p){console.warn(`${r}: skipping row ${c} — it cannot be re-projected: ${p instanceof Error?p.message:String(p)}`);return}return s}}}};export{_ as REPROJECTION_MIGRATION_PREFIX,A as buildReprojectionMigration,S as countLegacyRows,$ as reprojectableFields,x as reprojectionMigrationId,L as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as x}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{param as q}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as x}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{param as q}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-i17LYhIU.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-DYDRmLKH.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,c)=>{if(n?.length!==1+o.length+1)return;const i=[{column:"__partition__",direction:"asc"}];for(const[a,f]of o.entries())i.push({column:f,direction:c[a]?.direction??"asc"});i.push({column:m,direction:"asc"});const s=[];for(const[a,f]of i.entries()){const e=[];for(const[r,$]of i.slice(0,a).entries())e.push(t`${t.identifier($.column)} IS ${n[r]}`);e.push(t`${t.identifier(f.column)} ${t.raw(f.direction==="desc"?"<":">")} ${n[a]}`);const[d]=e;s.push(e.length===1&&d!==void 0?d:t`(${t.join(e,t` AND `)})`)}return t`(${t.join(s,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const c=[n.__partition__,...o.map(i=>n[i]),n[m]];return G(c)},U=(n,o,c)=>{const i=[];for(const s of n){const a=s[m];if(typeof a!="string")continue;const f=o.get(a);if(!f)continue;const e=typeof s.__partition__=="string"?s.__partition__:"",d=c.map(r=>s[r]??null);i.push({doc:f,key:{partitionKey:e,rowId:a,sortValues:d}})}return i},tt=(n,o,c)=>{const{rowToDocument:i}=n,s=new Map;if(c.length===0)return s;const a=t.join(c.map(e=>q(e)),t`, `),f=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE id IN (${a})`).toArray();for(const e of f){const d=i(e),r=e.id;d&&typeof r=="string"&&s.set(r,d)}return s},ft=(n,o,c,i)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:a,onRead:f,schema:e}=n,d=e.tables[o];if(!d)throw new A("INTERNAL",`unknown table: ${o}`);const r=d.rankIndexes?.find(p=>p.name===c);if(!r)throw new A("INTERNAL",`unknown rankIndex "${c}" on table "${o}"`);s(o,d,r),f(o,O),a(o,r);const $=V(o,r.name),u=r.sortBy.map((p,w)=>F(w)),l=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),S=x(i.baseWhere,i.where),R=H(r,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[p,w]of u.entries()){const v=r.sortBy[p]?.direction;h.push(t`${t.identifier(w)} ${t.raw(v==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof i.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${i.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(r.partitionBy??[],R)}`);const T=X(i),k=Z(T,u,r.sortBy);k&&_.push(k);const I=t.identifier(m),N=t.identifier("__partition__"),M=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,D=u.length>0?t`${I}, ${N}, ${t.join(u.map(p=>t.identifier(p)),t`, `)}`:t`${I}, ${N}`,K=t`SELECT ${D} FROM ${t.identifier($)}${M} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String(l+1))}`,y=B(n.sql,K).toArray(),g=y.length>l,E=g?y.slice(0,l):y,L=E.map(p=>p[m]),b=U(E,tt(n,o,L),u),j=g?Q(E.at(-1),u):C,P=r.sortBy.map(p=>p.direction==="desc"?"desc":"asc");return{continueCursor:j,directions:P,hasMore:g,rows:b}};export{ft as computeRankPage,tt as hydrateDocsById};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as l,q,O as C}from"./ctx-db-companions-CAJOSdN-.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DV-K7ft2.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./do-sql-1Yi1_Yq0.mjs";import"./param-B5lF5Jd9.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./RANK_TIEBREAK-DYDRmLKH.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{l as createCompanionSync,q as insertRankRow,C as rankColumnsSql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as j,aggregateSqlFunction as ie}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as oe,coerceAggregateNumber as I,aggregateTableName as W}from"./aggregateTableName-DV-K7ft2.mjs";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{C as re,a as B,E as H,c as O,p as v,T as _,h as ae,A as x,N as F}from"./do-sql-1Yi1_Yq0.mjs";import{param as se}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as le,GEO_DEFAULT_PRECISION as de}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{encodePartitionKey as ce,sortColumnName as ue,matchesRankStaticWhere as V,rankTableName as K}from"./RANK_TIEBREAK-DYDRmLKH.mjs";import{serializeSqlValue as G}from"./serializeSqlValue-BR4UOWoP.mjs";const fe=["de","en","es","fr","it","nl","none","pt"],$e=t=>fe.includes(t),me="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",he="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Ee="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",pe="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",ge="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",ye="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",_e="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,J=t=>t.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase(),L=t=>new Set(J(t).split(" ")),ve={de:L(he),en:L(me),es:L(Ee),fr:L(pe),it:L(ge),nl:L(ye),none:new Set,pt:L(_e)},Se=2,Te=256,U=new Map,we=t=>{const o=t!==void 0&&$e(t)?t:"none",l=U.get(o);if(l)return l;const p=ve[o],S=r=>{const T=(J(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(w=>w.length<=Te);return p.size===0?T:T.filter(w=>!p.has(w))},m={document:S,profile:`${o}-v${String(Se)}`,query:r=>{const T=S(r);return T.filter((w,A)=>T.lastIndexOf(w)===A)}};return U.set(o,m),m},Ae=(t,o)=>{if(!o.includes("."))return t[o];let l=t;for(const p of o.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[p]}return l},Re=(t,o)=>`${t}__fts_${o}`,Ne="__text__",P="__id__",Le=1e3,Oe=(t,o)=>o.document(t),k=(t,o)=>Ae(t,o),xe=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",je=(t,o,l)=>t!==void 0&&o!==void 0&&k(t,l.field)===k(o,l.field),Ie=(t,o)=>Oe(xe(k(t,o.field)),we(o.language)).slice(0,Le).join(" "),Fe=(t,o,l)=>[...t.partitionBy??[],...t.sortBy.map(p=>p.field),...t.where?Object.keys(t.where):[]].every(p=>o[p]===l[p]),X=t=>e.join(["__id__","__partition__",...t.sortBy.map((o,l)=>ue(l))].map(o=>e.identifier(o)),e`, `),Q=(t,o,l,p,S,m)=>{const r=ce(l.partitionBy??[],m),T=l.sortBy.map(A=>G(m[A.field]??null)),w=e.join([S,r,...T].map(A=>se(A)),e`, `);$(t,e`INSERT INTO ${e.identifier(o)} (${p}) VALUES (${w})`)},ke=(t,o,l,p,S,m)=>{if(S&&m&&Fe(l,S,m))return;const r=K(o,l.name);S&&$(t,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${p}`),!(!m||l.where&&!V(m,l.where))&&Q(t,r,l,X(l),p,m)},Ve=t=>{const{broadcast:o,indexKeysFor:l,invalidateCache:p,recordCdc:S,schema:m,sql:r}=t,T=new Set,w=new Set,A=(i,n)=>{const s=`${i}::${n.name}`;if(T.has(s))return;const u=W(i,n.name),d=n.by??[],f=new Map,h=$(r,e`SELECT id, _creationTime, ${e.identifier(B)} FROM ${e.identifier(i)}`).toArray();for(const b of h){const a=H(b);if(!a||n.where&&!j(a,n.where))continue;const c=N(d,a);oe(f,c,n,a)}$(r,e`DELETE FROM ${e.identifier(u)}`);const g=32,E=[...f];for(let b=0;b<E.length;b+=g){const a=E.slice(b,b+g),c=e.join(a.map(([y,R])=>e`(${y}, ${R.value}, ${R.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(u)} (${O}, ${v}, ${_}) VALUES ${c}`)}T.add(s)},Y=(i,n,s)=>{const u=n.by??[],d=ie(n.op),f=n.field??"",h=[],g=(a,c)=>{const y=G(c);y===null?h.push(e`${F(a)} IS NULL`):h.push(e`${F(a)} = ${y}`)};for(const a of u)g(a,s[a]??null);for(const[a,c]of Object.entries(n.where??{}))g(a,c!==null&&typeof c=="object"&&!Array.isArray(c)?c.eq:c);const E=h.length>0?e` WHERE ${e.join(h,e` AND `)}`:e``,b=F(f);return{value:$(r,e`SELECT ${e.raw(d)}(${b}) AS value FROM ${e.identifier(i)}${E}`).one().value??null}},Z=(i,n,s,u)=>{const d=W(i,n.name),{op:f}=n,h=n.field??"",g=a=>{$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${O} = ${a} AND ${_} <= 0`)},E=s&&(!n.where||j(s,n.where))?s:void 0,b=u&&(!n.where||j(u,n.where))?u:void 0;if(!(!E&&!b)){if(f==="count"){for(const[a,c]of[[E,-1],[b,1]]){if(!a)continue;const y=N(n.by??[],a);$(r,x(d,y,c,c,e`${v} = ${v} + excluded.${v}, ${_} = ${_} + excluded.${_}`))}E&&g(N(n.by??[],E));return}if(f==="sum"||f==="avg"){for(const[a,c]of[[E,-1],[b,1]]){if(!a)continue;const y=I(a[h]);if(y===void 0)continue;const R=N(n.by??[],a);$(r,x(d,R,c*y,c,e`${v} = COALESCE(${v}, 0) + excluded.${v}, ${_} = ${_} + excluded.${_}`))}E&&g(N(n.by??[],E));return}if(E){const a=N(n.by??[],E),c=I(E[h]),y=$(r,e`SELECT ${v} AS value, ${_} AS count FROM ${e.identifier(d)} WHERE ${O} = ${a}`).toArray()[0],R=(y?.count??0)-1;if(R<=0)$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${O} = ${a}`);else if(y&&c!==void 0&&y.value!==null&&c===y.value){const te=Y(i,n,E);$(r,e`UPDATE ${e.identifier(d)} SET ${v} = ${te.value}, ${_} = ${R} WHERE ${O} = ${a}`)}else $(r,e`UPDATE ${e.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${a}`)}if(b){const a=N(n.by??[],b),c=I(b[h]);if(c===void 0)$(r,x(d,a,null,1,e`${_} = ${_} + 1`));else{const y=f==="min"?"MIN":"MAX";$(r,x(d,a,c,1,e`${v} = ${e.raw(y)}(COALESCE(${v}, excluded.${v}), excluded.${v}), ${_} = ${_} + 1`))}}}},ee=i=>{for(const n of m.tables[i]?.aggregateIndexes??[])A(i,n)},q=(i,n,s)=>{for(const u of m.tables[i]?.aggregateIndexes??[])Z(i,u,n,s)},C=(i,n)=>{const s=`${i}::rank::${n.name}`;if(w.has(s))return;const u=K(i,n.name),d=$(r,e`SELECT id, _creationTime, ${e.identifier(B)} FROM ${e.identifier(i)}`).toArray();$(r,e`DELETE FROM ${e.identifier(u)}`);const f=X(n);for(const h of d){const g=H(h);!g||n.where&&!V(g,n.where)||Q(r,u,n,f,g._id,g)}w.add(s)},ne=i=>{for(const n of m.tables[i]?.rankIndexes??[])C(i,n)},M=(i,n,s,u)=>{for(const d of m.tables[i]?.rankIndexes??[])ke(r,i,d,n,s,u)},z=(i,n,s,u)=>{const d=m.tables[i]?.searchIndexes??[];if(!(d.length===0||!re(r)))for(const f of d){if(je(u,s,f))continue;const h=Re(i,f.name);$(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(P)} = ${n}`),s&&$(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ne)}, ${e.identifier(P)}) VALUES (${Ie(s,f)}, ${n})`)}},D=(i,n,s)=>{for(const u of m.tables[i]?.geoIndexes??[]){const d=ae(i,u.name);$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[u.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:g}=f,E=le({lat:h,lng:g},u.precision??de);$(r,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${E}, ${h}, ${g})`)}}};return{ensureBackfilledForTable:ee,ensureBackfilledIndex:A,ensureRankBackfilled:C,ensureRankBackfilledForTable:ne,syncAggregates:q,syncCompanionsForInsert:(i,n,s)=>{z(i,n,s),D(i,n,s),q(i,void 0,s),M(i,n,void 0,s),p(i,n,s),S(i,n,"insert",s),o({indexKeys:l(i,s),key:n,op:"insert",row:s,table:i})},syncGeo:D,syncRanks:M,syncSearch:z}};export{X as O,P as T,Re as c,Ve as k,Ne as l,Oe as n,Q as q,we as x,Ie as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-BItFDsAw.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CPBmX1FO.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-n2dKcH5E.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-B6rnz3so.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as c}from"./sql-projection-jfoe331H.mjs";const i=40,s=o=>{let r=0;const f=(e,t)=>typeof t=="bigint"?(r+=c+1+i,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r+=2*Math.ceil(t.byteLength/3)*4+i,""):t;try{const e=JSON.stringify(o,f);return(e===void 0?0:e.length)+r}catch{return}};export{s as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B6rnz3so.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B6rnz3so.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-DcCENzpV.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-BdBcbrUP.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{l as I,T as N,c as S}from"./ctx-db-companions-CAJOSdN-.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DV-K7ft2.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-tK0jrl43.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{a as u,N as E,y as _,I as X,C as b,c as x,p as B,T as c,h as Y}from"./do-sql-1Yi1_Yq0.mjs";import{sortColumnName as F,rankTableName as M}from"./RANK_TIEBREAK-DYDRmLKH.mjs";import{recordSchemaVersion as D}from"./SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";const k=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},y=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},j=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=Y(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},q=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=M(t,i.name),s=i.sortBy.map((T,d)=>F(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},ne=(r,t,o={})=>{o.schemaSnapshot!==void 0&&D(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(u)} TEXT NOT NULL
|
|
5
|
+
)`),k(r,i,n),y(r,i,n),j(r,i,n),G(r,i,n),q(r,i,n));o.cdc&&(h(r),l(r),R(r)),O(r),C(r)};export{ne as runShardMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{N as r}from"./do-sql-1Yi1_Yq0.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B6rnz3so.mjs";import{a as c,E as a,N as u}from"./do-sql-1Yi1_Yq0.mjs";import{compileWhereSql as h}from"./compileWhereSql-B4rPariq.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},m=(i,r)=>{const o=[];r&&o.push(r);const t=h(i,$);return t&&o.push(t),o.length===0?e``:e` WHERE ${e.join(o,e` AND `)}`},y=(i,r,o)=>{const t=m(o,void 0),d=l(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(r)}${t}`).toArray(),n=[];for(const s of d){const f=a(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},A=(i,r,o,t)=>{if(t.length===0)return new Set;const d=m(o,E(t)),n=l(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{A as selectShapeMemberIds,y as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as o}from"./sql-projection-jfoe331H.mjs";const t=e=>typeof e=="boolean"?e?1:0:e===null||typeof e=="string"||typeof e=="number"?e:o(e)??JSON.stringify(e);export{t as serializeSqlValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{a}from"./base64-fKomMf5D.mjs";const n=t=>{if(t.kind!=="optional")return t.kind;const r=t._meta?.inner;return r?n(r):t.kind},e=39,s="0",u="1",y=t=>{const r=t<0n,i=(r?-t:t).toString();if(i.length>e)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(i.length)} digits, over the ${String(e)}-digit limit for a queryable column`);const o=i.padStart(e,"0");return r?s+Array.from(o,f=>String(9-Number(f))).join(""):u+o},d=t=>typeof t=="bigint"?y(t):t instanceof ArrayBuffer?a(new Uint8Array(t)):ArrayBuffer.isView(t)?a(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,m=t=>{const r=n(t);return r==="bigint"||r==="bytes"},S=t=>{const r=n(t);return m(t)||r==="any"||r==="union"||r==="from"};export{d as b,m as f,e as r,S as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-Dsy70M3Q.mjs";const i=t=>r(e(t));export{i as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p,o as A}from"./base64-fKomMf5D.mjs";const i="$lunora.wire$",b=64,g=1024,d="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},m={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},v=r=>{if(r===null||typeof r!="object")return!1;const a=Object.getPrototypeOf(r);return a===null||a===Object.prototype},c=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const s=typeof r;if(s==="bigint")return[i,"bigint",r.toString()];if(s==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(s!=="object")return r;if(r instanceof Date)return[i,"date",c(r.getTime(),a+1)];if(r instanceof Error){const e=r,n={};for(const f of Object.keys(e))e[f]!==void 0&&(n[f]=c(e[f],a+1));const o=[i,"error",e.name,e.message,n];return e.cause!==void 0&&o.push(c(e.cause,a+1)),o}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,n])=>[c(e,a+1),c(n,a+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>c(e,a+1))];if(r instanceof ArrayBuffer)return[i,"bytes",p(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[i,"bytes",p(o)]:[i,"bytes",p(o),n]}if(Array.isArray(r)){const e=r.map(n=>c(n,a+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!v(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const l=r,t={};for(const e of Object.keys(l)){const n=l[e];if(n===void 0)continue;const o=c(n,a+1);e===d?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:o,writable:!0}):t[e]=o}return t},u=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>u(t,a+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>g||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(t)}case"date":return new Date(u(r[2],a+1));case"map":return new Map(r[2].map(([t,e])=>[u(t,a+1),u(e,a+1)]));case"set":return new Set(r[2].map(t=>u(t,a+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],n=(Object.hasOwn(m,t)?m[t]:void 0)??Error,o=new n(e);o.name!==t&&Object.defineProperty(o,"name",{configurable:!0,value:t,writable:!0});const f=u(r[4],a+1);for(const y of Object.keys(f))y===d?Object.defineProperty(o,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):o[y]=f[y];return r.length>5&&Object.defineProperty(o,"cause",{configurable:!0,value:u(r[5],a+1),writable:!0}),o}case"bytes":{const t=A(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(w,e)?w[e]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>u(t,a+1))}return r.map(t=>u(t,a+1))}const s=r,l={};for(const t of Object.keys(s)){const e=u(s[t],a+1);t===d?Object.defineProperty(l,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):l[t]=e}return l};export{c as a,u as s};
|
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.17",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";const Y="__lunora_admin__:",z="__lunora_relation__:",V="__lunora_flags__:",J={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"},F=50,f=500,L=30,P=200,m="__doc__",k=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},D=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const s=[];for(const r of a){const _=r[m],i=typeof _=="string"?k(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(r).filter(([l])=>l!==m));s.push({...u,...i})}const t=e.filter(r=>r!==m),n=[],o=new Set(t);for(const r of s)for(const _ of Object.keys(r))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:s}},R=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,s)=>Math.min(Math.max(e,a),s),y=(e,a)=>{const s=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(s.c)},Z=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),s=[];for(const{name:t}of a)E(t)||s.push({name:t,rowCount:y(e,d(t))});return s},w=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,A=(e,a)=>{if(E(a)||!w(e,a))throw new T("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},b=(e,a)=>e.exec(`PRAGMA table_info(${a})`).toArray().map(s=>s.name),U={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},W=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,a)=>{const s=a.includes(e),t=a.includes(m);if(!(!s&&!t))return s?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},q=(e,a)=>{const s=M(e.column,a);if(s===void 0)return;const{expression:t,params:n}=s;return e.operator==="contains"?{params:[...n,`%${R(W(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${U[e.operator]} ?`}},Q=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,j=e=>{const a=Q.exec(e.trim());if(a===null)return;const s=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)||s<100)return;const o=Date.UTC(s,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let r;return n!==void 0?r=Date.UTC(s,(t??1)-1,n+1):t===void 0?r=Date.UTC(s+1,0,1):r=Date.UTC(s,t,1),{from:o,to:r}},C=(e,a,s)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${R(a)}%`,r=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=j(a);if(_!==void 0)for(const i of e)r.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${r.join(" OR ")})`)}for(const o of s??[]){const r=q(o,e);r!==void 0&&(t.push(`(${r.sql})`),n.push(...r.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},B=(e,a)=>{if(e===void 0)return;const s=M(e.column,a);if(s===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:s.params,sql:`${s.expression} ${t}`}},ee=(e,a)=>{const{table:s}=a;A(e,s);const t=I(Math.trunc(a.limit??F),1,f),n=Math.max(0,Math.trunc(a.offset??0)),o=d(s),r=b(e,o),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const S={};for(const $ of h.columns){const O=a.refs[$];O!==void 0&&(S[$]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},u=C(r,_,a.filters),l=B(a.orderBy,r),c=u===void 0?"":` WHERE ${u.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],x=l?.params??[];let v;a.skipCount||(v=u===void 0?y(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const N=e.exec(`SELECT * FROM ${o}${c}${p} LIMIT ? OFFSET ?`,...g,...x,t,n).toArray();return i({...D(r,N),total:v})},ae=(e,a)=>{const{table:s}=a;A(e,s);const t=I(Math.trunc(a.limit??f),1,f),n=d(s),o=b(e,n),r=a.search?.trim()??"",_=C(o,r,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=i.slice(0,t).map(c=>c.id);return{hasMore:u,ids:l}},H=(e,a,s)=>{const t=new Set(s.filter(o=>o!==m));if(!s.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,f).toArray();for(const{doc:o}of n){const r=typeof o=="string"?k(o):void 0;if(r!==void 0)for(const _ of Object.keys(r))t.add(_)}return t},te=(e,a)=>{const{column:s,table:t}=a;A(e,t);const n=d(t),o=b(e,n);if(!H(e,n,o).has(s))throw new T("UNKNOWN_COLUMN",`unknown column: ${s}`,{status:404});const r=M(s,o);if(r===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${s}`,{status:404});const _=I(Math.trunc(a.limit??L),1,P),i=a.search?.trim()??"",u=C(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],p=e.exec(`SELECT ${r.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${r.expression} ORDER BY count DESC LIMIT ?`,...r.params,...c,...r.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},re=(e,a,s)=>{const t={},n=s.slice(0,f);for(const r of n)t[r]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[r,_]of Object.entries(a)){if(E(r)||!w(e,r))continue;const i=d(r),u=b(e,i);for(const l of _){const c=M(l,u);if(c===void 0)continue;const p=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 p)t[g.ref]?.push({column:l,id:g.id,table:r})}}return{references:t,storageColumns:a}},se=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(r=>({args:r.args,functionPath:r.functionPath,table:r.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),s=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:s}},G=20,ne=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),oe=(e,a,s,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+s,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),_e=(e,a=G)=>{const s=new Map,t=new Map;for(const o of e){for(const r of Object.values(o.shapes??{})){const _=r.name??"(unknown shape)";s.set(_,(s.get(_)??0)+1)}for(const r of o.whispers??[])t.set(r,(t.get(r)??0)+1)}const n=[...[...s].map(([o,r])=>({kind:"shape",subscribers:r,topic:o})),...[...t].map(([o,r])=>({kind:"whisper",subscribers:r,topic:o}))];return n.sort((o,r)=>r.subscribers-o.subscribers||o.topic.localeCompare(r.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{J as ADMIN_FUNCTIONS,Y as ADMIN_FUNCTION_PREFIX,G as DEFAULT_FANOUT_TOPIC_LIMIT,V as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,z as RELATION_FUNCTION_PREFIX,ne as createFanoutCounters,j as datePrefixRange,te as facetColumn,re as findStorageReferences,Z as listTables,ee as readTablePage,oe as recordFanoutPass,ae as selectMatchingIds,_e as summarizeFanoutTopics,se as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{s as $,a as u}from"./wire-codec-D_fiax9d.mjs";import{runDrizzle as s}from"./runDrizzle-B6rnz3so.mjs";import{serializeSqlValue as w}from"./serializeSqlValue-DnpyaLcw.mjs";const c="__doc__",y=e=>JSON.stringify(u(e)),d=e=>$(JSON.parse(e)),D=(e,t)=>`${e}__geo_${t}`,f=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${c}, '$.${t.replaceAll("'","''")}')`,T=e=>f("",e),U=e=>i.raw(T(e)),m=(e,t)=>f(`${l(e)}.`,t),b=(e,t)=>i.raw(m(e,t)),g=(e,t,r,o)=>i`CREATE ${o?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,n=i.identifier("__key__"),p=i.identifier("__value__"),E=i.identifier("__count__"),h=(e,t,r,o,a)=>i`INSERT INTO ${i.identifier(e)} (${n}, ${p}, ${E}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${n}) DO UPDATE SET ${a}`,q=e=>{const t=[];for(const[r,o]of Object.entries(e.shape)){const a=o._meta?.column;a&&t.push([r,a])}return t},S=e=>{if(!e)return;const t=e[c];let r;typeof t=="string"?r=d(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const a=e._creationTime;return typeof a=="number"&&(r._creationTime=a),r},C=e=>{try{return S(e)}catch{return}},_=new WeakMap,L=e=>{const t=_.get(e);if(t!==void 0)return t;let r;try{s(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{s(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return _.set(e,r),r};export{E as AGG_COUNT,n as AGG_KEY,p as AGG_VALUE,c as DOC_COLUMN,h as aggUpsertSql,g as createIndexSql,d as decodeDocJson,y as encodeDocJson,D as geoTableName,L as isFtsAvailable,T as jsonPath,U as jsonPathSql,m as qualifiedJsonPath,b as qualifiedJsonPathSql,l as quoteIdentifier,S as rowToDocument,w as serializeSqlValue,q as tableColumns,C as tryRowToDocument};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{encodeDocJson as C,decodeDocJson as l}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{ConflictError as $}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`)},m=(t,i,o,E,c,s)=>{const r=s===void 0?null:C(s);a(t,e`INSERT INTO ${e.identifier(d)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${o}, ${E}, ${c}, ${r})`)},q=(t,i={})=>{const o=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),c=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(r=>e`${r}`),e`, `)})`:e``,s=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(d)} WHERE seq > ${o}${c} ORDER BY seq ASC LIMIT ${E}`).toArray().map(r=>{const T={id:r.id,op:r.op,seq:r.seq,table:r.table,ts:r.ts};return r.doc===null?T:{...T,doc:l(r.doc)}});return{changes:s,cursor:s.at(-1)?.seq??o}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(d)} WHERE seq <= ${i}`)},S=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${d}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??0},h=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},u=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const o=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${o})`),o},M=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},L=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const o=i.doc??{};try{await t.insert(i.table,o,{allowExplicitId:!0})}catch(E){if(!(E instanceof $))throw E;const c={...o};delete c._id,await t.replace(i.id,c,void 0,{allowExplicitId:!0})}},b=async(t,i)=>{for(const o of i)await L(t,o)};export{d as CDC_LOG_TABLE,n as CDC_META_TABLE,m as appendCdcChange,b as applyCdcChanges,M as bumpCdcEpoch,I as migrateCdcLog,p as migrateCdcMeta,h as minCdcSeq,q as readCdcChanges,S as readCdcCursor,u as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{n as At,k as xt,x as Ue,T as ye,y as It,c as vt}from"./ctx-db-companions-7fIu-E2H.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as Ct,throwingScheduler as kt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ve,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-DKo6dwBP.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Me,selectIndexForGroupBy as Mt,selectIndexForCount as Lt,selectIndexForAggregate as Dt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Ft}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{backfillAggregateIndexes as br,backfillRankIndexes as Er,backfillSearchIndexes as yr}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{appendCdcChange as Ot}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{CDC_LOG_TABLE as Sr,applyCdcChanges as Tr,bumpCdcEpoch as _r,minCdcSeq as Rr,readCdcChanges as Ar,readCdcCursor as xr,readCdcEpoch as Ir,trimCdcChanges as vr}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{computeRankPage as et}from"./computeRankPage-B7U6t1fW.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as P,encodeDocJson as se,AGG_VALUE as Se,AGG_COUNT as Le,AGG_KEY as Te,jsonPathSql as Y,rowToDocument as ce,tableColumns as mt,isFtsAvailable as Wt,tryRowToDocument as wt,geoTableName as Bt,qualifiedJsonPathSql as tt}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{coveringGeohashes as qt,boundingBoxGeohashes as Ut,pointInBoundingBox as Pt,haversineMeters as jt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as Ht}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Gt,buildSeekWhere as gt,decodeCursor as We,applySelect as nt,encodeCursor as Be,softDeleteScope as de,buildSeekBeforeWhere as Kt}from"./applySelect-BjgwvZmI.mjs";import{sortColumnName as rt,resolveRankPartition as zt,encodePartitionKey as Qt,RANK_TIEBREAK as Vt,rankTableName as ot}from"./RANK_TIEBREAK-D541BOFR.mjs";import{indexKeysForRow as Yt,buildIndexRange as Jt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as De,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs";import{runRowValidators as Fe,resolveWith as at,relationHooks as st,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-fMu_5DR5.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as kr,advanceClientWatermark as Mr,migrateClientWatermark as Lr,readClientWatermark as Dr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Or,deleteGlobalShapeSnapshot as Wr,deleteGlobalShapeSnapshotsForConnection as Br,migrateGlobalShapeSnapshot as qr,readGlobalShapeSnapshot as Ur,writeGlobalShapeSnapshot as Pr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Hr,readIdempotent as Gr,trimIdempotent as Kr,writeIdempotent as zr}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as Vr}from"./runShardMigrations-DhZLG0bn.mjs";import{SEARCH_STATE_TABLE as Jr}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Zr,selectShapeRows as eo}from"./selectShapeMemberIds-BD3JiZn-.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";import{quoteIdentifier as rn}from"./quoteIdentifier-CObIFRhb.mjs";const on=o=>{const i=new TextEncoder().encode(o);let t="";for(const l of i)t+=String.fromCodePoint(l);return btoa(t)},an=o=>{const i=atob(o),t=Uint8Array.from(i,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},sn=()=>new b("BAD_REQUEST","invalid cursor"),lt=16,dt=8,X=1024,Pe=(o,i)=>i.query(o),ln=(o,i,t)=>{const l=At(o,t);if(l.length===0)return 0;let d=0;for(const[p,w]of i.entries()){const A=p===i.length-1;let y=0;for(const g of l)(A?g.startsWith(w):g===w)&&(y+=1);if(y===0)return 0;d+=y}return d},dn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(l)}},cn=(o,i,t)=>{const l={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new b("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=dt)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(dt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),l},search:(d,p)=>{const w=o;if(d!==w.definition.field)throw new b("INTERNAL",`search index "${w.indexName}" on table "${i}" indexes "${w.definition.field}", not "${d}"`);const A=Pe(p,t).length;if(A>lt)throw new b("BAD_REQUEST",`search index "${w.indexName}" on table "${i}": at most ${String(lt)} search terms are supported (got ${String(A)})`);return w.field=d,w.query=p,w.hasQuery=!0,l}};return l},un=o=>{if(o.length>X)throw new b("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},fn=o=>Math.min(o.offset+o.numItems+1,X),hn=o=>on(`search:${String(o)}`),pn=o=>{let i;try{i=an(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},$n=o=>{if(typeof o.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?pn(o.cursor):0;if(t===void 0)throw sn();if(t+i>X)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},mn=(o,i)=>{const t=i.offset+i.numItems,l=i.numItems>0&&o.length>t;return{continueCursor:l?hn(t):null,isDone:!l,page:o.slice(i.offset,t)}},wn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new b("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,bn=o=>{if(!gn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},ct=50,bt=500,En=128,le=(o,i,t)=>{const l=i??bt;if(o>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},yn=o=>{const i={eq:(t,l)=>(o.sqlConditions.push({comparator:"=",field:t,value:l}),i),gt:(t,l)=>(o.sqlConditions.push({comparator:">",field:t,value:l}),i),gte:(t,l)=>(o.sqlConditions.push({comparator:">=",field:t,value:l}),i),lt:(t,l)=>(o.sqlConditions.push({comparator:"<",field:t,value:l}),i),lte:(t,l)=>(o.sqlConditions.push({comparator:"<=",field:t,value:l}),i)};return i},Nn=o=>Math.max(o,X),Et=(o,i)=>{const t=o.filters.map(l=>n`${Y(l.field)} = ${ie(l.value)}`);return i&&t.push(i),t},Sn=(o,i,t,l,d)=>{const p=Pe(t.query,Ue(t.definition.language));if(p.length===0)return[];const w=vt(i,t.indexName),A=`${w}__vocab`,y=p.length-1,g=p.map((L,M)=>{const j=dn(L,M===y),W=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(M))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${W} GROUP BY ${n.identifier("doc")}`}),N=p.map((L,M)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(M))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(ye)} AS ${n.identifier(ye)}, ${n.join(N,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(ye)} HAVING ${n.join(N.map(L=>n`${L} > 0`),n` AND `)}`,_=Et(t,d);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(ye)}`;_.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(l))}`;const F=[];for(const L of B(o,C)){const M=wt(L);if(M){const j=L.__score__;F.push({document:M,score:typeof j=="number"?j:Number(j??0)})}}return F},Tn=(o,i,t,l,d)=>{const p=Ue(t.definition.language),w=Pe(t.query,p);if(w.length===0)return[];const A=Et(t,d);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(Nn(l)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=wt(S);if(!_)continue;const C=ln(It(_,t.definition),w,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,l).map(S=>({document:S.doc,score:S.score}))},Oe=(o,i,t,l)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},_n=(o,i)=>{const t=o,l={near:(d,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},l},within:d=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d.sw,".within() sw corner",i,t.indexName),Oe(d.ne,".within() ne corner",i,t.indexName),d.sw.lat>d.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},l}};return l},Rn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:l,lng:d}=t;return typeof l=="number"&&typeof d=="number"?{lat:l,lng:d}:void 0},An=(o,i)=>{const t=Rn(o,i.definition.field);if(!t)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const d=jt(i.near.point,t);return d<=i.near.radiusMeters?{creationTime:l,distance:d}:void 0}return Pt(t,i.within)?{creationTime:l,distance:0}:void 0},xn=(o,i,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const d=t.near?qt(t.near.point,t.near.radiusMeters):Ut(t.within),p=Bt(i,t.indexName),w=d.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),A=[n`(${n.join(w,n` OR `)})`];l&&A.push(l);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=ce(S),C=_?An(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},yt=(o,i,t,l)=>{const d=[];for(const p of o)if(i.every(w=>w(l(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},In=(o,i,t,l,d,p=()=>{})=>{const w=t.within!==void 0,A=xn(o,i,t,d).map(y=>({distanceMeters:w?null:y.distance,document:y.doc}));return p(A.length),typeof l=="number"?A.slice(0,Math.max(0,Math.floor(l))):A},Nt=(o,i,t,l,d,p=()=>{})=>{const{geo:w}=t;if(!w)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=In(o,i,w,A?void 0:d,l,p);return A?yt(y,t.inMemoryFilters,d,g=>g.document):y},vn=(o,i,t,l,d,p=()=>{})=>Nt(o,i,t,l,d,p).map(w=>w.document),Cn=(o,i,t,l,d,p,w=()=>{})=>{const A=[];for(const S of t.sqlConditions)A.push(n`${Y(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);l&&A.push(l);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();w(g.length);const N=[];for(const S of g){const _=ce(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:Y,serialize:ie},kn=o=>{let i=0;const t=[],l={fieldRef:Y,relationExists:d=>{const{childWhere:p,negated:w,parentTable:A,relation:y}=d,g=`__rel_${String(i)}`,N=t.at(-1)??A;i+=1,o(y.table,U);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${tt(g,_)} = ${tt(N,S)}`;t.push(g);const F=ne(p,l);t.pop();const L=F?n`${C} AND ${F}`:C,M=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${L})`;return w?n`NOT ${M}`:M},serialize:ie};return l},St=o=>{const i=o.map(t=>n`${Y(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${Y("id")} ASC`),n.join(i,n`, `)},Mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ln=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Dn=(o,i,t,l)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Mn[p.comparator]??"eq"]:p.value}}));if(t&&d.push(gt(i,We(t))),l&&d.push(Kt(i,We(l))),d.length!==0)return d.length===1?d[0]:{AND:d}},Fn=(o,i,t)=>{const l=[];for(const d of o){const p=ce(d);if(p&&i.every(w=>w(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},On=(o,i,t,l,d,p=()=>{})=>{const w=Math.max(0,Math.floor(l.numItems)),A=Ln(t),y=typeof l.endCursor=="string",g=ne(Dn(t,A,l.cursor,l.endCursor),oe),N=d&&g?n`${g} AND ${d}`:d??g;let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${St(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String(w+1))}`);const C=B(o,S).toArray();p(C.length);const F=Fn(C,t.inMemoryFilters,_||y?void 0:w);if(y){const W=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:F,splitCursor:W?Be(W,A):null}}const L=F.length>w,M=L?F.slice(0,w):F,j=M.at(-1);return{continueCursor:L&&j?Be(j,A):null,isDone:!L,page:M}};class Wn extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Bn=/\s/u,qn=String.fromCodePoint(0),ut=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Bn.test(t)||t.includes(qn)?null:t},Un=(o,i,t,l=()=>{},d=()=>{},p=()=>{})=>{const w=i.tables[t];if(!w)throw new b("INTERNAL",`unknown table: ${t}`);const A=de(w.softDeleteMode,void 0),y=A?ne(A,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Ft(o,t,w);const I=g.inMemoryFilters.length>0,k=wn(I?void 0:E),H=Wt(o)?Sn(o,t,v,k,y):Tn(o,t,v,k,y);return I?(N=H.length,yt(H,g.inMemoryFilters,E,te=>te.document)):(E===void 0&&un(H),H)},_=E=>S(E).map(v=>v.document),C=E=>{const v=$n(E);return mn(_(fn(v)),v)},F=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${Y(I)} ${n.raw(v)}`),n`, `)},L=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(Jt(t,g.indexName,g.indexFields,g.sqlConditions,ie))},M=E=>{L();let v=0;const I=(()=>{if(g.search){const k=_(E);return v=N,k}return g.geo?vn(o,t,g,y,E,k=>{v=k}):Cn(o,t,g,y,F(),E,k=>{v=k})})();return p(Math.max(v,I.length)),I},j=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return Nt(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},W={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await W.paginate({cursor:v??null,numItems:En});for(const k of I.page)E.every(H=>H(k))&&(yield k);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),W},async first(){return M(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",W},async paginate(E){let v=0;if(L(),g.search){const k=C(E);return p(k.page.length),k}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=On(o,t,g,E,y,k=>{v=k});return p(Math.max(v,I.page.length)),I},async take(E){return M(E)},async unique(){const E=M(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Wn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=(w.geoIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);l(t,E,"geo");const k={definition:I,indexName:E};if(g.geo=k,v(_n(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return W},withIndex(E,v){const I=w.indexes.find(k=>k.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return l(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(yn(g)),W},withSearchIndex(E,v){const I=(w.searchIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);l(t,E,"search");const k={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=k,v(cn(k,t,Ue(I.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return W}};return W},ft=(o,i,t)=>{const l={...i};for(const[d,p]of mt(o)){if(p.serverDefault){l[d]=p.serverDefault({auth:t});continue}l[d]===void 0&&(p.defaultFn?l[d]=p.defaultFn():"defaultValue"in p&&(l[d]=p.defaultValue))}return l},ht=(o,i,t,l)=>{const d=t;for(const[p,w]of mt(o)){if(w.serverDefault){p in i&&(d[p]=w.serverDefault({auth:l}));continue}w.onUpdateFn&&!(p in i)&&(d[p]=w.onUpdateFn())}},pt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Pn=/unique constraint failed/i,jn=o=>o instanceof Error&&Pn.test(o.message),qe=(o,i,t)=>{try{B(o,t)}catch(l){throw jn(l)?new pe(`unique constraint violation on "${i}"`,"unique"):l}},_e=(o,i,t)=>{if(qe(o,i,t),B(o,n`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},$t=(o,i,t,l,d,p,w)=>{const A=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let M=0;M<S;M+=1)_.push(n`${n.identifier(t[M])} IS ${p[M]}`);const C=t[S],F=l[S];if(C!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(M)} ${p[S]}`)}else _.push(n`${n.identifier(Vt)} < ${w}`);const[L]=_;A.push(_.length===1&&L!==void 0?L:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d}`).one();return{before:g.c,total:N.c}},mr=o=>{const{sql:i}=o,{schema:t}=o,l=o.broadcast??(()=>{}),d=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const u=[];for(const h of r)h&&u.push(...Yt(a,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let w=!1;const A=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,U)}),N=(e,r)=>{r!==void 0&&r!==U&&!w&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:F}=o,L=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??kt,{globalDb:W}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=j,k=tn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),H=(e,r,a,u)=>{v&&Ot(i,L(),e,r,a,u)},te=e=>t.tables[e]?.shardMode?.kind==="global",je=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}return q},Re=e=>je(e,"cascade"),Q=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}},Ae=(e,r)=>je(e,"relation load").findMany(e,r),He=(e,r)=>(te(e)&&N(e,U),Ae(e,r)),Tt=e=>!te(e.table),Ge=o.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:ze}=o,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Qe=async(e,r,a,u)=>{const h=Q(e,"relation grouped count");if(h)return N(e,U),Zt((x,K)=>h.count(x,K),e,r,a,u);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const s=de(f.softDeleteMode,void 0),c={[r]:{in:a}},$=z(z(c,u),s),T=await $e($,e,void 0),m=ne(T,oe),R=Y(r);let O=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;m&&(O=n`${O} WHERE ${m}`),O=n`${O} GROUP BY ${R}`;const D=B(i,O).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let me=0;const Ve=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ve.add(`${e} ${a.timing} ${a.op}`);const Z=(e,r,a)=>Ve.has(`${e} ${r} ${a}`),ee=async(e,r,a)=>{if(me+=1,me>ct)throw me-=1,new pe(`trigger recursion exceeded ${String(ct)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:Rt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{me-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:xe,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Ye,syncGeo:ge,syncRanks:he,syncSearch:be}=xt({broadcast:l,indexKeysFor:(e,r)=>d(e,r),invalidateCache:(e,r,a)=>F?.invalidate(e,r,d(e,a)),recordCdc:H,schema:t,sql:i}),Je=(e,r,a)=>{const{shardMode:u}=r;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(a.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${u.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})},Xe=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=Xe(r);if(a.length===0)return;const u=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),h=n`${n.join(u,n` UNION ALL `)} LIMIT 1`,[f]=B(i,h).toArray();if(!f)return;const s=f.__t__,c=ce(f);if(typeof s!="string"||!c)return;const $=f[P];return{docJson:typeof $=="string"?$:se($??{}),row:c,tableName:s}},_t=(e,r)=>{const a=[...new Set(e)],u=new Map;if(a.length===0)return u;const h=Xe(r);if(h.length===0)return u;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const c=a.slice(s,s+f),$=n.join(c.map(R=>n`${R}`),n`, `),T=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${$})`),m=n.join(T,n` UNION ALL `);for(const R of B(i,m)){const{id:O,__t__:D}=R;typeof D=="string"&&typeof O=="string"&&u.set(O,D)}}return u},Ze={assertRankPartitionLocal:Je,ensureRankBackfilled:Ie,onRead:N,rowToDocument:ce,schema:t,sql:i},q={system:k,async aggregate(e,r){const a=Q(e,"aggregate");if(a)return N(e,U),a.aggregate(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,U);const h=de(u.softDeleteMode,void 0),f=z(z(r.baseWhere,r.where),h),s=await $e(f,e,r.relationBaseWhere),c=s!==f;if(u.aggregateIndexes&&!r.baseWhere&&!c&&!h){const D=Dt(u.aggregateIndexes,r.op,r.field,r.where);if(D){xe(e,D.index);const x=ve(D.index.by??[],D.key),K=ke(e,D.index.name),V=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${x}`).toArray()[0];return Ce(r.op,V)}}const $=ne(s,oe),T=Ne(r.op),m=Y(r.field);let R=n`SELECT ${n.raw(T)}(${m}) AS value FROM ${n.identifier(e)}`;return $&&(R=n`${R} WHERE ${$}`),B(i,R).toArray()[0]?.value??null},asId(e,r){const a=ut(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=Q(e,"count");if(a)return N(e,U),a.count(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=Ct(r);if(h.restrictsCounts)throw new Me(e);N(e,U);const f=de(u.softDeleteMode,void 0),s=z(z(h.baseWhere,h.where),f),c=await $e(s,e,h.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!h.baseWhere&&!$&&!f){const R=Lt(u.aggregateIndexes,h.where);if(R){xe(e,R.index);const O=ve(R.index.by??[],R.key),D=ke(e,R.index.name),x=B(i,n`SELECT ${Se} AS value FROM ${n.identifier(D)} WHERE ${Te} = ${O}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(c,oe);let m=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(m=n`${m} WHERE ${T}`),B(i,m).one().count},async delete(e,r,a){const u=re(e,r);if(!u){const m=r===void 0?W:void 0;m&&await m.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s],$=a?.hard===!0,T=!$&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(T&&f[T]!==null&&f[T]!==void 0)){if(Z(s,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:s}),await Xt({deletedId:e,deletedReference:m=>f[m],findHolders:async(m,R,O)=>(await Re(m).findMany(m,{includeDeleted:$,where:{[R]:O}})).page,onCascade:(m,R)=>Re(m).delete(R,void 0,a),onRestrict:m=>{throw new pe(m,"restrict")},onSetNull:(m,R,O)=>Re(m).patch(R,{[O]:null}),schema:t,tableName:s}),ue(s),fe(s),T){const m={...f,[T]:L(),_id:e};_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,m,f),ge(s,e,void 0),we(s,f,m),he(s,e,f,void 0),F?.invalidate(s,e,d(s,f,m)),H(s,e,"update",m),l({indexKeys:d(s,f,m),key:e,op:"update",row:m,table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}_e(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,f,void 0),he(s,e,f,void 0),F?.invalidate(s,e,d(s,f)),H(s,e,"delete"),l({indexKeys:d(s,f),key:e,op:"delete",table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??bt),u=r?.hard===void 0?void 0:{hard:r.hard},h=te(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await q.delete(c,h,u),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){le(e.length,r?.limit,"deleteMany");for(const u of e)await q.delete(u,a);return{deleted:e.length}},async deleteWhere(e,r,a){const u=(await(Q(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(le(u.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(u,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Ht(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=Q(e,"findMany");if(a)return N(e,U),a.findMany(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,U):N(e);const f=Gt(r.orderBy),s=r.cursor?gt(f,We(r.cursor)):void 0;let c=z(r.baseWhere,r.where);c=z(c,de(u.softDeleteMode,r.includeDeleted)),c=await it(c,{canPushExists:Ke?Tt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const $=Ke?kn(N):oe,T=ne(c,$);let m=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(m=n`${m} WHERE ${T}`),m=n`${m} ORDER BY ${St(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&(m=n`${m} LIMIT ${n.raw(String(R+1))}`);const O=B(i,m).toArray();h&&!w&&p?.recordRead(O.length);const D=[];for(const J of O){const G=ce(J);G&&(D.push(G),!h&&typeof G._id=="string"&&N(e,G._id))}if(R===void 0)return r.with&&await at({groupedCounter:Qe,fetcher:Ae,parents:D,...st(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:nt(D,r.select,r.with)};const x=D.length>R,K=x?D.slice(0,R):D,V=K.at(-1);return r.with&&await at({fetcher:Ae,groupedCounter:Qe,parents:K,...st(r),schema:t,tableName:e,with:r.with}),{continueCursor:x&&V?Be(V,f):null,isDone:!x,page:nt(K,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const u=r===void 0?W:void 0;return u?u.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=Q(e,"groupBy");if(a)return N(e,U),a.groupBy(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const h=r.agg??{op:"count"};if(Ne(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=de(u.softDeleteMode,void 0),s=z(z(r.baseWhere,r.where),f),c=await $e(s,e,r.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!r.baseWhere&&!$&&!f){const x=Mt(u.aggregateIndexes,h.op,h.field,r.by,r.where);if(x){xe(e,x.index);const K=ke(e,x.index.name),V=Object.keys(x.partial),J=[];if(V.length===(x.index.by??[]).length&&V.length>0){const ae=ve(x.index.by??[],x.partial),Ee=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${ae}`).toArray();return Ee.length>0&&J.push({key:{...x.partial},value:Ce(h.op,Ee[0])}),J}const G=B(i,n`SELECT ${Te} AS key, ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ee=JSON.parse(ae.key);J.push({key:Ee,value:Ce(h.op,ae)})}return J}}const T=ne(c,oe),m=r.by.map(x=>n`${Y(x)} AS ${n.identifier(x)}`);if(h.op==="count")m.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);m.push(n`${n.raw(Ne(h.op))}(${Y(x)}) AS value`)}let R=n`SELECT ${n.join(m,n`, `)} FROM ${n.identifier(e)}`;T&&(R=n`${R} WHERE ${T}`),R=n`${R} GROUP BY ${n.join(r.by.map(x=>Y(x)),n`, `)}`;const O=B(i,R).toArray(),D=[];for(const x of O){const K={};for(const J of r.by)K[J]=x[J]??null;const{value:V}=x;D.push({key:K,value:V==null?null:Number(V)})}return D},async insert(e,r,a){const u=Q(e,"insert");if(u){const T=await u.insert(e,r,a);return w||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=ft(h,r,E);Fe(h,f);let s;a?.clientId!==void 0?(bn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=M();const c=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:L(),$={...f,_creationTime:c,_id:s};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...$},id:s,op:"insert",table:e}),ue(e),fe(e),qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${c}, ${se($)})`),Ye(e,s,$),Z(e,"after","insert")&&await ee("after","insert",{doc:$,id:s,op:"insert",table:e}),await C({doc:$,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(le(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const $ of r){const T=await u.insert(e,$,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite($),l({key:T,op:"insert",row:{...$,_id:T},table:e}),c.push(T)}return c}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const f=r.map(c=>{const $=ft(h,c,E),T=a?.allowExplicitId===!0&&typeof $._id=="string"?$._id:M(),m=a?.allowExplicitId===!0&&typeof $._creationTime=="number"?$._creationTime:L();return{creationTime:m,document:{...$,_creationTime:m,_id:T},id:T}});if(!w)for(const c of f)p?.recordWrite(c.document);const s=n.join(f.map(c=>n`(${c.id}, ${c.creationTime}, ${se(c.document)})`),n`, `);qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:c,id:$}of f)Ye(e,$,c),await _({doc:c,id:$,op:"insert",table:e});return f.map(c=>c.id)},async insertMany(e,r,a){le(r.length,a?.limit,"insertMany");const u=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(u&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return ut(t,e,r)},async patch(e,r,a){const u=re(e,a);if(!u){const T=a===void 0?W:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s];if(!c)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),pt("patch",r);const $={...f,...r,_id:e};ht(c,r,$,E),Fe(c,$,!0),Z(s,"before","update")&&await ee("before","update",{doc:{...$},id:e,op:"update",previous:f,table:s}),ue(s),fe(s),_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se($)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,$,f),ge(s,e,$),we(s,f,$),he(s,e,f,$),F?.invalidate(s,e,d(s,f,$)),H(s,e,"update",$),l({indexKeys:d(s,f,$),key:e,op:"update",row:$,table:s}),Z(s,"after","update")&&await ee("after","update",{doc:$,id:e,op:"update",previous:f,table:s}),await C({doc:$,id:e,op:"update",table:s})},async patchMany(e,r,a){le(e.length,r?.limit,"patchMany");for(const u of e)await q.patch(u.id,u.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const u=(await(Q(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(le(u.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(u,a),{patched:u.length}},query(e){const r=Q(e,"query");return r?(N(e,U),r.query(e)):Un(i,t,e,S,a=>{a?g(a):N(e,U)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const u=Q(e,"rank");if(u)return N(e,U),u.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(G=>G.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,h,f),a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const c=ot(e,f.name),$=f.sortBy.map((G,ae)=>rt(ae)),T=$.map(G=>rn(G)).join(", "),m=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(c)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=m;if(R===void 0)return null;let O=R.__partition__;const D=z(a.baseWhere,a.where);De(D,t,e,"rank");const x=zt(f,D);if(x){const G=Qt(f.partitionBy??[],x);if(G!==O)return null;O=G}const K=$.map(G=>R[G]),{before:V,total:J}=$t(i,c,$,f.sortBy,O,K,s);return{position:V+1,total:J}},async rankBefore(e,r,a){if(te(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find($=>$.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,h);const f=ot(e,h.name),s=h.sortBy.map(($,T)=>rt(T)),c=h.sortBy.map(($,T)=>ie(a.sortValues[T]??null));return $t(i,f,s,h.sortBy,a.partitionKey,c,a.rowId)},async rankPage(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return N(e,U),u.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=et(Ze,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(c=>c.doc)}},async rankPageRows(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:u,hasMore:h,rows:f}=et(Ze,e,r,a);return{directions:u,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?W:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const u=t.tables[a.tableName]?.softDeleteMode?.field;if(!u)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[u]!==null&&a.row[u]!==void 0;await q.patch(e,{[u]:null},r),h&&he(a.tableName,e,void 0,a.row)},async replace(e,r,a,u){const h=re(e,a);if(!h){const R=a===void 0?W:void 0;if(R){await R.replace(e,r,void 0,u);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:c}=h,$=t.tables[c];if(!$)throw new b("INTERNAL",`unknown table: ${c}`);pt("replace",r);const T=u?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),m={...r,_creationTime:T,_id:e};ht($,r,m,E),Fe($,m),Z(c,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),_e(i,c,n`UPDATE ${n.identifier(c)} SET _creationTime = ${T}, ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),be(c,e,m,s),ge(c,e,m),we(c,s,m),he(c,e,s,m),F?.invalidate(c,e,d(c,s,m)),H(c,e,"update",m),l({indexKeys:d(c,s,m),key:e,op:"update",row:m,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:s,table:c}),await C({doc:m,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,u=Object.entries(t.tables).filter(([c,$])=>r.has(c)||a!==void 0&&!a.includes(c)?!1:$.shardMode?.kind!=="global").map(([c])=>c);if(a!==void 0){for(const c of a)if(!t.tables[c])throw new b("INTERNAL",`wipeShard: unknown table: ${c}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of u){const $=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[c]=$.deleted,f+=$.deleted}return{deleted:f,tables:h}}},Rt={db:q,scheduler:j};return o.enforceRls===!0?en(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>_t(e,r)):q};export{Sr as CDC_LOG_TABLE,kr as CLIENT_WATERMARK_TABLE,Or as GLOBAL_SHAPE_SNAPSHOT_TABLE,Hr as IDEMPOTENCY_TABLE,Wn as NotUniqueError,Jr as SEARCH_STATE_TABLE,Mr as advanceClientWatermark,Tr as applyCdcChanges,bn as assertValidClientId,br as backfillAggregateIndexes,Er as backfillRankIndexes,yr as backfillSearchIndexes,_r as bumpCdcEpoch,mr as createShardCtxDb,Wr as deleteGlobalShapeSnapshot,Br as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,qr as migrateGlobalShapeSnapshot,Rr as minCdcSeq,ut as normalizeIdStructurally,Ar as readCdcChanges,xr as readCdcCursor,Ir as readCdcEpoch,Dr as readClientWatermark,Ur as readGlobalShapeSnapshot,Gr as readIdempotent,Vr as runShardMigrations,Zr as selectShapeMemberIds,eo as selectShapeRows,vr as trimCdcChanges,Kr as trimIdempotent,Pr as writeGlobalShapeSnapshot,zr as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const g=(e,t)=>e<t?-1:e>t?1:0,r=(e,t)=>`${e}__agg_${t}`,n=e=>{if(typeof e=="number")return Number.isFinite(e)?e:void 0},c=(e,t,l,o)=>{const u=e.get(t)??{count:0,value:null};if(l.op==="count"){u.count+=1,u.value=u.count,e.set(t,u);return}const a=n(o[l.field??""]);if(l.op==="sum"||l.op==="avg"){a!==void 0&&(u.value=(u.value??0)+a,u.count+=1),e.set(t,u);return}u.count+=1,a!==void 0&&(u.value===null?u.value=a:u.value=l.op==="min"?Math.min(u.value,a):Math.max(u.value,a)),e.set(t,u)},v=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,i=(e,t)=>{if(e.length===0)return"";const l={};for(const o of e.toSorted(g))l[o]=t[o]??null;return JSON.stringify(l)};export{r as aggregateTableName,n as coerceAggregateNumber,g as compareStrings,i as encodeAggregateKey,c as foldAggregateTally,v as readAggregateValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";const m="id",S=new Set(["_id","id"]),_=r=>{const e=[];for(const t of r??[])for(const[o,i]of Object.entries(t))e.push({direction:i,field:o});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},g=r=>{const e=new TextEncoder().encode(r);let t="";for(const o of e)t+=String.fromCodePoint(o);return btoa(t)},y=r=>{const e=atob(r),t=Uint8Array.from(e,o=>o.codePointAt(0)??0);return new TextDecoder().decode(t)},A=(r,e)=>{const t=e.map(o=>r[o.field]);return t.push(r._id),g(JSON.stringify(t))},a=()=>new p("BAD_REQUEST","invalid cursor"),D=r=>{let e;try{e=JSON.parse(y(r))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(r,e,t)=>{const o=r.some(s=>S.has(s.field))?r:[...r,{direction:"asc",field:m}],i=[];for(const[s,n]of o.entries()){const c=[];for(const[u,h]of o.slice(0,s).entries())c.push({[h.field]:{eq:e[u]}});const l=t(n.direction,s===o.length-1);c.push({[n.field]:{[l]:e[s]}});const[d]=c;i.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:i}},E=(r,e)=>f(r,e,t=>t==="desc"?"lt":"gt"),w=(r,e)=>r==="desc"?e?"gte":"gt":e?"lte":"lt",T=(r,e)=>f(r,e,w),b=["_id","_creationTime"],k=(r,e,t)=>{if(!e)return r;const o=new Set([...e,...b,...t?Object.keys(t):[]]);return r.map(i=>{const s={};for(const n of o)n in i&&(s[n]=i[n]);return s})},v=(r,e)=>r&&e!==!0?{[r.field]:{isNull:!0}}:void 0;export{k as applySelect,T as buildSeekBeforeWhere,E as buildSeekWhere,D as decodeCursor,A as encodeCursor,y as fromBase64,a as invalidCursor,_ as normalizeOrderKeys,v as softDeleteScope,g as toBase64};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{O as R,q as p,x,T as h,l as A,y as k,c as w}from"./ctx-db-companions-7fIu-E2H.mjs";import"@lunora/errors";import{sql as i}from"drizzle-orm";import{matchesStaticWhere as M}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as y,aggregateTableName as C}from"./aggregateTableName-DKo6dwBP.mjs";import{migrateSearchState as N,readSearchBackfillState as D,writeSearchBackfillState as F}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as d}from"./runDrizzle-B6rnz3so.mjs";import{isFtsAvailable as T,rowToDocument as u,AGG_KEY as _,AGG_VALUE as G,AGG_COUNT as U,DOC_COLUMN as m,tryRowToDocument as v}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{matchesRankStaticWhere as j,rankTableName as q}from"./RANK_TIEBREAK-D541BOFR.mjs";const B=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>d(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(n)}`).one().count>0,I=(e,n)=>d(e,i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)}`).toArray(),V=(e,n,o)=>{const r=C(n,o.name);if(b(e,r))return;const t=o.by??[],a=new Map,c=I(e,n);for(const s of c){const f=u(s);if(!f||o.where&&!M(f,o.where))continue;const l=L(t,f);y(a,l,o,f)}for(const[s,f]of a)d(e,i`INSERT INTO ${i.identifier(r)} (${_}, ${G}, ${U}) VALUES (${s}, ${f.value}, ${f.count})`)},ee=(e,n)=>{for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const t of r.aggregateIndexes)V(e,o,t)},W=(e,n,o)=>{const r=q(n,o.name);if(b(e,r))return;const t=R(o),a=I(e,n);for(const c of a){const s=u(c);!s||o.where&&!j(s,o.where)||p(e,r,o,t,s._id,s)}},re=(e,n)=>{for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const t of r.rankIndexes)W(e,o,t)},g=500,O=(e,n,o)=>{const r=w(n,o.name),{profile:t}=x(o.language),a=B(D(e,r),t);if(a.finished)return!0;a.wipe&&d(e,i`DELETE FROM ${i.identifier(r)}`);const{cursor:c}=a,s=d(e,c===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)} ORDER BY id ASC LIMIT ${i.raw(String(g))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(n)} WHERE id > ${c} ORDER BY id ASC LIMIT ${i.raw(String(g))}`).toArray();let f=c;for(const E of s){const{id:$}=E;if(typeof $!="string")continue;f=$,d(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(h)} = ${$}`);const S=v(E);S&&d(e,i`INSERT INTO ${i.identifier(r)} (${i.identifier(A)}, ${i.identifier(h)}) VALUES (${k(S,o)}, ${$})`)}const l=s.length<g;return F(e,r,f,l,t),l},ie=(e,n,o)=>{if(T(e))for(const r of o.searchIndexes??[])r.staged||O(e,n,r)},ne=(e,n)=>{if(T(e)){N(e);for(const[o,r]of Object.entries(n.tables))if(!(r.shardMode?.kind==="global"||!r.searchIndexes))for(const t of r.searchIndexes){let a=!1;for(;!a;)a=O(e,o,t)}}};export{ee as backfillAggregateIndexes,re as backfillRankIndexes,ne as backfillSearchIndexes,ie as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as l,q,O as C}from"./ctx-db-companions-7fIu-E2H.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DKo6dwBP.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./AGG_COUNT-B0Pb1nQZ.mjs";import"./param-B5lF5Jd9.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./RANK_TIEBREAK-D541BOFR.mjs";import"./serializeSqlValue-DnpyaLcw.mjs";export{l as createCompanionSync,q as insertRankRow,C as rankColumnsSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as x,aggregateSqlFunction as ie}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as oe,aggregateTableName as U,coerceAggregateNumber as I}from"./aggregateTableName-DKo6dwBP.mjs";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{isFtsAvailable as re,DOC_COLUMN as W,rowToDocument as B,AGG_KEY as N,AGG_VALUE as S,AGG_COUNT as _,geoTableName as ae,aggUpsertSql as j,jsonPathSql as F}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{param as se}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as le,GEO_DEFAULT_PRECISION as de}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{encodePartitionKey as ce,sortColumnName as ue,matchesRankStaticWhere as P,rankTableName as V}from"./RANK_TIEBREAK-D541BOFR.mjs";import{serializeSqlValue as K}from"./serializeSqlValue-DnpyaLcw.mjs";const fe=["de","en","es","fr","it","nl","none","pt"],$e=t=>fe.includes(t),me="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",Ee="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",he="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ge="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",pe="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",ye="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",_e="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,J=t=>t.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase(),O=t=>new Set(J(t).split(" ")),Se={de:O(Ee),en:O(me),es:O(he),fr:O(ge),it:O(pe),nl:O(ye),none:new Set,pt:O(_e)},ve=2,Te=256,G=new Map,Ae=t=>{const o=t!==void 0&&$e(t)?t:"none",l=G.get(o);if(l)return l;const g=Se[o],v=r=>{const T=(J(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(A=>A.length<=Te);return g.size===0?T:T.filter(A=>!g.has(A))},m={document:v,profile:`${o}-v${String(ve)}`,query:r=>{const T=v(r);return T.filter((A,w)=>T.lastIndexOf(A)===w)}};return G.set(o,m),m},we=(t,o)=>{if(!o.includes("."))return t[o];let l=t;for(const g of o.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Re=(t,o)=>`${t}__fts_${o}`,Le="__text__",H="__id__",Oe=1e3,Ne=(t,o)=>o.document(t),k=(t,o)=>we(t,o),je=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",xe=(t,o,l)=>t!==void 0&&o!==void 0&&k(t,l.field)===k(o,l.field),Ie=(t,o)=>Ne(je(k(t,o.field)),Ae(o.language)).slice(0,Oe).join(" "),Fe=(t,o,l)=>[...t.partitionBy??[],...t.sortBy.map(g=>g.field),...t.where?Object.keys(t.where):[]].every(g=>o[g]===l[g]),X=t=>e.join(["__id__","__partition__",...t.sortBy.map((o,l)=>ue(l))].map(o=>e.identifier(o)),e`, `),Y=(t,o,l,g,v,m)=>{const r=ce(l.partitionBy??[],m),T=l.sortBy.map(w=>K(m[w.field]??null)),A=e.join([v,r,...T].map(w=>se(w)),e`, `);$(t,e`INSERT INTO ${e.identifier(o)} (${g}) VALUES (${A})`)},ke=(t,o,l,g,v,m)=>{if(v&&m&&Fe(l,v,m))return;const r=V(o,l.name);v&&$(t,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!P(m,l.where))&&Y(t,r,l,X(l),g,m)},Pe=t=>{const{broadcast:o,indexKeysFor:l,invalidateCache:g,recordCdc:v,schema:m,sql:r}=t,T=new Set,A=new Set,w=(i,n)=>{const s=`${i}::${n.name}`;if(T.has(s))return;const u=U(i,n.name),d=n.by??[],f=new Map,E=$(r,e`SELECT id, _creationTime, ${e.identifier(W)} FROM ${e.identifier(i)}`).toArray();for(const b of E){const a=B(b);if(!a||n.where&&!x(a,n.where))continue;const c=L(d,a);oe(f,c,n,a)}$(r,e`DELETE FROM ${e.identifier(u)}`);const p=32,h=[...f];for(let b=0;b<h.length;b+=p){const a=h.slice(b,b+p),c=e.join(a.map(([y,R])=>e`(${y}, ${R.value}, ${R.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(u)} (${N}, ${S}, ${_}) VALUES ${c}`)}T.add(s)},Q=(i,n,s)=>{const u=n.by??[],d=ie(n.op),f=n.field??"",E=[],p=(a,c)=>{const y=K(c);y===null?E.push(e`${F(a)} IS NULL`):E.push(e`${F(a)} = ${y}`)};for(const a of u)p(a,s[a]??null);for(const[a,c]of Object.entries(n.where??{}))p(a,c!==null&&typeof c=="object"&&!Array.isArray(c)?c.eq:c);const h=E.length>0?e` WHERE ${e.join(E,e` AND `)}`:e``,b=F(f);return{value:$(r,e`SELECT ${e.raw(d)}(${b}) AS value FROM ${e.identifier(i)}${h}`).one().value??null}},Z=(i,n,s,u)=>{const d=U(i,n.name),{op:f}=n,E=n.field??"",p=a=>{$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${N} = ${a} AND ${_} <= 0`)},h=s&&(!n.where||x(s,n.where))?s:void 0,b=u&&(!n.where||x(u,n.where))?u:void 0;if(!(!h&&!b)){if(f==="count"){for(const[a,c]of[[h,-1],[b,1]]){if(!a)continue;const y=L(n.by??[],a);$(r,j(d,y,c,c,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}h&&p(L(n.by??[],h));return}if(f==="sum"||f==="avg"){for(const[a,c]of[[h,-1],[b,1]]){if(!a)continue;const y=I(a[E]);if(y===void 0)continue;const R=L(n.by??[],a);$(r,j(d,R,c*y,c,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}h&&p(L(n.by??[],h));return}if(h){const a=L(n.by??[],h),c=I(h[E]),y=$(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(d)} WHERE ${N} = ${a}`).toArray()[0],R=(y?.count??0)-1;if(R<=0)$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${N} = ${a}`);else if(y&&c!==void 0&&y.value!==null&&c===y.value){const te=Q(i,n,h);$(r,e`UPDATE ${e.identifier(d)} SET ${S} = ${te.value}, ${_} = ${R} WHERE ${N} = ${a}`)}else $(r,e`UPDATE ${e.identifier(d)} SET ${_} = ${_} - 1 WHERE ${N} = ${a}`)}if(b){const a=L(n.by??[],b),c=I(b[E]);if(c===void 0)$(r,j(d,a,null,1,e`${_} = ${_} + 1`));else{const y=f==="min"?"MIN":"MAX";$(r,j(d,a,c,1,e`${S} = ${e.raw(y)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ee=i=>{for(const n of m.tables[i]?.aggregateIndexes??[])w(i,n)},q=(i,n,s)=>{for(const u of m.tables[i]?.aggregateIndexes??[])Z(i,u,n,s)},C=(i,n)=>{const s=`${i}::rank::${n.name}`;if(A.has(s))return;const u=V(i,n.name),d=$(r,e`SELECT id, _creationTime, ${e.identifier(W)} FROM ${e.identifier(i)}`).toArray();$(r,e`DELETE FROM ${e.identifier(u)}`);const f=X(n);for(const E of d){const p=B(E);!p||n.where&&!P(p,n.where)||Y(r,u,n,f,p._id,p)}A.add(s)},ne=i=>{for(const n of m.tables[i]?.rankIndexes??[])C(i,n)},M=(i,n,s,u)=>{for(const d of m.tables[i]?.rankIndexes??[])ke(r,i,d,n,s,u)},D=(i,n,s,u)=>{const d=m.tables[i]?.searchIndexes??[];if(!(d.length===0||!re(r)))for(const f of d){if(xe(u,s,f))continue;const E=Re(i,f.name);$(r,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier(H)} = ${n}`),s&&$(r,e`INSERT INTO ${e.identifier(E)} (${e.identifier(Le)}, ${e.identifier(H)}) VALUES (${Ie(s,f)}, ${n})`)}},z=(i,n,s)=>{for(const u of m.tables[i]?.geoIndexes??[]){const d=ae(i,u.name);$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[u.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:E,lng:p}=f,h=le({lat:E,lng:p},u.precision??de);$(r,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${h}, ${E}, ${p})`)}}};return{ensureBackfilledForTable:ee,ensureBackfilledIndex:w,ensureRankBackfilled:C,ensureRankBackfilledForTable:ne,syncAggregates:q,syncCompanionsForInsert:(i,n,s)=>{D(i,n,s),z(i,n,s),q(i,void 0,s),M(i,n,void 0,s),g(i,n,s),v(i,n,"insert",s),o({indexKeys:l(i,s),key:n,op:"insert",row:s,table:i})},syncGeo:z,syncRanks:M,syncSearch:D}};export{X as O,H as T,Re as c,Pe as k,Le as l,Ne as n,Y as q,Ae as x,Ie as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const r=n=>{try{const t=JSON.stringify(n);return t===void 0?0:t.length}catch{return}};export{r as t};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{l as I,T as N,c as l}from"./ctx-db-companions-7fIu-E2H.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as S}from"./aggregateTableName-DKo6dwBP.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{migrateCdcLog as p,migrateCdcMeta as h}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as t}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as b,jsonPathSql as E,createIndexSql as T,tableColumns as u,isFtsAvailable as X,AGG_KEY as x,AGG_VALUE as B,AGG_COUNT as c,geoTableName as G}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{sortColumnName as Y,rankTableName as F}from"./RANK_TIEBREAK-D541BOFR.mjs";import{recordSchemaVersion as M}from"./SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";const D=(r,o,a)=>{for(const i of a.indexes){const n=`${o}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);t(r,T(n,o,s,i.unique??!1))}for(const[i,n]of u(a)){if(!n.unique)continue;const s=`${o}_unique_${i}`;t(r,T(s,o,E(i),!0))}},k=(r,o,a)=>{if(!(!a.searchIndexes||a.searchIndexes.length===0||!X(r))){for(const i of a.searchIndexes){const n=l(o,i.name);t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,o,a)}},j=(r,o,a)=>{if(a.geoIndexes)for(const i of a.geoIndexes){const n=G(o,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${i.name}__btree`;t(r,T(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,o,a)=>{if(a.aggregateIndexes)for(const i of a.aggregateIndexes){const n=S(o,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),t(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||t(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},y=(r,o,a)=>{if(a.rankIndexes)for(const i of a.rankIndexes){const n=F(o,i.name),s=i.sortBy.map((_,d)=>Y(d)),f=s.map(_=>e`${e.identifier(_)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,d]of s.entries()){const L=i.sortBy[_]?.direction;m.push(e`${e.identifier(d)} ${e.raw(L==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const A=`${o}__rank_${i.name}__btree`;t(r,T(A,n,e.join(m,e`, `),!1))}},ne=(r,o,a={})=>{a.schemaSnapshot!==void 0&&M(r,a.schemaSnapshot.hash,a.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(b)} TEXT NOT NULL
|
|
5
|
-
)`),D(r,i,n),k(r,i,n),j(r,i,n),q(r,i,n),y(r,i,n));a.cdc&&(p(r),h(r),R(r)),O(r),C(r)};export{ne as runShardMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as L}from"./runDrizzle-B6rnz3so.mjs";import{jsonPathSql as r}from"./AGG_COUNT-B0Pb1nQZ.mjs";const E=(s,i,a,o)=>{const d=a-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${d}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const f=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=L(s,f).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as a,rowToDocument as c,jsonPathSql as u}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{compileWhereSql as h}from"./compileWhereSql-B4rPariq.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-DnpyaLcw.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(o=>e`${o}`),e`, `)})`},p=(i,o)=>{const r=[];o&&r.push(o);const t=h(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},C=(i,o,r)=>{const t=p(r,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(a)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of d){const f=c(s),{id:l}=s;f!==void 0&&typeof l=="string"&&n.push({doc:f,id:l})}return n},D=(i,o,r,t)=>{if(t.length===0)return new Set;const d=p(r,E(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{D as selectShapeMemberIds,C as selectShapeRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=t=>typeof t=="boolean"?t?1:0:t===null||typeof t=="string"||typeof t=="number"?t:typeof t=="bigint"?t.toString():JSON.stringify(t);export{e as serializeSqlValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const b=r=>{let n="";for(let u=0;u<r.length;u+=32768)n+=String.fromCharCode(...r.subarray(u,u+32768));return btoa(n)},g=r=>{const n=atob(r),u=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)u[c]=n.codePointAt(c)??0;return u},o="$lunora.wire$";const p="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},d={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},m=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},s=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const u=typeof r;if(u==="bigint")return[o,"bigint",r.toString()];if(u==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(u!=="object")return r;if(r instanceof Date)return[o,"date",s(r.getTime(),n+1)];if(r instanceof Error){const e=r,a={};for(const l of Object.keys(e))e[l]!==void 0&&(a[l]=s(e[l],n+1));const i=[o,"error",e.name,e.message,a];return e.cause!==void 0&&i.push(s(e.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,a])=>[s(e,n+1),s(a,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>s(e,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,a=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return a==="Uint8Array"?[o,"bytes",b(i)]:[o,"bytes",b(i),a]}if(Array.isArray(r)){const e=r.map(a=>s(a,n+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!m(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=r,t={};for(const e of Object.keys(c)){const a=c[e];if(a===void 0)continue;const i=s(a,n+1);e===p?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}return t},f=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>f(t,n+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>1024||!/^-?\d+$/.test(t))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(t)}case"date":return new Date(f(r[2],n+1));case"map":return new Map(r[2].map(([t,e])=>[f(t,n+1),f(e,n+1)]));case"set":return new Set(r[2].map(t=>f(t,n+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],a=(Object.hasOwn(d,t)?d[t]:void 0)??Error,i=new a(e);i.name!==t&&Object.defineProperty(i,"name",{configurable:!0,value:t,writable:!0});const l=f(r[4],n+1);for(const y of Object.keys(l))y===p?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:l[y],writable:!0}):i[y]=l[y];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],n+1),writable:!0}),i}case"bytes":{const t=g(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const a=Object.hasOwn(w,e)?w[e]:void 0;return a?new a(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>f(t,n+1))}return r.map(t=>f(t,n+1))}const u=r,c={};for(const t of Object.keys(u)){const e=f(u[t],n+1);t===p?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[t]=e}return c};export{s as a,f as s};
|