@lunora/shard-engine 1.0.0-alpha.200 → 1.0.0-alpha.202
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 +99 -1
- package/dist/index.d.ts +99 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CfHGnLsC.mjs +14 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs → DEFAULT_MAX_RELATION_KEYS-B0nxRm8q.mjs} +1 -1
- package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-BezPdXmB.mjs +1 -0
- package/dist/packem_shared/{applyInsertDefaults-BJ4dP3OL.mjs → applyInsertDefaults-nXMzGae5.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-BToZWQxH.mjs → defineEngineContractSuite-BxYuR8CF.mjs} +1 -1
- package/dist/packem_shared/exportShardRows-BEzRTBwD.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs +0 -14
- package/dist/packem_shared/NotUniqueError-T-8lMmWk.mjs +0 -1
- package/dist/packem_shared/exportShardRows-CZh4wrvI.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BxYuR8CF.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -734,7 +734,9 @@ interface ImportRow extends ExportRow {
|
|
|
734
734
|
interface ImportShardArgs {
|
|
735
735
|
deletes?: boolean;
|
|
736
736
|
dryRun?: boolean;
|
|
737
|
+
keepIds?: ReadonlySet<string>;
|
|
737
738
|
onConflict?: ImportConflictMode;
|
|
739
|
+
replaceTables?: ReadonlyArray<string>;
|
|
738
740
|
rows: ReadonlyArray<ImportRow>;
|
|
739
741
|
startLine?: number;
|
|
740
742
|
}
|
|
@@ -743,11 +745,13 @@ interface ImportShardResult {
|
|
|
743
745
|
deleted: number;
|
|
744
746
|
errors: ImportError[];
|
|
745
747
|
inserted: Record<string, number>;
|
|
748
|
+
pruned?: Record<string, number>;
|
|
746
749
|
replaced: number;
|
|
747
750
|
}
|
|
748
751
|
declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
|
|
749
752
|
declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
|
|
750
753
|
declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
|
|
754
|
+
declare const replaceRefusal: (scope: ReadonlySet<string>, row: ExportRow) => string | undefined;
|
|
751
755
|
declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
|
|
752
756
|
interface ExportShardAdminArgs {
|
|
753
757
|
batchSize?: number;
|
|
@@ -1539,6 +1543,94 @@ declare class GlobalPollTick {
|
|
|
1539
1543
|
rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
|
|
1540
1544
|
shouldRead(table: string): boolean;
|
|
1541
1545
|
}
|
|
1546
|
+
declare const IMPORT_STAGE_TTL_MS: number;
|
|
1547
|
+
declare const IMPORT_MANIFEST_TTL_MS: number;
|
|
1548
|
+
interface StagedImportRow {
|
|
1549
|
+
doc: Record<string, unknown>;
|
|
1550
|
+
line: number;
|
|
1551
|
+
table: string;
|
|
1552
|
+
}
|
|
1553
|
+
interface ImportStepResult {
|
|
1554
|
+
deleted: Record<string, number>;
|
|
1555
|
+
inserted: Record<string, number>;
|
|
1556
|
+
warnings?: string[];
|
|
1557
|
+
}
|
|
1558
|
+
type ManifestState = "aborting" | "committed" | "committing" | "open";
|
|
1559
|
+
interface ImportManifest {
|
|
1560
|
+
batches: number;
|
|
1561
|
+
claims?: Record<string, {
|
|
1562
|
+
by: string;
|
|
1563
|
+
until: number;
|
|
1564
|
+
}>;
|
|
1565
|
+
expiresAt: number;
|
|
1566
|
+
generation: string;
|
|
1567
|
+
globals: boolean;
|
|
1568
|
+
pending: number;
|
|
1569
|
+
received: number;
|
|
1570
|
+
rejected: number;
|
|
1571
|
+
sections: string[];
|
|
1572
|
+
session: string;
|
|
1573
|
+
shards: string[];
|
|
1574
|
+
state: ManifestState;
|
|
1575
|
+
steps: Record<string, ImportStepResult>;
|
|
1576
|
+
storage: boolean;
|
|
1577
|
+
tables: string[];
|
|
1578
|
+
}
|
|
1579
|
+
declare const assertImportSessionId: (session: unknown) => string;
|
|
1580
|
+
declare const readShardImportSession: (sql: SqlExec, session: string) => undefined | {
|
|
1581
|
+
generation: string;
|
|
1582
|
+
result?: Record<string, unknown>;
|
|
1583
|
+
state: "committed" | "staging";
|
|
1584
|
+
};
|
|
1585
|
+
declare const sweepImportStaging: (sql: SqlExec, now: number) => ImportManifest[];
|
|
1586
|
+
declare const stageImportRows: (sql: SqlExec, session: string, generation: string, rows: ReadonlyArray<StagedImportRow>, now: number) => Record<string, number>;
|
|
1587
|
+
declare const touchShardImportSession: (sql: SqlExec, session: string, now: number) => void;
|
|
1588
|
+
declare const stagedImportPage: (sql: SqlExec, session: string, options: {
|
|
1589
|
+
afterSeq: number;
|
|
1590
|
+
limit: number;
|
|
1591
|
+
sections?: ReadonlyArray<string>;
|
|
1592
|
+
}) => {
|
|
1593
|
+
rows: StagedImportRow[];
|
|
1594
|
+
seq: number;
|
|
1595
|
+
};
|
|
1596
|
+
declare const stagedImportIds: (sql: SqlExec, session: string) => Set<string>;
|
|
1597
|
+
declare const markShardImportCommitted: (sql: SqlExec, session: string, generation: string, result: Record<string, unknown>, now: number) => void;
|
|
1598
|
+
declare const dropImportSession: (sql: SqlExec, session: string, generation: string) => boolean;
|
|
1599
|
+
declare const readImportManifest: (sql: SqlExec, session: string, now: number) => ImportManifest | undefined;
|
|
1600
|
+
interface ManifestTouch {
|
|
1601
|
+
begin: boolean;
|
|
1602
|
+
globals?: boolean;
|
|
1603
|
+
received?: number;
|
|
1604
|
+
rejected?: number;
|
|
1605
|
+
sections?: ReadonlyArray<string>;
|
|
1606
|
+
shards?: ReadonlyArray<string>;
|
|
1607
|
+
storage?: boolean;
|
|
1608
|
+
tables: ReadonlyArray<string>;
|
|
1609
|
+
}
|
|
1610
|
+
declare const touchImportManifest: (sql: SqlExec, session: string, touch: ManifestTouch, now: number) => {
|
|
1611
|
+
created: boolean;
|
|
1612
|
+
manifest: ImportManifest;
|
|
1613
|
+
};
|
|
1614
|
+
type ManifestChange = {
|
|
1615
|
+
batches: number;
|
|
1616
|
+
state: "committing";
|
|
1617
|
+
} | {
|
|
1618
|
+
claim: string;
|
|
1619
|
+
step: string;
|
|
1620
|
+
} | {
|
|
1621
|
+
claimant: string;
|
|
1622
|
+
step: string;
|
|
1623
|
+
stepResult: ImportStepResult;
|
|
1624
|
+
} | {
|
|
1625
|
+
release: string;
|
|
1626
|
+
step: string;
|
|
1627
|
+
} | {
|
|
1628
|
+
state: "aborting";
|
|
1629
|
+
} | {
|
|
1630
|
+
state: "committed";
|
|
1631
|
+
};
|
|
1632
|
+
declare const advanceImportManifest: (sql: SqlExec, session: string, change: ManifestChange, now: number) => ImportManifest;
|
|
1633
|
+
declare const dropImportManifest: (sql: SqlExec, session: string, now: number) => void;
|
|
1542
1634
|
declare const isInternalTableName: (name: string) => boolean;
|
|
1543
1635
|
declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
|
|
1544
1636
|
declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
|
|
@@ -1593,7 +1685,12 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1593
1685
|
readonly getTraces: "__lunora_admin__:getTraces";
|
|
1594
1686
|
readonly getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus";
|
|
1595
1687
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1688
|
+
readonly importAbort: "__lunora_admin__:importAbort";
|
|
1689
|
+
readonly importCommit: "__lunora_admin__:importCommit";
|
|
1690
|
+
readonly importManifest: "__lunora_admin__:importManifest";
|
|
1596
1691
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1692
|
+
readonly importStage: "__lunora_admin__:importStage";
|
|
1693
|
+
readonly importStagedRows: "__lunora_admin__:importStagedRows";
|
|
1597
1694
|
readonly listAdminTokens: "__lunora_admin__:listAdminTokens";
|
|
1598
1695
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1599
1696
|
readonly listReactors: "__lunora_admin__:listReactors";
|
|
@@ -1611,6 +1708,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1611
1708
|
readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
|
|
1612
1709
|
readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
|
|
1613
1710
|
readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
|
|
1711
|
+
readonly recordImportAudit: "__lunora_admin__:recordImportAudit";
|
|
1614
1712
|
readonly recordMail: "__lunora_admin__:recordMail";
|
|
1615
1713
|
readonly recordQueueMessage: "__lunora_admin__:recordQueueMessage";
|
|
1616
1714
|
readonly releaseShardRegistration: "__lunora_admin__:releaseShardRegistration";
|
|
@@ -2828,4 +2926,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2828
2926
|
ordered: OrderedAfterWrites;
|
|
2829
2927
|
restart?: boolean;
|
|
2830
2928
|
}) => Promise<VectorBackfillProgress>;
|
|
2831
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, ADMIN_WILDCARD, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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, DELTA_PLACEHOLDER_TABLE, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, deltaTableFor, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2929
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, ADMIN_WILDCARD, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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, DELTA_PLACEHOLDER_TABLE, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, IMPORT_MANIFEST_TTL_MS, IMPORT_STAGE_TTL_MS, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportManifest, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type ImportStepResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type ManifestChange, type ManifestTouch, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StagedImportRow, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, advanceImportManifest, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertImportSessionId, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, deltaTableFor, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropImportManifest, dropImportSession, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markShardImportCommitted, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readImportManifest, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readShardImportSession, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, replaceRefusal, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stageImportRows, stagedImportIds, stagedImportPage, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, sweepImportStaging, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, touchImportManifest, touchShardImportSession, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -734,7 +734,9 @@ interface ImportRow extends ExportRow {
|
|
|
734
734
|
interface ImportShardArgs {
|
|
735
735
|
deletes?: boolean;
|
|
736
736
|
dryRun?: boolean;
|
|
737
|
+
keepIds?: ReadonlySet<string>;
|
|
737
738
|
onConflict?: ImportConflictMode;
|
|
739
|
+
replaceTables?: ReadonlyArray<string>;
|
|
738
740
|
rows: ReadonlyArray<ImportRow>;
|
|
739
741
|
startLine?: number;
|
|
740
742
|
}
|
|
@@ -743,11 +745,13 @@ interface ImportShardResult {
|
|
|
743
745
|
deleted: number;
|
|
744
746
|
errors: ImportError[];
|
|
745
747
|
inserted: Record<string, number>;
|
|
748
|
+
pruned?: Record<string, number>;
|
|
746
749
|
replaced: number;
|
|
747
750
|
}
|
|
748
751
|
declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
|
|
749
752
|
declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
|
|
750
753
|
declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
|
|
754
|
+
declare const replaceRefusal: (scope: ReadonlySet<string>, row: ExportRow) => string | undefined;
|
|
751
755
|
declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
|
|
752
756
|
interface ExportShardAdminArgs {
|
|
753
757
|
batchSize?: number;
|
|
@@ -1539,6 +1543,94 @@ declare class GlobalPollTick {
|
|
|
1539
1543
|
rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
|
|
1540
1544
|
shouldRead(table: string): boolean;
|
|
1541
1545
|
}
|
|
1546
|
+
declare const IMPORT_STAGE_TTL_MS: number;
|
|
1547
|
+
declare const IMPORT_MANIFEST_TTL_MS: number;
|
|
1548
|
+
interface StagedImportRow {
|
|
1549
|
+
doc: Record<string, unknown>;
|
|
1550
|
+
line: number;
|
|
1551
|
+
table: string;
|
|
1552
|
+
}
|
|
1553
|
+
interface ImportStepResult {
|
|
1554
|
+
deleted: Record<string, number>;
|
|
1555
|
+
inserted: Record<string, number>;
|
|
1556
|
+
warnings?: string[];
|
|
1557
|
+
}
|
|
1558
|
+
type ManifestState = "aborting" | "committed" | "committing" | "open";
|
|
1559
|
+
interface ImportManifest {
|
|
1560
|
+
batches: number;
|
|
1561
|
+
claims?: Record<string, {
|
|
1562
|
+
by: string;
|
|
1563
|
+
until: number;
|
|
1564
|
+
}>;
|
|
1565
|
+
expiresAt: number;
|
|
1566
|
+
generation: string;
|
|
1567
|
+
globals: boolean;
|
|
1568
|
+
pending: number;
|
|
1569
|
+
received: number;
|
|
1570
|
+
rejected: number;
|
|
1571
|
+
sections: string[];
|
|
1572
|
+
session: string;
|
|
1573
|
+
shards: string[];
|
|
1574
|
+
state: ManifestState;
|
|
1575
|
+
steps: Record<string, ImportStepResult>;
|
|
1576
|
+
storage: boolean;
|
|
1577
|
+
tables: string[];
|
|
1578
|
+
}
|
|
1579
|
+
declare const assertImportSessionId: (session: unknown) => string;
|
|
1580
|
+
declare const readShardImportSession: (sql: SqlExec, session: string) => undefined | {
|
|
1581
|
+
generation: string;
|
|
1582
|
+
result?: Record<string, unknown>;
|
|
1583
|
+
state: "committed" | "staging";
|
|
1584
|
+
};
|
|
1585
|
+
declare const sweepImportStaging: (sql: SqlExec, now: number) => ImportManifest[];
|
|
1586
|
+
declare const stageImportRows: (sql: SqlExec, session: string, generation: string, rows: ReadonlyArray<StagedImportRow>, now: number) => Record<string, number>;
|
|
1587
|
+
declare const touchShardImportSession: (sql: SqlExec, session: string, now: number) => void;
|
|
1588
|
+
declare const stagedImportPage: (sql: SqlExec, session: string, options: {
|
|
1589
|
+
afterSeq: number;
|
|
1590
|
+
limit: number;
|
|
1591
|
+
sections?: ReadonlyArray<string>;
|
|
1592
|
+
}) => {
|
|
1593
|
+
rows: StagedImportRow[];
|
|
1594
|
+
seq: number;
|
|
1595
|
+
};
|
|
1596
|
+
declare const stagedImportIds: (sql: SqlExec, session: string) => Set<string>;
|
|
1597
|
+
declare const markShardImportCommitted: (sql: SqlExec, session: string, generation: string, result: Record<string, unknown>, now: number) => void;
|
|
1598
|
+
declare const dropImportSession: (sql: SqlExec, session: string, generation: string) => boolean;
|
|
1599
|
+
declare const readImportManifest: (sql: SqlExec, session: string, now: number) => ImportManifest | undefined;
|
|
1600
|
+
interface ManifestTouch {
|
|
1601
|
+
begin: boolean;
|
|
1602
|
+
globals?: boolean;
|
|
1603
|
+
received?: number;
|
|
1604
|
+
rejected?: number;
|
|
1605
|
+
sections?: ReadonlyArray<string>;
|
|
1606
|
+
shards?: ReadonlyArray<string>;
|
|
1607
|
+
storage?: boolean;
|
|
1608
|
+
tables: ReadonlyArray<string>;
|
|
1609
|
+
}
|
|
1610
|
+
declare const touchImportManifest: (sql: SqlExec, session: string, touch: ManifestTouch, now: number) => {
|
|
1611
|
+
created: boolean;
|
|
1612
|
+
manifest: ImportManifest;
|
|
1613
|
+
};
|
|
1614
|
+
type ManifestChange = {
|
|
1615
|
+
batches: number;
|
|
1616
|
+
state: "committing";
|
|
1617
|
+
} | {
|
|
1618
|
+
claim: string;
|
|
1619
|
+
step: string;
|
|
1620
|
+
} | {
|
|
1621
|
+
claimant: string;
|
|
1622
|
+
step: string;
|
|
1623
|
+
stepResult: ImportStepResult;
|
|
1624
|
+
} | {
|
|
1625
|
+
release: string;
|
|
1626
|
+
step: string;
|
|
1627
|
+
} | {
|
|
1628
|
+
state: "aborting";
|
|
1629
|
+
} | {
|
|
1630
|
+
state: "committed";
|
|
1631
|
+
};
|
|
1632
|
+
declare const advanceImportManifest: (sql: SqlExec, session: string, change: ManifestChange, now: number) => ImportManifest;
|
|
1633
|
+
declare const dropImportManifest: (sql: SqlExec, session: string, now: number) => void;
|
|
1542
1634
|
declare const isInternalTableName: (name: string) => boolean;
|
|
1543
1635
|
declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
|
|
1544
1636
|
declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
|
|
@@ -1593,7 +1685,12 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1593
1685
|
readonly getTraces: "__lunora_admin__:getTraces";
|
|
1594
1686
|
readonly getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus";
|
|
1595
1687
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1688
|
+
readonly importAbort: "__lunora_admin__:importAbort";
|
|
1689
|
+
readonly importCommit: "__lunora_admin__:importCommit";
|
|
1690
|
+
readonly importManifest: "__lunora_admin__:importManifest";
|
|
1596
1691
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1692
|
+
readonly importStage: "__lunora_admin__:importStage";
|
|
1693
|
+
readonly importStagedRows: "__lunora_admin__:importStagedRows";
|
|
1597
1694
|
readonly listAdminTokens: "__lunora_admin__:listAdminTokens";
|
|
1598
1695
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1599
1696
|
readonly listReactors: "__lunora_admin__:listReactors";
|
|
@@ -1611,6 +1708,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1611
1708
|
readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
|
|
1612
1709
|
readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
|
|
1613
1710
|
readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
|
|
1711
|
+
readonly recordImportAudit: "__lunora_admin__:recordImportAudit";
|
|
1614
1712
|
readonly recordMail: "__lunora_admin__:recordMail";
|
|
1615
1713
|
readonly recordQueueMessage: "__lunora_admin__:recordQueueMessage";
|
|
1616
1714
|
readonly releaseShardRegistration: "__lunora_admin__:releaseShardRegistration";
|
|
@@ -2828,4 +2926,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2828
2926
|
ordered: OrderedAfterWrites;
|
|
2829
2927
|
restart?: boolean;
|
|
2830
2928
|
}) => Promise<VectorBackfillProgress>;
|
|
2831
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, ADMIN_WILDCARD, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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, DELTA_PLACEHOLDER_TABLE, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, deltaTableFor, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2929
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, ADMIN_WILDCARD, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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, DELTA_PLACEHOLDER_TABLE, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, IMPORT_MANIFEST_TTL_MS, IMPORT_STAGE_TTL_MS, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportManifest, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type ImportStepResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type ManifestChange, type ManifestTouch, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StagedImportRow, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, advanceImportManifest, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertImportSessionId, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, deltaTableFor, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropImportManifest, dropImportSession, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markShardImportCommitted, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readImportManifest, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readShardImportSession, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, replaceRefusal, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stageImportRows, stagedImportIds, stagedImportPage, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, sweepImportStaging, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, touchImportManifest, touchShardImportSession, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as R,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as H,stripReservedPatchFields as X}from"./packem_shared/NotUniqueError-T-8lMmWk.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Re,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-DO92CQek.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as He,deleteGlobalShapeSnapshotsForConnection as Xe,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Ar,recordScheduleOutbox as Rr,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Hr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ao,unionAll as Ro}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Ho}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Aa,DEFAULT_FANOUT_TOPIC_LIMIT as Ra,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Ha,recordCapturedMail as Xa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as At,readQueueMessageById as Rt,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as Ht,UNVOUCHABLE_DEP as Xt,createReadFootprint as Vt,markUnvouchableReads as zt}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as Yt,indexKeysForRow as jt,keysTouchRanges as Jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as $t,whereFilter as ei,whereOfFilter as ri}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as ai,RELATED_DEPTH_DECAY as ti,RELATED_MAX_DEPTH as ii,RELATED_MAX_LIMIT as si,deriveRelationEdges as ni,findRelated as li}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as ci,assertFlatPredicate as mi,assertShapeShardable as pi,composeReadPredicate as ui,containsRelationPredicate as Si,findManyPage as fi,isRelationPredicate as xi,resolveRelationPredicates as Ei}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs";import{describeRelationWrites as Ti}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ri,applyOnDelete as Ci,distinctValues as gi,fanOutScalarCounts as _i,relationHooks as Ii,resolveWith as bi,runRowValidators as Li}from"./packem_shared/applyInsertDefaults-BJ4dP3OL.mjs";import{D as Oi,c as Pi,n as yi,r as Mi,s as Fi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Ni,OwnerRelay as Bi,RelayMember as Ui,createRelayLink as Gi}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as qi,gateReplicaDispatch as vi,handleReplicaControl as Ki}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Hi,countLegacyRows as Xi,reprojectableFields as Vi,reprojectionTables as zi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as Yi,RlsRequiredError as ji,guardWriter as Ji}from"./packem_shared/RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as $i,readSchemaHistory as es,readSchemaVersion as rs,recordSchemaVersion as os}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as ts}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ss,isDevEnvironment as ns,readDeployInfo as ls}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as cs}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ps,createShapeDiffCache as us,globalShapeReadKey as Ss}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as xs,diffGlobalMembership as Es,encodeRowsPatch as hs,projectColumns as Ts}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Rs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as gs}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Is}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ls,assertReadonly as Ds,lintReadonlySql as Os,runReadonlySql as Ps}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Ms,bigintSqlKey as Fs,decodeBigintSqlKey as ks,decodeFloat64SqlKey as Ns,float64SqlKey as Bs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as Gs,awaitWsDrain as ws,deltaTableFor as qs,subscriptionFrames as vs,subscriptionListDeltas as Ks,trySendFrame as Ws}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as Xs,recordChangedKeys as Vs,writeTouchesMemo as zs}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Ys}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as Js}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as $s,TransactionHeadroomTracker as en}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as on,runTriggers as an}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as sn,nextTtlExpiry as nn,selectExpiredIds as ln}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as cn,backfillVectorIndexes as mn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs";import{c as un,s as Sn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as xn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as hn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as An,siblingSecretOf as Rn,signSiblingBody as Cn,verifySiblingBody as gn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as In,reprojectionMigrationId as bn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Dn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Pn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Mn}from"./packem_shared/runShardMigrations-Bc7PsQhM.mjs";import{stableStringify as kn,stableWireKey as Nn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Aa as ADMIN_FUNCTION_PREFIX,hn as ADMIN_TOKEN_TABLE,Ht as ADMIN_WILDCARD,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,Ms as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,Js as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Ra as DEFAULT_FANOUT_TOPIC_LIMIT,ci as DEFAULT_MAX_RELATION_KEYS,Ni as DEFAULT_MAX_RELAYS,Oi as DEFAULT_PROMOTION_THRESHOLDS,$s as DEFAULT_TRANSACTION_LIMITS,Gs as DELTA_PLACEHOLDER_TABLE,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,Ls as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,Bi as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,ai as RELATED_DEFAULT_LIMIT,ti as RELATED_DEPTH_DECAY,ii as RELATED_MAX_DEPTH,si as RELATED_MAX_LIMIT,xn as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,An as RELAY_SIGNATURE_HEADER,In as REPROJECTION_MIGRATION_PREFIX,Yi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Ui as RelayMember,ji as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,$i as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ps as ShapeDiffCache,Rs as ShardRunner,en as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,cn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,R as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ri as applyInsertDefaults,Ci as applyOnDelete,it as applySelect,Re as archiveCdcSegment,rt as armRestore,mi as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,Ds as assertReadonly,pi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,ws as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,mn as backfillVectorIndexes,Fs as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Yt as buildIndexRange,xs as buildPokeFrames,Hi as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,ss as buildSettings,cs as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Pi as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,un as compileWhereSql,ui as composeReadPredicate,sr as computeRankPage,Si as containsRelationPredicate,Xi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Vt as createReadFootprint,Gi as createRelayLink,qi as createReplicaLink,us as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Ys as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,ks as decodeBigintSqlKey,lt as decodeCursor,Ns as decodeFloat64SqlKey,cr as deferScheduleOutbox,He as deleteGlobalShapeSnapshot,Xe as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,qs as deltaTableFor,Qr as depKey,ni as deriveRelationEdges,Ti as describeRelationWrites,qo as diffExternalSource,Es as diffGlobalMembership,gi as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,hs as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,_i as fanOutScalarCounts,fi as findManyPage,li as findRelated,Oa as findStorageReferences,bo as finishStreamRun,Bs as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,vi as gateReplicaDispatch,so as geoTableName,Ss as globalShapeReadKey,na as groupUnmappedRows,Ji as guardWriter,Ki as handleReplicaControl,ur as hasScheduleOutboxEntry,on as hasTrigger,Sa as haversineMeters,a as importShardRows,jt as indexKeysForRow,ns as isDevEnvironment,no as isFtsAvailable,Dn as isInternalTableName,At as isLossyBody,ar as isMemoryTable,$t as isPushableWhere,xi as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,sn as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,Jt as keysTouchRanges,Ko as liftSourceId,Os as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,zt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,Xs as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,yi as nextPromotionState,nn as nextTtlExpiry,h as normalizeCountArgument,H as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Ho as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,Ts as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,Pn as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Ha as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ls as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,Rt as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Ar as readScheduleOutboxState,es as readSchemaHistory,rs as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Xa as recordCapturedMail,Vs as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Rr as recordScheduleOutbox,os as recordSchemaVersion,Na as recordShapeProbePass,Ii as relationHooks,Mi as relayCountFor,To as renderSql,Vi as reprojectableFields,bn as reprojectionMigrationId,zi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,Ei as resolveRelationPredicates,bi as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Hr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Ps as runReadonlySql,Li as runRowValidators,Mn as runShardMigrations,Is as runSocketPool,Zr as runSql,an as runTriggers,ln as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,ts as serializeSqlValue,Sn as serverInList,Fi as shapeRoutingKey,Rn as siblingSecretOf,Cn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ao as sqliteInList,kn as stableStringify,Nn as stableWireKey,X as stripReservedPatchFields,gs as stubByName,vs as subscriptionFrames,Ks as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,Ws as trySendFrame,Ro as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,gn as verifySiblingBody,ei as whereFilter,ri as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,zs as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-BezPdXmB.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-DO92CQek.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-CfHGnLsC.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-B0nxRm8q.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-nXMzGae5.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-Bc7PsQhM.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{decodeWire as G,WIRE_TAG as F,needsWireEncoding as J,encodeWire as X}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as $}from"./isInternalTableName-BoljO2tP.mjs";import{n as y,o as V}from"./do-sql-105TONaE.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as Y,sqliteInList as Z}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Fe="__lunora_admin__:",xe="__lunora_relation__:",qe="__lunora_flags__:",Ue={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiCronExpression:"__lunora_admin__:aiCronExpression",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiNameQuery:"__lunora_admin__:aiNameQuery",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createAdminToken:"__lunora_admin__:createAdminToken",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",dropOutboxEntry:"__lunora_admin__:dropOutboxEntry",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",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",getScheduleOutbox:"__lunora_admin__:getScheduleOutbox",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",importAbort:"__lunora_admin__:importAbort",importCommit:"__lunora_admin__:importCommit",importManifest:"__lunora_admin__:importManifest",importShard:"__lunora_admin__:importShard",importStage:"__lunora_admin__:importStage",importStagedRows:"__lunora_admin__:importStagedRows",listAdminTokens:"__lunora_admin__:listAdminTokens",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordImportAudit:"__lunora_admin__:recordImportAudit",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",retryOutboxEntry:"__lunora_admin__:retryOutboxEntry",resolveIssue:"__lunora_admin__:resolveIssue",revokeAdminToken:"__lunora_admin__:revokeAdminToken",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",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",verifyAdminToken:"__lunora_admin__:verifyAdminToken",writeRow:"__lunora_admin__:writeRow"},ee=50,N=500,te=30,ne=200,c="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},re=e=>{const{[y]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...n}:{...n,...G(t)}},oe=(e,t)=>{if(!e.includes(c))return{columns:e,rows:t};const n=[];for(const i of t){const s=i[c],_=typeof s=="string"?x(s):void 0;if(_===void 0)return{columns:e,rows:t};const l=Object.fromEntries(Object.entries(i).filter(([u])=>u!==c));n.push({...l,...re(_)})}const r=e.filter(i=>i!==c),o=[],a=new Set(r);for(const i of n)for(const s of Object.keys(i))a.has(s)||(a.add(s),o.push(s));return{columns:[...r,...o],rows:n}},g=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,O=(e,t,n)=>Math.min(Math.max(e,t),n),q=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},He=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)$(r)||n.push({name:r,rowCount:q(e,d(r))});return n},U=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if($(t)||!U(e,t))throw new m("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},j=100,M=(e,t)=>{if(t>j)throw new m("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(j)} — remove some filters or narrow the search`)},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",ae=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?H(e.value)==="":ae.has(e.operator)&&e.value==="",P=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new m("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},T=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(c);if(!(!r&&!o)){if(r){if(n.length>0)throw new m("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:d(e),params:[]}}return{expression:`json_extract(${d(c)}, ?)`,params:[P(e,n)]}}},ie=/^-?\d+$/u,R=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ie.test(r))throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},_e=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,le=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new m("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},ce=(e,t,n)=>{if(t.includes(e.column))throw new m("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(c))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new m("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=le(e.value),a=P(e.column,r),i=d(c),s=`SELECT 1 FROM json_each(${i}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${a}[0]`,a,...o.params,`${a}[1]`,`${a}[2]`,...o.params],sql:`CASE WHEN json_extract(${i}, ?) IS NOT '${F}' THEN EXISTS (${s}) WHEN json_extract(${i}, ?) IS 'arr' THEN EXISTS (${s}) ELSE 0 END`}},de=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return J(e)?JSON.stringify(X(e)):void 0}catch(t){throw new m("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",me=(e,t,n)=>{const r=de(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new m("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let a="'integer', 'real'";return typeof e.value=="string"?a="'text'":typeof e.value=="boolean"&&(a="'true', 'false'"),{params:[...n,...n,R(e,void 0)],sql:`(json_type(${d(c)}, ?) IN (${a}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const a=`json_type(${d(c)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,i=R(e,void 0);return o==="eq"?{params:[...n,...n,i],sql:`(${a})`}:{params:[...n,...n,...n,i],sql:`(${t} IS NOT NULL AND NOT (${a}))`}}},fe=/["\\\u0000-\u001F]/u,W=e=>fe.test(e)?"":e,B=(e,t,n,r)=>{const o=`'${F}'`,a=f=>`(instr(${f}, ${o}) > 0 OR instr(${f}, ${String.raw`'\u'`}) > 0)`,i=a(e),s=r.prefilter===void 0?[]:[r.prefilter],_=r.root===void 0?"":", ?",l=r.root===void 0?[]:[r.root],u=[...r.prefilter===void 0?[]:[g(e)],`EXISTS (SELECT 1 FROM json_tree(${e}${_}) AS j WHERE ${n.sql})`],p=[a(`t.${e}`),...r.prefilter===void 0?[]:[g(`t.${e}`)]],E=`(${u.join(" AND ")})`;return{params:[...s,...l,...n.params,...s,...l,...n.params],sql:`CASE WHEN ${i} THEN ${e} COLLATE BINARY IN (WITH RECURSIVE
|
|
2
|
+
__wf_framed AS MATERIALIZED (SELECT DISTINCT t.${e} COLLATE BINARY AS doc FROM ${t} AS t WHERE ${p.join(" AND ")}),
|
|
3
|
+
__wf_docs AS MATERIALIZED (SELECT doc, row_number() OVER () AS n FROM __wf_framed),
|
|
4
|
+
__wf_raw AS (SELECT d.n, j.id, j.parent, j.key, j.type, j.atom, j.value, j.fullkey FROM __wf_docs AS d, json_tree(d.doc${_}) AS j),
|
|
5
|
+
__wf_flags AS MATERIALIZED (SELECT n, parent AS id,
|
|
6
|
+
max(CASE WHEN typeof(key) = 'integer' AND key = 0 AND type = 'text' AND atom = ${o} THEN 1 ELSE 0 END) AS tagged,
|
|
7
|
+
count(CASE WHEN typeof(key) = 'integer' AND ((key = 0 AND atom = ${o}) OR (key = 1 AND atom = 'arr')) THEN 1 END) = 2 AS shaped
|
|
8
|
+
FROM __wf_raw WHERE parent IS NOT NULL GROUP BY n, parent),
|
|
9
|
+
__wf_tree AS MATERIALIZED (SELECT __wf_raw.*, coalesce(f.tagged, 0) AS tagged_parent, coalesce(f.shaped, 0) AS shaped_parent FROM __wf_raw LEFT JOIN __wf_flags AS f ON f.n = __wf_raw.n AND f.id = __wf_raw.parent),
|
|
10
|
+
__wf_steps AS MATERIALIZED (SELECT n, id, parent FROM __wf_tree WHERE typeof(key) = 'integer' AND key = 2 AND shaped_parent),
|
|
11
|
+
__wf_runs(n, id, k) AS MATERIALIZED (SELECT s.n, s.id, 1 FROM __wf_steps AS s LEFT JOIN __wf_steps AS p ON p.n = s.n AND p.id = s.parent WHERE p.id IS NULL UNION ALL SELECT c.n, c.id, r.k + 1 FROM __wf_runs AS r JOIN __wf_steps AS c ON c.n = r.n AND c.parent = r.id),
|
|
12
|
+
__wf_excluded AS MATERIALIZED (SELECT j.n, j.id FROM __wf_tree AS j LEFT JOIN __wf_runs AS p ON p.n = j.n AND p.id = j.parent WHERE typeof(j.key) = 'integer' AND j.key IN (0, 1) AND j.tagged_parent AND coalesce(p.k, 0) % 2 = 0),
|
|
13
|
+
__wf_framedMatches AS (SELECT d.doc FROM __wf_docs AS d JOIN (SELECT DISTINCT j.n FROM __wf_tree AS j LEFT JOIN __wf_excluded AS e ON e.n = j.n AND e.id = j.id WHERE ${n.sql} AND e.id IS NULL) AS m ON m.n = d.n)
|
|
14
|
+
SELECT doc FROM __wf_framedMatches) ELSE ${E} END`}},pe=(e,t,n,r)=>{const o={params:[r],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")}`},a=B(t,e,o,{prefilter:W(r),root:n});return{params:[n,n,r,n,n,r,n,...a.params],sql:`CASE WHEN json_type(${t}, ?) IN ('text', 'integer', 'real') THEN ${g(`json_extract(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('true', 'false') THEN ${g(`json_type(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('array', 'object') THEN ${a.sql} ELSE 0 END`}},Ee=(e,{expression:t,kind:n,pathParameters:r,physical:o,table:a})=>{const i=e.path??[];if(n==="bigint")throw new m("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const s=H(e.value);return i.length===0&&o?{params:[s],sql:g(t)}:i.length===0?pe(a,d(c),r[0],s):{params:[...r,...r,s],sql:`(json_type(${d(c)}, ?) IN ('text', 'integer', 'real') AND ${g(t)})`}},Se=(e,t,n,r)=>{if(e.operator==="has")return ce(e,t,n);const o=e.path??[],a=T(e.column,t,o);if(a===void 0||se(e))return;const{expression:i,params:s}=a,_=t.includes(e.column)||o.length>0?void 0:n?.[e.column];if(e.operator==="contains")return Ee(e,{expression:i,kind:_,pathParameters:s,physical:t.includes(e.column),table:r});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:s,sql:`${i} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(o.length>0){const l=me(e,i,s);if(l!==void 0)return l}return{params:[...s,R(e,_)],sql:`${i} ${I[e.operator]} ?`}},ge=new Set(["date","timestamp"]),Ae=[`$.${y}`,`$."${y}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Ne=(e,t)=>{const n={params:[t],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${Ae}`};return B(d(c),e,n,{prefilter:W(t)})},Te=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,he=e=>{const t=Te.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const a=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(a).getUTCDate()!==o)return;let i;return o!==void 0?i=Date.UTC(n,(r??1)-1,o+1):r===void 0?i=Date.UTC(n+1,0,1):i=Date.UTC(n,r,1),{from:a,to:i}},ye=(e,t,n)=>t.map(r=>r===c?Ne(e,n):{params:[n],sql:g(d(r))}),be=(e,t,n)=>{const r=e.map(a=>({params:[n.from,n.to],sql:`(${d(a)} >= ? AND ${d(a)} < ?)`})),o=Object.keys(t??{}).filter(a=>!e.includes(a)&&ge.has(t?.[a]??""));return o.length>0&&e.includes(c)&&r.push({params:[JSON.stringify(o),n.from,n.to],sql:`EXISTS (SELECT 1 FROM json_each(${d(c)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`}),r},v=(e,t,n,r,o)=>{const a=[],i=[];if(n!==""&&t.length>0){const s=ye(e,t,n),_=he(n);_!==void 0&&s.push(...be(t,o,_)),a.push(`(${s.map(l=>l.sql).join(" OR ")})`),i.push(...s.flatMap(l=>l.params))}for(const s of r??[]){const _=Se(s,t,o,e);_!==void 0&&(a.push(`(${_.sql})`),i.push(..._.params))}return a.length===0?void 0:{parameters:i,where:a.join(" AND ")}},we=(e,t)=>{if(e===void 0)return;const n=T(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Pe=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??ee),1,N),o=Math.max(0,Math.trunc(t.offset??0)),a=d(n),i=b(e,a),s=t.search?.trim()??"",_=h=>{if(t.refs===void 0)return h;const w={};for(const D of h.columns){const k=t.refs[D];k!==void 0&&(w[D]=k)}return Object.keys(w).length>0?{...h,refs:w}:h},l=v(a,i,s,t.filters,t.columnKinds),u=we(t.orderBy,i),p=l===void 0?"":` WHERE ${l.where}`,E=u===void 0?"":` ORDER BY ${u.sql}`,f=l?.parameters??[],A=u?.params??[];M(n,f.length+A.length+2);let S;t.skipCount||(S=l===void 0?q(e,a):Number(e.exec(`SELECT COUNT(*) AS c FROM ${a}${p}`,...f).one().c));const Q=e.exec(`SELECT * FROM ${a}${p}${E} LIMIT ? OFFSET ?`,...f,...A,r,o).toArray();return _({...oe(i,Q),sqlColumns:i,total:S})},We=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??N),1,N),o=d(n),a=b(e,o),i=t.search?.trim()??"";for(const S of t.filters??[])if(T(S.column,a,S.path??[])===void 0)throw new m("BAD_REQUEST",`unknown column: ${S.column}`);const s=v(o,a,i,t.filters,t.columnKinds);if(s===void 0&&(t.filters?.length??0)>0)throw new m("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],l=[];s!==void 0&&(_.push(s.where),l.push(...s.parameters)),t.after!==void 0&&(_.push("id > ?"),l.push(t.after));const u=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";M(n,l.length+1);const E=e.exec(`SELECT id FROM ${o}${u}${p} LIMIT ?`,...l,r+1).toArray(),f=E.length>r,A=E.slice(0,r).map(S=>S.id);return{hasMore:f,ids:A}},Ie=(e,t,n,r)=>{const o=new Set(n.filter(i=>i!==c));if(!n.includes(c))return o;for(const i of Object.keys(r??{}))o.add(i);const a=e.exec(`SELECT ${d(c)} AS doc FROM ${t} LIMIT ?`,N).toArray();for(const{doc:i}of a){const s=typeof i=="string"?x(i):void 0;if(s!==void 0)for(const _ of Object.keys(s))o.add(_)}return o},Be=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),a=b(e,o);if(!Ie(e,o,a,t.columnKinds).has(n))throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=T(n,a);if(i===void 0)throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=O(Math.trunc(t.limit??te),1,ne),_=t.search?.trim()??"",l=v(o,a,_,t.filters,t.columnKinds),u=l===void 0?"":` WHERE ${l.where}`,p=l?.parameters??[];M(r,i.params.length*2+p.length+1);const E=e.exec(`SELECT ${i.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${i.expression} ORDER BY count DESC LIMIT ?`,...i.params,...p,...i.params,s+1).toArray(),f=E.length>s,A=a.includes(n)?void 0:t.columnKinds?.[n];return{truncated:f,values:E.slice(0,s).map(S=>({count:Number(S.count),value:_e(S.value,A)}))}},Qe=(e,t,n)=>{const r={},o=n.slice(0,N);for(const a of o)r[a]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[a,i]of Object.entries(t)){if($(a)||!U(e,a))continue;const s=d(a),_=b(e,s);for(const l of i){const u=T(l,_);if(u===void 0)continue;const p=Y("sqlite",Z(K.raw(u.expression),o,!1)),E=e.exec(`SELECT id, ${u.expression} AS ref FROM ${s} WHERE ${p.sql}`,...u.params,...u.params,...p.params).toArray();for(const f of E)r[f.ref]?.push({column:l,id:f.id,table:a})}}return{references:r,storageColumns:t}},Ge=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,a)=>{const i=Object.values(o.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:o.admin===!0,id:a,subscriptions:i}}),r=n.reduce((o,a)=>o+a.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},Re=20,Je=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ke=()=>({drains:0,pairsSkipped:0}),Ve=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ye=(e,t,n)=>({run:e.run+t,served:e.served+n}),Ze=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),ze=(e,t=Re)=>{const n=new Map,r=new Map,o=e.filter(s=>s.authenticated!==!1);for(const s of o){for(const _ of Object.values(s.shapes??{})){const l=_.name??"(unknown shape)";n.set(l,(n.get(l)??0)+1)}for(const _ of s.whispers??[])r.set(_,(r.get(_)??0)+1)}const a=[...[...n].map(([s,_])=>({kind:"shape",subscribers:_,topic:s})),...[...r].map(([s,_])=>({kind:"whisper",subscribers:_,topic:s}))];return a.sort((s,_)=>_.subscribers-s.subscribers||s.topic.localeCompare(_.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:o.length}};export{Ue as ADMIN_FUNCTIONS,Fe as ADMIN_FUNCTION_PREFIX,Re as DEFAULT_FANOUT_TOPIC_LIMIT,qe as FLAGS_FUNCTION_PREFIX,N as MAX_PAGE_SIZE,xe as RELATION_FUNCTION_PREFIX,Je as createFanoutCounters,Ke as createGlobalPollCounters,Xe as createShapeProbeCounters,he as datePrefixRange,Be as facetColumn,Qe as findStorageReferences,$ as isInternalTableName,se as isVacuousFilterClause,He as listTables,Pe as readTablePage,Ze as recordFanoutPass,Ve as recordGlobalPollPass,Ye as recordShapeProbePass,We as selectMatchingIds,ze as summarizeFanoutTopics,Ge as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{i as j,R as k}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as N}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as P,uniqueIndexFields as _,equalityPinnedFields as D,buildSeekWhere as K,decodeCursor as E,buildSeekBeforeWhere as B,softDeleteScope as I,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as T}from"./applyInsertDefaults-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{i as j,R as k}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as N}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as P,uniqueIndexFields as _,equalityPinnedFields as D,buildSeekWhere as K,decodeCursor as E,buildSeekBeforeWhere as B,softDeleteScope as I,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as T}from"./applyInsertDefaults-nXMzGae5.mjs";import{RELATION_EXISTS_KEY as W}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const $={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}},S=e=>k.has(e)?e:void 0,p=e=>{const t=S(e),r=t===void 0?void 0:$[t];if(!r)throw new l("INTERNAL",`unknown relation operator "${e}"`);return r},F=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},q=5e3,m=Symbol("relation-key-overflow"),y=e=>Array.isArray(e)?e.map(t=>t??{}):[],C=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>j(e),f=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?y(s).some(i=>f(i,t,r)):o==="NOT"?f(s??{},t,r):!!n[o]&&b(s)})},de=(e,t,r,n)=>{if(e&&f(e,t,r))throw new l("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},H=async(e,t,r,n)=>{const o=await u(t,e.table,n),{page:s}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return T(s,r)},z=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},Y=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},Q=async(e,t,r,n,o)=>{const s=await H(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?m:z(e,s.length,n)},v=async(e,t,r,n)=>{const o=await u(t,e.table,n),s=n.maxRelationKeys+1,i=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:s,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>s)throw new l("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(s)}; the fetcher did not honour the page limit`);for(const c of T(d.page,r))i.add(c);if(i.size>n.maxRelationKeys&&Y(e,i.size,n),d.isDone)return[...i];if(typeof d.continueCursor!="string")throw new l("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new l("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},X=async(e,t,r,n,o)=>{const s=p(e),{clause:i,project:a}=F(t),d=await Q(t,s.negateChild?{NOT:r}:r,a,n,o);return d===m?m:s.negated?s.nullDisjunct?{OR:[{[i]:{notIn:d}},{[i]:{isNull:!0}}]}:{[i]:{notIn:d}}:{[i]:{in:d}}},x=async(e,t,r,n)=>{const o=p(e),{from:s,table:i,to:a}=t.through,d=await v(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await v({table:i},{[a]:{in:d}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},O=async(e,t,r,n,o)=>{const s=p(e),i=o.relationBaseWhere?.(t.table),a=s.negateChild?{NOT:r}:r,L={childWhere:await u(i?{AND:[i,a]}:a,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[W]:L}},U=(e,t,r)=>{const n=S(e),o=n===void 0?void 0:$[n];if(o&&o.kind!==r.kind)throw new l("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},V=async(e,t,r,n,o)=>{const s=[];for(const i of Object.keys(r)){U(i,e,t);const a=r[i]??{};if(t.through!==void 0){s.push(await x(i,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){s.push(await O(i,t,a,n,o));continue}const c=await X(i,t,a,o,d);c===m?s.push(await O(i,t,a,n,o)):s.push(c)}return C(s)},J=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const i of y(t))s.push(await u(i,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await u(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&b(t)?V(e,o,t,r,n):{[e]:t}},u=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await J(o,e[o],t,r));return C(n)},G=async(e,t)=>!e||!f(e,t.schema,t.tableName)?e:u(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??q,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),A=100,h=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,s)=>o+h(s),0):r==="NOT"?t+=h(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},ce=async(e,t,r)=>{const n=P(t.orderBy,e.shape,{pinned:D(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?K(n,E(t.cursor)):void 0,s=typeof t.endCursor=="string"?B(n,E(t.endCursor)):void 0;if(s!==void 0&&h(o)+h(s)>A)throw new l("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(h(o)+h(s))} cursor parameters, and a statement takes at most ${String(A)} — order by fewer fields`);let i=w(t.baseWhere,t.where);i=w(i,I(e.softDeleteMode,t.includeDeleted)),i=await G(i,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,s])d&&(i=i?{AND:[i,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:i}},le=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:s}=t,i=n!==void 0&&e.length>n,a=i?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:i&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,s):null,...i?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:i&&d&&o!==!0?R(d,s):null,isDone:!i,page:a}},g=(e,t,r)=>{for(const n of e){const o=M(n,t,r);if(o)return o}},Z=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(y(t),r,n);if(e==="NOT")return g([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!b(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],i=s.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(i!==void 0)return{kind:"shard",relation:e,target:i};const a=s.find(d=>N(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:g(Object.values(t),r,o.table)},M=(e,t,r)=>{for(const n of Object.keys(e)){const o=Z(n,e[n],t,r);if(o)return o}},ee=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!f(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},he=(e,t,r)=>{if(N(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=M(e,t,r);if(!n){ee(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{q as DEFAULT_MAX_RELATION_KEYS,de as assertFlatPredicate,he as assertShapeShardable,ce as composeReadPredicate,f as containsRelationPredicate,le as findManyPage,b as isRelationPredicate,G as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{encodeWire as L,decodeWire as $}from"@lunora/wire";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const T="__lunora_import_stage__",d="__lunora_import_session__",c="__lunora_import_manifest__",N=1440*60*1e3,f=3600*1e3,A=600*1e3,P=/^[\w-]{1,64}$/u,D=new Set(["committed","staging"]),C=new Set(["aborting","committed","committing","open"]),a=(t,e)=>new p(t,e,{status:409}),G=t=>{if(typeof t!="string"||!P.test(t))throw new p("BAD_REQUEST","an import session id is 1-64 characters of [A-Za-z0-9_-]",{status:400});return t},I=t=>{n(t,`CREATE TABLE IF NOT EXISTS "${T}" (seq INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT NOT NULL, tbl TEXT NOT NULL, id TEXT, line INTEGER NOT NULL, doc TEXT NOT NULL)`),n(t,`CREATE INDEX IF NOT EXISTS "${T}_by_session" ON "${T}" (session, seq)`),n(t,`CREATE TABLE IF NOT EXISTS "${d}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, generation TEXT NOT NULL, expires_at INTEGER NOT NULL, result TEXT)`),n(t,`CREATE TABLE IF NOT EXISTS "${c}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, expires_at INTEGER NOT NULL, manifest TEXT NOT NULL)`)},O=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0,m=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),M=t=>{let e;try{e=JSON.parse(t)}catch{return}const s=e;if(!(s===null||typeof s!="object"||typeof s.session!="string"||typeof s.generation!="string"||typeof s.state!="string"||!C.has(s.state)||typeof s.expiresAt!="number"||!O(s.batches)||!O(s.pending)||!O(s.rejected)||!O(s.received)||typeof s.globals!="boolean"||typeof s.storage!="boolean"||!m(s.sections)||!m(s.shards)||!m(s.tables)||typeof s.steps!="object"||s.steps===null))return s},_=(t,e)=>{I(t);const s=n(t,`SELECT state, generation, result FROM "${d}" WHERE session = ?`,e).toArray()[0];if(s===void 0)return;if(!D.has(s.state))throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has an unreadable state on this shard`);const o=s.state;return s.result===null?{generation:s.generation,state:o}:{generation:s.generation,result:JSON.parse(s.result),state:o}},g=(t,e)=>{n(t,`DELETE FROM "${T}" WHERE session = ?`,e),n(t,`DELETE FROM "${d}" WHERE session = ?`,e)},B=(t,e)=>{I(t),n(t,`DELETE FROM "${T}" WHERE session IN (SELECT session FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed'))`,e),n(t,`DELETE FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed')`,e);const s=[];for(const o of n(t,`SELECT session, manifest FROM "${c}" WHERE expires_at < ?`,e)){const i=M(o.manifest);i===void 0||i.state==="committing"||(i.state!=="committed"&&_(t,o.session)?.generation===i.generation&&g(t,o.session),n(t,`DELETE FROM "${c}" WHERE session = ?`,o.session),s.push(i))}return s},h=(t,e,s)=>{if(t!==void 0&&t.generation!==s)throw a("IMPORT_SESSION_STALE",`import session "${e}" on this shard belongs to an earlier session of the same id`)},J=(t,e,s,o,i)=>{const r=_(t,e);if(h(r,e,s),r?.state==="committed")throw a("IMPORT_SESSION_COMMITTED",`import session "${e}" is already committed`);n(t,`INSERT INTO "${d}" (session, state, generation, expires_at) VALUES (?, 'staging', ?, ?) ON CONFLICT (session) DO UPDATE SET expires_at = excluded.expires_at`,e,s,i+N);const E={};for(const S of o){const l=S.doc._id;n(t,`INSERT INTO "${T}" (session, tbl, id, line, doc) VALUES (?, ?, ?, ?, ?)`,e,S.table,typeof l=="string"?l:null,S.line,JSON.stringify(L(S.doc))),E[S.table]=(E[S.table]??0)+1}return E},v=(t,e,s)=>{n(t,`UPDATE "${d}" SET expires_at = ? WHERE session = ?`,s+N,e)},Y=(t,e,s)=>{I(t);let o="substr(tbl, 1, 1) <> '$'";s.sections!==void 0&&(o=s.sections.length===0?"0":`tbl IN (${s.sections.map(()=>"?").join(", ")})`);const i=n(t,`SELECT seq, tbl, line, doc FROM "${T}" WHERE session = ? AND seq > ? AND ${o} ORDER BY seq LIMIT ?`,e,s.afterSeq,...s.sections??[],s.limit).toArray();return{rows:i.map(r=>({doc:$(JSON.parse(r.doc)),line:r.line,table:r.tbl})),seq:i.at(-1)?.seq??s.afterSeq}},V=(t,e)=>new Set(n(t,`SELECT id FROM "${T}" WHERE session = ? AND id IS NOT NULL AND substr(tbl, 1, 1) <> '$'`,e).toArray().map(({id:s})=>s)),K=(t,e,s,o,i)=>{n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) <> '$'`,e),n(t,`INSERT INTO "${d}" (session, state, generation, expires_at, result) VALUES (?, 'committed', ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = 'committed', expires_at = excluded.expires_at, result = excluded.result`,e,s,i+N,JSON.stringify(o))},x=(t,e,s)=>{const o=_(t,e);return o!==void 0&&o.generation!==s?!1:(g(t,e),!0)},R=(t,e,s)=>{I(t);const o=n(t,`SELECT manifest FROM "${c}" WHERE session = ?`,e).toArray()[0];if(o===void 0)return;const i=M(o.manifest);if(i===void 0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has a manifest that cannot be read`);return i.state==="open"&&i.expiresAt<s?void 0:i},b=(t,e)=>{n(t,`INSERT INTO "${c}" (session, state, expires_at, manifest) VALUES (?, ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = excluded.state, expires_at = excluded.expires_at, manifest = excluded.manifest`,e.session,e.state,e.expiresAt,JSON.stringify(e))},y=(t,e)=>{const s=(o,i)=>o.localeCompare(i);return[...t].toSorted(s).join(",")===[...e].toSorted(s).join(",")},U=(t,e)=>({batches:0,expiresAt:0,generation:crypto.randomUUID(),globals:!1,pending:0,received:0,rejected:0,sections:[],session:t,shards:[],state:"open",steps:{},storage:!1,tables:[...e]}),k=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0&&!s.begin)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});if(i!==void 0&&i.state!=="open")throw a(i.state==="committed"?"IMPORT_SESSION_COMMITTED":"IMPORT_SESSION_CLOSED",`import session "${e}" is ${i.state==="committed"?"already committed":i.state}`);if(i!==void 0&&!y(i.tables,s.tables))throw new p("IMPORT_SESSION_MISMATCH",`import session "${e}" was opened over other tables`,{status:400});if(i!==void 0&&!s.begin&&i.pending===0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has no staging request in flight to finish`);const r=i??U(e,s.tables),E={...r,batches:r.batches+(s.begin?1:0),expiresAt:o+f,globals:r.globals||s.globals===!0,pending:r.pending+(s.begin?1:-1),received:r.received+(s.received??0),rejected:r.rejected+(s.rejected??0),sections:[...new Set([...r.sections,...s.sections??[]])],shards:[...new Set([...r.shards,...s.shards??[]])],storage:r.storage||s.storage===!0};return b(t,E),{created:i===void 0,manifest:E}},u=(t,e,s,o,i)=>{if(t.steps[e]!==void 0)return a("IMPORT_STEP_DONE",`import session "${t.session}" already ran its ${e} step — send the commit again for its totals`);const r=t.claims?.[e],E=r?.by===s;if(i?!E:r!==void 0&&!E&&r.until>=o)return a("IMPORT_STEP_CLAIMED",`another commit of import session "${t.session}" is running its ${e} step — send the commit again later`)},F=(t,e,s)=>{if(t.state!=="committing")return a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`);if(!("release"in e))return"claim"in e?u(t,e.step,e.claim,s,!1):u(t,e.step,e.claimant,s,!0)},w=(t,e,s)=>"step"in e?F(t,e,s):e.state==="committed"?t.state==="committing"?void 0:a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`):e.state==="aborting"?t.state==="open"||t.state==="aborting"?void 0:a("IMPORT_SESSION_COMMITTING",`import session "${t.session}" is ${t.state} — send the commit again to finish it`):t.state!=="open"?a("IMPORT_SESSION_CLOSED",`import session "${t.session}" is ${t.state}`):t.rejected>0?a("IMPORT_SESSION_REJECTED",`import session "${t.session}" had refused rows or unreachable shards while staging — abort it`):t.pending>0?a("IMPORT_SESSION_INCOMPLETE",`import session "${t.session}" has ${String(t.pending)} staging request(s) that never finished — abort it`):t.batches===e.batches?void 0:a("IMPORT_SESSION_CHANGED",`import session "${t.session}" took another batch after the commit's prepare — commit again`),H=(t,e,s)=>{if(!("step"in e))return{state:e.state};const{[e.step]:o,...i}=t.claims??{};return"claim"in e?{claims:{...i,[e.step]:{by:e.claim,until:s+A}}}:"release"in e?{claims:o===void 0||o.by===e.release?i:{...i,[e.step]:o}}:{claims:i,steps:{...t.steps,[e.step]:e.stepResult}}},z=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});const r=w(i,s,o);if(r!==void 0)throw r;const E={...i,...H(i,s,o),expiresAt:o+f};return b(t,E),v(t,e,o),"state"in s&&s.state==="committed"&&n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) = '$'`,e),E},Q=(t,e,s)=>{const o=R(t,e,s);if(o!==void 0){if(o.state!=="aborting")throw a("IMPORT_SESSION_CLOSED",`import session "${e}" is ${o.state}, not aborting`);x(t,e,o.generation),n(t,`DELETE FROM "${c}" WHERE session = ?`,e)}};export{f as IMPORT_MANIFEST_TTL_MS,N as IMPORT_STAGE_TTL_MS,A as IMPORT_STEP_CLAIM_MS,z as advanceImportManifest,G as assertImportSessionId,Q as dropImportManifest,x as dropImportSession,K as markShardImportCommitted,R as readImportManifest,_ as readShardImportSession,J as stageImportRows,V as stagedImportIds,Y as stagedImportPage,B as sweepImportStaging,k as touchImportManifest,v as touchShardImportSession};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Qn,l as Pe,s as Vn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Jn,stableWireKey as Gt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as zn,aggregateSqlFunction as Oe,normalizeCountArgument as Yn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Xn,selectIndexForCount as Zn,selectIndexForAggregate as eo}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as to,searchIndexCoversTable as no}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as es,backfillRankIndexes as ts,backfillSearchIndexes as ns}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as oo,readCdcDocAtOrBefore as ro}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as rs,applyCdcChanges as is,bumpCdcEpoch as ss,cdcCanVouchFor as cs,cdcForkedError as as,cdcSeqLeavingRows as ds,cdcTouchesTables as ls,cdcTrimmedError as us,compactCdcDocs as fs,cursorBelowRetainedFloor as hs,minCdcReplayableSeq as ws,minCdcSeq as ps,readCdcChangeKeys as gs,readCdcChanges as ys,readCdcCursor as Es,readCdcEpoch as $s,trimCdcChanges as ms}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as io,COMMIT_SEQ_FIELD as so}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as co}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as jt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ht}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as ao}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as pe,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as lo,j as pt,D as ie,r as xe,W as uo,k as fe,b as Ue,A as lt,a as Ge,m as he,e as we,s as fo,t as ho,u as wo,i as po,q as Kt,h as En,g as go}from"./do-sql-105TONaE.mjs";import{renderSql as $n,unionAll as mn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as yo,u as Eo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as $o,boundingBoxGeohashes as mo,haversineMeters as Ro,pointInBoundingBox as So}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as vo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as _o,assertPatchAllowed as To,operatorFields as Ao,readPatchField as Nt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Io,encodeCursor as gt,nullsOrderSuffix as bo,normalizeOrderKeys as Qt,uniqueIndexFields as xo,buildSeekWhere as Co,decodeCursor as Vt,buildSeekBeforeWhere as Mo,softDeleteScope as Ie,applySelect as Sn}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Jt,sortColumnName as zt,resolveRankPartition as Do,encodePartitionKey as ko,RANK_TIEBREAK as Lo,rankPivotConditionSql as Fo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Yt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Bo,withUnknownIndexKeys as Wo,indexKeysForRow as qo,buildIndexRange as Po}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as Ce,c as Z,t as Ye,i as Xt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Me}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as De}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Oo,isPushableWhere as Uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Go,findRelated as jo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ut,findManyPage as Ho,resolveRelationPredicates as Ko,composeReadPredicate as No}from"./DEFAULT_MAX_RELATION_KEYS-B0nxRm8q.mjs";import{describeRelationWrites as Qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Vo,applyInsertDefaults as yt,resolveWith as Jo,relationHooks as zo,applyOnDelete as Yo,fanOutScalarCounts as Xo,CASCADE_MAX_ROWS as Zo}from"./applyInsertDefaults-nXMzGae5.mjs";import{guardWriter as er}from"./RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{mayHoldProjectedValue as tr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as nr}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as or}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ss,migrateClientWatermark as vs,readClientWatermark as _s}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as As,readIdempotent as Is,trimIdempotent as bs,writeIdempotent as xs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ms}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as ks,selectShapeRows as Ls}from"./selectShapeMembers-Dqx_m7BF.mjs";const rr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ir=()=>new R("INVALID_CURSOR","invalid cursor"),en=16,tn=8,z=1024,vt=(n,i)=>i.query(n),sr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of i.entries()){const h=s===i.length-1;let g=0;for(const m of n)(h?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},cr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},ar=(n,i,o)=>{const s={eq:(c,h)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=tn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:h}),s},search:(c,h)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const m=vt(h,o).length;if(m>en)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(en)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=h,g.hasQuery=!0,s}};return s},dr=n=>{if(n.length>z)throw new R("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},lr=n=>Math.min(n.offset+n.numItems+1,z),ur=n=>btoa(`search:${String(n)}`),fr=n=>{let i;try{i=rr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},hr=n=>{if(typeof n.endCursor=="string")throw new R("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?fr(n.cursor):0;if(o===void 0)throw ir();if(o+i>=z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},wr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?ur(o):null,isDone:!s,page:n.slice(i.offset,o)}},pr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new R("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},vn=500,_n=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},gr=32,yr=1024,An=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${De(ie)} FROM ${De(n)}`,h=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Ve(`${c} ${h}`):Ce(`${c} WHERE `,i,` ${h}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,i)=>Ve(lo(n,i)),serialize:Me},Er=n=>n===void 0?"":bo(n==="first"),In=n=>{const i=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Er(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${pt("id")} ${Io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},$r={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},bn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),mr=n=>{const i=bn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Rr=(n,i)=>{const o=n.order,s=mr(n),{shape:c}=i;return s.length>0?Qt(s.map(h=>({[h]:o})),c,{pinned:bn(n),uniqueBy:xo(i.indexes,c)}):Qt([{_creationTime:o}],c)},Sr=(n,i,o,s)=>{const c=n.sqlConditions.map(h=>({[h.field]:{[$r[h.comparator]??"eq"]:h.value}}));if(o&&c.push(Co(i,Vt(o))),s&&c.push(Mo(i,Vt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},vr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,gr):n.want},Et=(n,i,o,s,c,h,g)=>{const m=Rr(s,o),E=In(m),u=[],{filters:C,want:T}=h;let v=h.cursor??void 0,b=vr(h);if(T===0)return{documents:u,orderKeys:m};for(;;){const W=Z(Sr(s,m,v,h.endCursor),Xe,Ye),q=An(i,c&&W?Ce(W," AND ",c):c??W,E,b),B=pe(n,q.text,...q.params).toArray();let O={};g(B.length);for(const j of B)if(O=xe(j),C.every(ee=>ee(O))&&u.push(O)===T)return{documents:u,orderKeys:m};if(b===void 0||B.length<b)return{documents:u,orderKeys:m};v=gt(O,m),b=Math.max(b,Math.min(b*2,yr))}},_r=(n,i,o,s,c,h,g,m)=>{const E=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=Et(n,i,o,s,h,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?gt(B,q):null}}const{documents:u,orderKeys:C}=Et(n,i,o,s,h,{cursor:c.cursor,filters:g.all,selective:g.selective,want:E+1},m),T=u.length>E,v=T?u.slice(0,E):u,b=v.at(-1);return{continueCursor:T&&b?gt(b,C):null,isDone:!T,page:v}},Ze=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(De(o));return i.set(o,c),c}},ge=De(ie),Tr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Ar=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Ir=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),br="SELECT changes() AS changed",on=new Map,xr="",Cr=n=>{const i=JSON.stringify(n),o=on.get(i);if(o!==void 0)return o;const s=n.map(h=>f`SELECT ${f.raw(`'${h.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(h)} WHERE id = ${xr}`),{sql:c}=$n("sqlite",f`${mn(s)} LIMIT 1`);return on.set(i,c),c},Mr=(n,i)=>i.map(()=>n),Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,kr=n=>{if(!Dr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Lr=(n,i,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const h of i){const g=c?yt(n,h,s)._id:h._id;typeof g=="string"&&$t(g)}},rn=50,He=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,Fr=128,Je=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ke=(n,i,o)=>{Tn(n,_n(i,o,Je),o,Je)},cn=async(n,i,o,s,c)=>{const h=_n(s,c,Je),{page:g}=await n.findMany(i,Number.isFinite(h)?{limit:h+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>h&&Tn(Math.max(await n.count(i,{where:o}),g.length),h,c,Je),g},Br=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Wr=n=>Math.max(n,z),xn=(n,i)=>{const o=n.filters.map(s=>f`${we(s.field)} = ${Me(s.value)}`);return i&&o.push(i),o},qr=(n,i,o,s,c)=>{const h=vt(o.query,St(o.definition.language));if(h.length===0)return[];const g=Qn(i,o.indexName),m=`${g}__vocab`,E=h.length-1,u=h.map((q,B)=>{const O=cr(q,B===E),j=O.exact?f`${f.identifier("term")} = ${O.lower}`:f`${f.identifier("term")} >= ${O.lower} AND ${f.identifier("term")} < ${O.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(B))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(m)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=h.map((q,B)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(B))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),T=f`SELECT f.${f.identifier(Pe)} AS ${f.identifier(Pe)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${mn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Pe)} HAVING ${f.join(C.map(q=>f`${q} > 0`),f` AND `)}`,v=xn(o,c);let b=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${T}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Pe)}`;v.length>0&&(b=f`${b} WHERE ${f.join(v,f` AND `)}`),b=f`${b} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const W=[];for(const q of K(n,b)){const B=En(q);if(B){const O=q.__score__;W.push({document:B,score:typeof O=="number"?O:Number(O??0)})}}return W},Pr=(n,i,o,s,c)=>{const h=St(o.definition.language),g=vt(o.query,h);if(g.length===0)return[];const m=xn(o,c);let E=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;m.length>0&&(E=f`${E} WHERE ${f.join(m,f` AND `)}`),E=f`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Wr(s)))}`;const u=K(n,E).toArray(),C=[];for(const T of u){const v=En(T);if(!v)continue;const b=sr(Vn(v,o.definition),g);b>0&&C.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:b})}return C.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),C.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Or=(n,i)=>{const o=n,s={near:(c,h)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c,".near() point",i,o.indexName),!Number.isFinite(h)||h<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(h)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:h},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",i,o.indexName),ft(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.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 o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Ur=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Gr=(n,i)=>{const o=Ur(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=Ro(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return So(o,i.within)?{creationTime:s,distance:0}:void 0},jr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?$o(o.near.point,o.near.radiusMeters):mo(o.within),h=go(i,o.indexName),g=c.map(T=>f`(g.${f.identifier("__geohash__")} >= ${T} AND g.${f.identifier("__geohash__")} < ${`${T}{`})`),m=[f`(${f.join(g,f` OR `)})`];s&&m.push(s);const E=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(h)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(m,f` AND `)}`,u=K(n,E).toArray(),C=[];for(const T of u){const v=xe(T),b=v?Gr(v,o):void 0;v&&b&&C.push({creationTime:b.creationTime,distance:b.distance,doc:v})}return C.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),C},Cn=(n,i,o,s)=>{const c=[];for(const h of n)if(i.every(g=>g(s(h)))&&(c.push(h),typeof o=="number"&&c.length>=o))break;return c},Hr=(n,i,o,s,c,h=()=>{})=>{const g=o.within!==void 0,m=jr(n,i,o,c).map(E=>({distanceMeters:g?null:E.distance,document:E.doc}));return h(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},an=(n,i,o,s,c,h,g=()=>{})=>{const{geo:m}=o;if(!m)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const E=c.length>0,u=Hr(n,i,m,E?void 0:h,s,g);return E?Cn(u,c,h,C=>C.document):u},dn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&tr(s))throw new R("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Kr=n=>{let i=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:h,negated:g,parentTable:m,relation:E}=c,u=`__rel_${String(i)}`,C=o.at(-1)??m;i+=1,n(E.table,G);const T=E.kind==="one"?E.field:E.references,v=E.kind==="one"?E.references:E.field,b=Ve(`${Kt(u,v)} = ${Kt(C,T)}`);o.push(u);const W=Z(h,s,Ye);o.pop();const q=W===void 0?b:Ce(b," AND ",W),B=Ce("EXISTS (SELECT 1 FROM ",Xt(E.table)," AS ",Xt(u)," WHERE ",q,")");return g?Ce("NOT ",B):B}};return s};class Nr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Qr=/\s/u,Vr=String.fromCodePoint(0),ln=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Qr.test(o)||o.includes(Vr)?null:o},Mn=(n,i,o,s=()=>{},c=()=>{},h=()=>{},g)=>{const m=i.tables[o];if(!m)throw new R("INTERNAL",`unknown table: ${o}`);const E=Ie(m.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,he):void 0},T=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,Xe,Ye):void 0},v=()=>[...u.inMemoryFilters,...u.verifyFilters];let b=0;const W=S=>{const{search:M}=u;if(!M)throw new R("INTERNAL","runSearchFetch called without a staged search");to(wo(n),o,m);const L=u.inMemoryFilters.length>0,F=pr(L?void 0:S),k=po(n);if(k&&!no(n,o,M.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ye=C(),te=k?qr(n,o,M,F,ye):Pr(n,o,M,F,ye);!L&&S===void 0&&dr(te);const Ee=v();return b=te.length,Ee.length>0?Cn(te,Ee,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=hr(S);return wr(q(lr(M)),M)},O=()=>{if(u.search||u.geo||u.indexName===void 0){c(void 0);return}c(Po(o,u.indexName,u.indexFields,u.sqlConditions,Me))},j=S=>{O();let M=0;const L=(()=>{if(u.search){const F=q(S);return M=b,F}return u.geo?an(n,o,u,C(),v(),S,F=>{M=F}).map(F=>F.document):Et(n,o,m,u,T(),{filters:v(),selective:u.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return h(Math.max(M,L.length)),L},ee=()=>{if(!u.search&&!u.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let S=0;const M=(()=>{if(u.search){const L=W(void 0);return S=b,L}return an(n,o,u,C(),v(),void 0,L=>{S=L})})();return h(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=Mn(n,i,o,s,c,h,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Fr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Oo(S);return M!==void 0&&Uo(M,m.shape)?(u.pushedWhere=Q(u.pushedWhere,M),u.verifyFilters.push(S)):u.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return u.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(O(),u.search){const F=B(S);return h(F.page.length),F}if(u.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=_r(n,o,m,u,S,T(),{all:v(),selective:u.inMemoryFilters.length>0},F=>{M+=F});return h(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Nr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(m.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(u.geo=F,M(Or(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=m.indexes.find(F=>F.name===S);if(!L)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),u.indexName=S,u.indexFields=L.fields,M&&M(Br(u)),N},withSearchIndex(S,M){const L=(m.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(u.search=F,M(ar(F,o,St(L.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,i,o,s)=>{const c=o;for(const[h,g]of ho(n)){if(g.serverDefault){h in i&&(c[h]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(h in i)&&(c[h]=g.onUpdateFn())}},un=5,fn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ne=n=>hn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!hn.includes(i))):n,Jr=/unique constraint failed/i,zr=n=>n instanceof Error&&Jr.test(n.message),Yr=/string or blob too big/iu,Xr=(n,i)=>{if(!(!(n instanceof Error)||!Yr.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,i,o,s)=>{try{pe(n,o,...s)}catch(c){throw zr(c)?new ae(`unique constraint violation on "${i}"`,"unique"):(Xr(c,i),c)}},Qe=(n,i,o,s)=>{if(mt(n,i,o,s),pe(n,br).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,i,o,s,c,h,g)=>{const m=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],b=s[T],W=b?.direction==="desc"?"desc":"asc",q=v===void 0||b===void 0?f`${f.identifier(Lo)} < ${g}`:Fo(v,h[T],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(f`${f.identifier(o[j])} IS ${h[j]}`);B.push(q);const[O]=B;m.push(B.length===1&&O!==void 0?O:f`(${f.join(B,f` AND `)})`)}const E=m.length>0?f.join(m,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c} AND (${E})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c}`).one();return{before:u.c,total:C.c}},Zr=n=>{const i=new Map;for(const[s,c]of Object.entries(n.tables))for(const h of Object.values(c.relationMap??{}))h.kind==="one"&&(h.onDelete==="cascade"||h.onDelete==="set null")&&i.set(h.table,[...i.get(h.table)??[],{holder:s,op:h.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,h=[s];for(let g=h.pop();g!==void 0;g=h.pop())for(const{holder:m,op:E}of i.get(g)??[]){if(m===s||Zt(n,m,E))return!0;c.has(m)||(c.add(m),h.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Zt(n,s,"delete")||o(s)).map(([s])=>s))},ei=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},wt=new WeakMap,ti=(n,i)=>{let o=wt.get(i.tables);if(!wt.has(i.tables)){const c=Object.keys(i.tables).map(h=>h.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},ni=(n,i,o)=>{for(const s of n){const c=s,h=c?.[ie];if(typeof h=="string"){const g=c?.id,m=Eo(h);typeof g!="string"?i.recordReadBytes(m):o===void 0?i.recordDocumentRead(`${g}\0${String(m)}`,m):i.recordDocumentRead(`${o}\0${g}`,m)}}},oi=(n,i,o)=>{if(i===void 0)return n;const s=(c,...h)=>{const g=n.exec(c,...h),m=g.one.bind(g),E=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ti(c,o);let C=!1;const T=v=>{ni(v,i,u)};return g.toArray=()=>{const v=[];for(const b of{[Symbol.iterator]:E})T([b]),v.push(b);return v},g.one=()=>{C=!0;try{const v=m();return T([v]),v}finally{C=!1}},g[Symbol.iterator]=function*(){for(const b of{[Symbol.iterator]:E})C||T([b]),yield b},g};return new Proxy(n,{get:(c,h)=>h==="exec"?s:h===uo?c:Reflect.get(c,h,c)})},ri=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ii=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),be=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=yo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},ze=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{be(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const h of c.page??[])be(h,o,s);return}case"rows":{for(const h of Array.isArray(n)?n:[n])be(h,o,s);return}default:for(const h of Array.isArray(n)?n:[])be(h.document,o,s)}},Dn=(n,i,o)=>new Proxy(n,{get:(s,c)=>{const h=Reflect.get(s,c,s);if(typeof h!="function")return h;if(c===Symbol.asyncIterator)return async function*(){for await(const E of Reflect.apply(h,s,[]))be(E,i,o),yield E};const g=ii.get(c);return(...m)=>{const E=Reflect.apply(h,s,m);return g!==void 0?Promise.resolve(E).then(u=>(ze(u,g,i,o),u)):typeof E=="object"&&E!==null&&!(E instanceof Promise)?Dn(E,i,o):E}}}),si=new Set(["findFirst","findFirstOrThrow","findMany"]),ci=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),c=s.with,h=g=>Sn(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:h(g.page)}:h([g])[0]}},pn=256,Rt=4096,ai=1024*1024,di=async(n,i,o,s)=>{const c=i[1]??{},h=[];let{cursor:g}=c,m=pn,E=0;for(;;){const u=await n([i[0],{...c,cursor:g,limit:m},...i.slice(2)]);if(Array.isArray(u))return ze(u,"rows",o,s),[...h,...u];const C=s.headroom().readBytes;if(ze(u,"page",o,s),h.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:h};g=u.continueCursor,E+=s.headroom().readBytes-C,m=E>0?Math.min(Rt,Math.max(pn,Math.floor(ai*h.length/E))):Rt}},li=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),i);const h=ri.get(s);return h===void 0?c:async(...g)=>{const m=si.has(s)?ci(g):void 0;let E=m?.args??g;const u=String(g[0]),C=E[1],T=s==="findMany"&&typeof C?.endCursor=="string",v=s==="findMany"&&typeof C?.limit!="number"&&!T;if(T&&typeof C.limit!="number"&&(E=[E[0],{...C,limit:Rt},...E.slice(2)]),v){const W=await di(q=>Reflect.apply(c,o,q),E,u,i);return m===void 0?W:m.project(W,h)}const b=await Reflect.apply(c,o,E);return ze(b,h,u,i),m===void 0?b:m.project(b,h)}}}),gn=new WeakMap,yn=new WeakMap,ui=500,fi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=gn.get(n)??{value:void 0},h=yn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};gn.set(e,c),yn.set(e,h),g=fi(e)}return g},E=oi(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Go(u),b=new Map;for(const e of v){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&b.set(e.sourceTable,[...b.get(e.sourceTable)??[],e])}const W=(e,t,r)=>{for(const a of b.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(K(E,f`SELECT 1 FROM ${f.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},q=Qo(u,n.inTransaction),B=Zr(u),O=ei(u),j=()=>n.inTransaction?.()===!0,ee=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=io(E)),{[so]:c.value}),N=(e,...t)=>{const r=u.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Bo(l))),a.push(...Wo(r,qo(r,p,Me))));return a.length>0?a:void 0},S=n.onRead??(()=>{}),M=e=>{jt(u.tables[e])&&S(Yt,Yt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,r)},ye=(e,t)=>{const r=e.row._id;k(e.tableName,typeof r=="string"?r:t,typeof r=="string")},te=n.onIndexUse??(()=>{}),Ee=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},$e=async e=>{J(e.doc),await Ee(e)},{cache:de}=n,me=n.clock??(()=>Date.now()),_t=n.idGenerator??(()=>crypto.randomUUID()),Tt=n.scheduler??zn,Re=li(n.globalDb,s),le=n.auth??{identity:null,userId:null},At=n.cdc??!1,et=Tt,kn=nr({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,r,a)=>{At&&!jt(u.tables[e])&&oo(E,me(),e,t,r,a)},It=(e,t,r,a)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!At)return!1;const p=i?.();if(p===void 0)return!1;const d=ro(E,e,t,p);if(d===void 0)return!1;const w=Ao(l,r);return Object.keys(Ne(r)).some(y=>!w.has(y)&&Gt(Nt(d,y))!==Gt(Nt(a,y)))},se=e=>u.tables[e]?.shardMode?.kind==="global",bt=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}return U},tt=e=>bt(e,"cascade"),H=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}},ce=(e,t,r)=>{de?.invalidateTable(t),C({key:r,op:e,table:t})},xt=async(e,t,r,a,l)=>{l&&J(r);const p=await e.insert(t,r,a);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Ln=(e,t)=>bt(e,"relation load").findMany(e,t),Fn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ct=e=>{for(const t of e===void 0?[]:Fn(e))se(t)&&k(t,G)},Mt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Ct(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(Ct(p),typeof l=="object"&&Mt(p.table,l.with))}},nt=(e,t)=>(se(e)&&(k(e,G),Mt(e,t.with)),Ln(e,t)),Bn=e=>!se(e.table),Dt=n.relationExistsPushDown??"auto",kt=Dt!=="never",{maxRelationKeys:Lt}=n,ke=(e,t,r)=>Ko(e,{fetcher:nt,maxRelationKeys:Lt,relationBaseWhere:r,schema:u,tableName:t}),Wn=async(e,t,r,a)=>{const l=H(e,"relation grouped count");if(l)return k(e,G),Xo(($,P)=>l.count($,P),e,t,r,a);const p=u.tables[e];if(!p)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const d=Ie(p.softDeleteMode,void 0),w={[t]:{in:r}},y=Q(Q(w,a),d),A=await ke(y,e,void 0),x=Z(A,he),I=we(t);let _=f`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;x&&(_=f`${_} WHERE ${x}`),_=f`${_} GROUP BY ${I}`;const D=K(E,_).toArray();return new Map(D.map($=>[$.__fk__,$.count]))},Ft=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Ft.add(`${e} ${r.timing} ${r.op}`);const ne=(e,t,r)=>Ft.has(`${e} ${t} ${r}`),oe=async(e,t,r)=>{if(h.value+=1,h.value>rn)throw h.value-=1,new ae(`trigger recursion exceeded ${String(rn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await or({ctx:Kn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{h.value-=1}},{ensureBackfilledForTable:ve,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:_e,syncAggregates:Le,syncCompanionsForInsert:Bt,syncGeo:Fe,syncRanks:Te,syncSearch:Be}=co({broadcast:C,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,r)=>de?.invalidate(e,t,N(e,r)),recordCdc:Se,schema:u,sql:E,verified:n.companionMemo?.verified}),Wt=(e,t,r)=>{const{shardMode:a}=t;if(a?.kind==="shardBy"&&!(a.field!==void 0&&(r.partitionBy??[]).includes(a.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${a.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})},qt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ae=e=>e===void 0||se(e)?Re:void 0,qn=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(a=>a.through!==void 0||a.kind!=="one"||a.table!==e?[]:a.onDelete!=="cascade"&&a.onDelete!=="set null"?[]:[{action:a.onDelete==="cascade"?"delete":"update",field:a.field,holderTable:t,references:a.references}]):[]),Pn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],On=async(e,t,r,a,l)=>{const p=[];let d;do{const w=await e.findMany(t,{cursor:d,includeDeleted:l,limit:ui,where:{[r]:a}});for(const y of w.page)p.push(String(y._id));d=w.isDone?void 0:w.continueCursor??void 0}while(d!==void 0&&p.length<=Zo);return p},Un=async(e,t,r,a,l,p)=>{const{action:d,field:w,holderTable:y,references:A}=r,x=await Pn(e,t,A,a);if(x==null)return{effects:[],toExpand:[]};const I=await On(e,y,w,x,p),_=I.filter($=>!l.announced.has(`${d}:${y}:${$}`)),D=d==="delete"?I.filter($=>!l.expanded.has(`${y}:${$}`)):[];for(const $ of _)l.announced.add(`${d}:${y}:${$}`);for(const $ of D)l.expanded.add(`${y}:${$}`);return{effects:_.map($=>({id:$,op:d,table:y})),toExpand:D}},Pt=async(e,t,r,a,l)=>{const p=[];for(const d of qn(t))for(const w of r){const y=await Un(e,t,d,w,a,l);p.push(...y.effects),y.toExpand.length>0&&p.push(...await Pt(e,d.holderTable,y.toExpand,a,l))}return p},it=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)J(void 0);const p=a?.skipOnDelete===!0?[]:await Pt(e,t,r,{announced:new Set,expanded:new Set},a?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},re=(e,t)=>{const r=qt(t);for(let a=0;a<r.length;a+=sn){const l=r.slice(a,a+sn),[p]=pe(E,Cr(l),...Mr(e,l)).toArray();if(!p)continue;const d=p.__t__,w=xe(p);if(typeof d!="string"||!w)return;const y=p[ie];return{docJson:typeof y=="string"?y:fe(y??{}),row:w,tableName:d}}},Ot={assertRankPartitionLocal:Wt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:u,sql:E},Gn=(e,t,r)=>{const a=Z(r,he);return a===void 0||K(E,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${a}`).toArray().length>0},jn=(e,t,r,a)=>It(e,t,r,a)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Hn=async(e,t,r,a,l)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Gn(e,t,r.where)||jn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:re(t,e)?.row??null}},Ut=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:w}=await No(t,r,{canPushExists:kt?Bn:void 0,existsPushMode:Dt==="always"?"always":"auto",fetcher:nt,maxRelationKeys:Lt,schema:u,tableName:e}),y=kt?Kr(a):Xe,A=Z(w,y,Ye),x=An(e,A,In(d),l);return{limit:p,orderKeys:d,statement:x}},U={system:kn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return k(e,G),r.aggregate(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const l=Ie(a.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await ke(p,e,t.relationBaseWhere),w=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!w){const $=eo(a.aggregateIndexes,t.op,t.field,t.where);if($){ot(e,$.index);const P=ct($.index.by??[],$.key),Y=st(e,$.index.name),X=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(Y)} WHERE ${Ge} = ${P}`).toArray()[0];return at(t.op,X)}}dn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const y=Z(d,he),A=Oe(t.op),x=we(t.field);let I=f`SELECT ${f.raw(A)}(${x}) AS value FROM ${f.identifier(e)}`;y&&(I=f`${I} WHERE ${y}`);const D=K(E,I).toArray()[0]?.value;return D??null},asId(e,t){const r=ln(u,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return k(e,G),r.count(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=Yn(t);if(l.restrictsCounts)throw new dt(e);k(e,G);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),w=await ke(d,e,l.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!l.baseWhere&&!y){const _=Zn(a.aggregateIndexes,l.where);if(_){ot(e,_.index);const D=ct(_.index.by??[],_.key),$=st(e,_.index.name),P=K(E,f`SELECT ${Ue} AS value FROM ${f.identifier($)} WHERE ${Ge} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(w,he);let x=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return A&&(x=f`${x} WHERE ${A}`),K(E,x).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const a=re(t,e);if(!a){const _=Ae(e);_&&await it(_,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,w=u.tables[d],y=r?.hard===!0,A=!y&&w?.softDeleteMode?w:void 0,x=A?.softDeleteMode?.field;if(x&&p[x]!==null&&p[x]!==void 0)return;if(ne(d,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await Yo({deletedId:t,deletedReference:_=>p[_],findHolders:async(_,D,$,P)=>(await tt(_).findMany(_,{...P,includeDeleted:y,where:{[D]:$}})).page,onCascade:(_,D)=>tt(_).delete(_,D,r),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,D,$)=>tt(_).patch(_,D,{[$]:null}),schema:u,tableName:d}),ve(d),_e(d),A&&x){const _={[x]:me()},D={...p,...ee(d),..._,_id:t};ht(A,_,D,le),Qe(E,d,nn(d),[fe(D),t,l]),Be(d,t,D,p),Fe(d,t,void 0),Le(d,p,D),Te(d,t,p,void 0);const $=N(d,p,D);de?.invalidate(d,t,$),Se(d,t,"update",D),C({indexKeys:$,key:t,op:"update",row:D,table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d});return}Qe(E,d,Ir(d),[t,l]),Be(d,t,void 0),Fe(d,t,void 0),Le(d,p,void 0),Te(d,t,p,void 0);const I=N(d,p);de?.invalidate(d,t,I),Se(d,t,"delete"),C({indexKeys:I,key:t,op:"delete",table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??vn),a=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const w=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(y=>String(y._id));if(w.length===0)break;for(const y of w)await(l===void 0?U.delete(e,y,a):it(l,e,[y],a)),p+=1;if(w.length<r)break}return{deleted:p}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),Ke(t.length,r?.limit,"deleteMany");for(const a of t)await U.delete(e,a);return{deleted:t.length}},async deleteWhere(e,t,r){const a=H(e,"deleteWhere"),p=(await cn(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return it(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,p,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new vo(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return k(e,G),t.consistency==="primary"&&S(e,ao),r.findMany(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?k(e,G):k(e);const{limit:p,orderKeys:d,statement:w}=await Ut(e,a,t,k),y=pe(E,w.text,...w.params).toArray();l&&s?.recordRead(y.length);const A=[];for(const I of y){const _=xe(I);_&&(A.push(_),!l&&typeof _._id=="string"&&k(e,_._id))}const x=Ho(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Jo({fetcher:nt,groupedCounter:Wn,parents:x.page,...zo(t),schema:u,tableName:e,with:t.with}),{...x,page:Sn(x.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Ut(e,a,t,()=>{}),p=pe(E,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const r=re(t,e);if(!r){const a=Ae(e);return a?(S(e,t,!0),a.get(e,t)):(M(e),S(e,t,!0),null)}return ye(r,t),r.row},async lookupById(e,t){const r=re(e,t);if(!r){for(const a of qt(t))M(a),S(a,e,!0);return null}return ye(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return k(e,G),r.groupBy(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),w=await ke(d,e,t.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!t.baseWhere&&!y){const $=Xn(a.aggregateIndexes,l.op,l.field,t.by,t.where),P=$===void 0?0:Object.keys($.partial).length,Y=$?.index.by?.length??0;if($&&(P===0||P===Y)){ot(e,$.index);const X=st(e,$.index.name),V=Object.keys($.partial),ue=[];if(V.length===($.index.by??[]).length&&V.length>0){const We=ct($.index.by??[],$.partial),qe=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)} WHERE ${Ge} = ${We}`).toArray();return qe.length>0&&ue.push({key:{...$.partial},value:at(l.op,qe[0])}),ue}const Nn=K(E,f`SELECT ${Ge} AS key, ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)}`).toArray();for(const We of Nn){const qe=Jn(JSON.parse(We.key));ue.push({key:qe,value:at(l.op,We)})}return ue}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const P=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;dn(a,$,P)}const A=Z(w,he),x=t.by.map($=>f`${we($)} AS ${f.identifier($)}`);if(l.op==="count")x.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);x.push(f`${f.raw(Oe(l.op))}(${we($)}) AS value`)}let I=f`SELECT ${f.join(x,f`, `)} FROM ${f.identifier(e)}`;A&&(I=f`${I} WHERE ${A}`),I=f`${I} GROUP BY ${f.join(t.by.map($=>we($)),f`, `)}`;const _=K(E,I).toArray(),D=[];for(const $ of _){const P={};for(const X of t.by)P[X]=fo(a.shape[X],$[X]??null);const{value:Y}=$;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,r){const a=H(e,"insert");if(a)return xt(a,e,t,r,!0);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=je(l,yt(l,t,le),{supplied:t,trusted:p});let w;r?.clientId!==void 0?(kr(r.clientId),w=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?($t(d._id),w=d._id):w=_t();const y=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:me(),A={...d,...ee(e),_creationTime:y,_id:w};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:w,op:"insert",table:e}),p||W(e,A),ve(e),_e(e),mt(E,e,Tr(e),[w,y,fe(A)]),Bt(e,w,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:w,op:"insert",table:e}),await $e({doc:A,id:w,op:"insert",table:e}),w},async insertManyUnsafe(e,t,r){if(Ke(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=H(e,"insert");if(a){const y=[];Lr(u.tables[e],t,r?.allowExplicitId,le);for(const A of t)J(A);for(const A of t){const x=await a.insert(e,A,{allowExplicitId:r?.allowExplicitId});C({key:x,op:"insert",row:{...A,_id:x},table:e}),y.push(x)}return y}const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);ve(e),_e(e);const p=[];for(let y=0;y<t.length;y+=He)p.push(ee(e));const d=r?.allowExplicitId===!0?void 0:Vo(l),w=t.map((y,A)=>{const x=yt(l,y,le),I=d===void 0?x:je(d,x,{supplied:y}),_=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;_!==void 0&&$t(_);const D=_??_t(),$=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:me(),P={...I,...p[Math.floor(A/He)],_creationTime:$,_id:D};return{creationTime:$,document:P,id:D}});for(const y of w)J(y.document);for(let y=0;y<w.length;y+=He){const A=f.join(w.slice(y,y+He).map(I=>f`(${I.id}, ${I.creationTime}, ${fe(I.document)})`),f`, `),x=$n("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${A}`);mt(E,e,x.sql,x.params)}for(const{document:y,id:A}of w)Bt(e,A,y),await Ee({doc:y,id:A,op:"insert",table:e});return w.map(y=>y.id)},async insertMany(e,t,r){Ke(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const w of t)J(w);const d=async w=>p?xt(p,e,w,void 0,!1):U.insert(e,w);for(const w of t)try{l.push(await d(w))}catch(y){if(a&&y instanceof ae&&y.kind==="unique")l.push(null);else throw y}return l},normalizeId(e,t){return ln(u,e,t)},async patch(e,t,r,a){T(e,"ctx.db.patch(table, id, values)");const l=re(t,e);if(!l){const D=Ae(e);if(D){J(r);try{await D.patch(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);if(k(w,t),fn("patch",r),It(w,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:w});return}const A=_o(y,r,d),x={...d,...Ne(A),...ee(w),_id:t};ht(y,A,x,le);const I=je(y,x,{only:new Set(Object.keys(A)),previous:()=>d,tolerateStoredNull:!0});To(a,d,I),ne(w,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:d,table:w}),W(w,I,d),ve(w),_e(w),Qe(E,w,nn(w),[fe(I),t,p]),Be(w,t,I,d),Fe(w,t,I),Le(w,d,I),Te(w,t,d,I);const _=N(w,d,I);de?.invalidate(w,t,_),Se(w,t,"update",I),C({indexKeys:_,key:t,op:"update",row:I,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:d,table:w}),await $e({doc:I,id:t,op:"update",table:w})},async patchIf(e,t,r){const a=H(e,"patchIf");if(a){if(a.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);J(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=un;l+=1){const p=await Hn(e,t,r,l<un,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),Ke(t.length,r?.limit,"patchMany");for(const a of t)await U.patch(e,a.id,a.patch);return{patched:t.length}},async patchWhere(e,t,r){const a=H(e,"patchWhere")??U,p=(await cn(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,p,r),{patched:p.length}},async related(e,t){return jo(U,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:O,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(E,u,e,te,r=>{r?F(r):k(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=H(e,"rank");if(te(e,t,"rank"),a)return k(e,G),a.rank(e,t,r);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(V=>V.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Wt(e,l,p),r.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const w=Jt(e,p.name),y=p.sortBy.map((V,ue)=>zt(ue)),A=y.map(V=>De(V)).join(", "),x=K(E,f`SELECT ${f.identifier("__partition__")}, ${f.raw(A)} FROM ${f.identifier(w)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[I]=x;if(I===void 0)return null;let _=I.__partition__;const D=Q(r.baseWhere,r.where);ut(D,u,e,"rank");const $=Do(p,D);if($){const V=ko(p.partitionBy??[],$);if(V!==_)return null;_=V}const P=y.map(V=>I[V]),{before:Y,total:X}=wn(E,w,y,p.sortBy,_,P,d);return{position:Y+1,total:X}},async rankBefore(e,t,r){if(se(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(y=>y.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new dt(e);k(e,G),rt(e,l);const p=Jt(e,l.name),d=l.sortBy.map((y,A)=>zt(A)),w=l.sortBy.map((y,A)=>Me(r.sortValues[A]??null));return wn(E,p,d,l.sortBy,r.partitionKey,w,r.rowId)},async rankPage(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage");const a=H(e,"rankPage");if(te(e,t,"rank"),a)return k(e,G),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Ht(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(w=>w.doc)}},async rankPageRows(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage"),te(e,t,"rank");const{directions:a,hasMore:l,rows:p}=Ht(Ot,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=re(t,e);if(!r){const p=Ae(e);if(p?.restore){try{await p.restore(e,t)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const a=u.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[a]!==null&&r.row[a]!==void 0;await U.patch(e,t,{[a]:null}),l&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,a){T(e,"ctx.db.replace(table, id, document)");const l=re(t,e);if(!l){const P=Ae(e);if(P){J(r);try{await P.replace(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);fn("replace",r);const A=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof d._creationTime=="number"?d._creationTime:void 0,I=A??x??me(),_={...r,...ee(w),_creationTime:I,_id:t};ht(y,r,_,le);const D=a?.allowExplicitId===!0,$=je(y,_,{previous:()=>d,supplied:r,trusted:D});ne(w,"before","update")&&await oe("before","update",{doc:{...$},id:t,op:"update",previous:d,table:w}),D||W(w,$,d),ve(w),_e(w),Qe(E,w,Ar(w),[I,fe($),t,p]),Be(w,t,$,d),Fe(w,t,$),Le(w,d,$),Te(w,t,d,$),de?.invalidate(w,t,N(w,d,$)),Se(w,t,"update",$),C({indexKeys:N(w,d,$),key:t,op:"update",row:$,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:$,id:t,op:"update",previous:d,table:w}),await $e({doc:$,id:t,op:"update",table:w})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(u.tables).filter(([w,y])=>t.has(w)||r!==void 0&&!r.includes(w)?!1:y.shardMode?.kind!=="global").map(([w])=>w);if(r!==void 0){for(const w of r)if(!u.tables[w])throw new R("INTERNAL",`wipeShard: unknown table: ${w}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const w of a){const y=await d(w,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[w]=y.deleted,p+=y.deleted}return{deleted:p,tables:l}}},Kn={db:U,scheduler:Tt};return n.enforceRls===!0?er(U,u,(e,t)=>re(e,t)?.tableName,v):U};export{rs as CDC_LOG_TABLE,As as IDEMPOTENCY_TABLE,Nr as NotUniqueError,Ss as advanceClientWatermark,is as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,kr as assertValidClientId,es as backfillAggregateIndexes,ts as backfillRankIndexes,ns as backfillSearchIndexes,ss as bumpCdcEpoch,cs as cdcCanVouchFor,as as cdcForkedError,ds as cdcSeqLeavingRows,ls as cdcTouchesTables,us as cdcTrimmedError,fs as compactCdcDocs,fi as createShardCtxDb,hs as cursorBelowRetainedFloor,oi as meterReadBytes,vs as migrateClientWatermark,ws as minCdcReplayableSeq,ps as minCdcSeq,ln as normalizeIdStructurally,gs as readCdcChangeKeys,ys as readCdcChanges,Es as readCdcCursor,$s as readCdcEpoch,_s as readClientWatermark,Is as readIdempotent,Ms as runShardMigrations,ks as selectShapeMembers,Ls as selectShapeRows,Ne as stripReservedPatchFields,ms as trimCdcChanges,bs as trimIdempotent,xs as writeIdempotent};
|
package/dist/packem_shared/{applyInsertDefaults-BJ4dP3OL.mjs → applyInsertDefaults-nXMzGae5.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-105TONaE.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-105TONaE.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{N as CASCADE_MAX_ROWS,B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-BezPdXmB.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-Bc7PsQhM.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=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"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const y=200,_=(e,t)=>{const o=r=>{const s=e.tables[r];return s!==void 0&&s.shardMode?.kind!=="global"};return(t&&t.length>0?[...t]:Object.keys(e.tables)).filter(r=>o(r))},h=async function*(e,t,o=y){let r=null,s=!1;for(;!s;){const n=await e.findMany(t,{cursor:r,includeDeleted:!0,limit:o});for(const i of n.page)yield{doc:i,table:t};r=n.continueCursor,s=n.isDone||r===null}},W=async function*(e,t,o){const r=_(t,o.tables),s=o.batchSize??y;for(const n of r)yield*h(e,n,s)},E=new Set(["_creationTime","_id"]),R=(e,t)=>{for(const[o,r]of Object.entries(e.shape)){const s=t[o];if(s===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(s)}catch(i){const a=i instanceof Error?i.message:String(i);return`field "${o}": ${a}`}}},A=(e,t,o)=>{const r=e.tables[t];if(!r)return`unknown table: ${t}`;if(r.shardMode?.kind==="global")return`table "${t}" is a global (.global()) table and is not importable through the shard import path`;const s=Object.fromEntries(Object.entries(o).filter(([n])=>!E.has(n)));for(const n of Object.keys(s))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${t}"`;return R(r,s)},k=async(e,t,o)=>{if(e.lookupById){const r=await e.lookupById(o);return r===null?void 0:r.tableName}return await e.get(t,o)===null?void 0:t},S=async(e,t,o)=>{try{return await k(e,t,o)}catch{return}},v=e=>u in e?Object.fromEntries(Object.entries(e).filter(([t])=>t!==u)):e,m=(e,t,o)=>{const{table:r}=t;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:o,message:"row is missing `table`",table:r};if(!t.doc||typeof t.doc!="object"||Array.isArray(t.doc))return{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:r};const s=A(e,r,v(t.doc));return s===void 0?void 0:{code:"VALIDATION_ERROR",line:o,message:s,table:r}},g=(e,t,o)=>{const r=e.tables[t.table];return r===void 0?{code:"BAD_ROW",line:o,message:`unknown table: ${t.table}`,table:t.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:o,message:`table "${t.table}" is a global (.global()) table and is not importable through the shard import path`,table:t.table}:typeof t.doc?._id=="string"?void 0:{code:"BAD_ROW",line:o,message:"a delete row needs the `_id` to delete",table:t.table}},I=async(e,t,o,r)=>{const s=g(t,o,r);if(s!==void 0)return{error:s,kind:"error"};const n=o.doc._id;try{const i=await k(e,o.table,n);return i===void 0?{kind:"absent"}:i!==o.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${i}", not "${o.table}"`,table:o.table},kind:"error"}:(await e.delete(o.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(i){const{body:a}=b(i,{fallbackCode:"DELETE_FAILED"});return{error:{code:a.code,line:r,message:a.message,table:o.table},kind:"error"}}},D=async(e,t,o,r,s)=>{const n=m(t,o,r);if(n!==void 0)return{error:n,kind:"error"};const{table:i}=o,a=v(o.doc),l=typeof a._id=="string"?a._id:void 0,d=l===void 0?void 0:await S(e,i,l);if(d!==void 0&&d!==i)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(l)}" already belongs to table "${d}"`,table:i},kind:"error"};if(d===i&&l!==void 0){if(s!=="replace")return{kind:"conflict"};try{const c={...a};return delete c._id,await e.replace(i,l,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:f}=b(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}}try{return await e.insert(i,a,{allowExplicitId:!0}),{kind:"inserted",table:i}}catch(c){const{body:f}=b(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}},O=(e,t,o)=>e.op==="delete"?o?void 0:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},L=async(e,t,o)=>{const r={};for(const s of t){const n=[];for await(const{doc:i}of h(e,s)){const a=i._id;typeof a=="string"&&!o.has(a)&&n.push(a)}for(const i of n)await e.delete(s,i,{hard:!0});r[s]=n.length}return r},$=(e,t)=>e.has(t.table)?typeof t.doc?._id=="string"?void 0:"a replace import row must carry its `_id`":`table "${t.table}" is not in this replace import's tables`,C=async(e,t,o,r,s,n)=>{const i=O(o,r,n);return i!==void 0?{error:i,kind:"error"}:o.op==="delete"?I(e,t,o,r):D(e,t,o,r,s)},B=(e,t,o,r)=>{const s=n=>{e.inserted[n]=(e.inserted[n]??0)+1};switch(t.kind){case"absent":break;case"conflict":{e.conflicts+=1;break}case"deleted":{e.deleted+=1;break}case"error":{e.errors.push(t.error);break}case"replaced":{r?s(o):e.replaced+=1;break}default:s(t.table)}},T=(e,t)=>t?.filter(o=>{const r=e.tables[o];return r!==void 0&&r.shardMode?.kind!=="global"}),j=(e,t,o,r)=>O(t,o,r)??(t.op==="delete"?g(e,t,o):m(e,t,o)),F=async(e,t,o)=>{const r={conflicts:0,deleted:0,errors:[],inserted:{},replaced:0};let s=(o.startLine??1)-1;const n=T(t,o.replaceTables),i=new Set(n),a=n===void 0?o.onConflict??"skip":"replace";for(const d of o.rows){s+=1;const c=n===void 0?void 0:$(i,d);if(c!==void 0){r.errors.push({code:"BAD_ROW",line:s,message:c,table:d.table});continue}if(o.dryRun===!0){const p=j(t,d,s,o.deletes===!0);p!==void 0&&r.errors.push(p);continue}const f=await C(e,t,d,s,a,o.deletes===!0);B(r,f,d.table,n!==void 0)}if(n===void 0||o.keepIds===void 0||r.errors.length>0||o.dryRun===!0)return r;const l=new Set([...o.keepIds,...o.rows.flatMap(d=>d.op!=="delete"&&typeof d.doc._id=="string"?[d.doc._id]:[])]);return{...r,pruned:await L(e,n,l)}},N=e=>{const t=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:t}},w=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},z=e=>{const t=Array.isArray(e.rows)?e.rows:[],o=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){o.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}o.push({doc:n.doc,...w(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:o,startLine:r}};export{W as exportShardRows,F as importShardRows,N as parseExportShardArgs,z as parseImportShardArgs,$ as replaceRefusal,_ as selectExportTables,A as validateImportRow};
|
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.202",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.87 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "^1.0.0-alpha.81",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
54
54
|
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{decodeWire as G,WIRE_TAG as F,needsWireEncoding as J,encodeWire as X}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as $}from"./isInternalTableName-BoljO2tP.mjs";import{n as y,o as V}from"./do-sql-105TONaE.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as Y,sqliteInList as Z}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Fe="__lunora_admin__:",xe="__lunora_relation__:",qe="__lunora_flags__:",Ue={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiCronExpression:"__lunora_admin__:aiCronExpression",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiNameQuery:"__lunora_admin__:aiNameQuery",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createAdminToken:"__lunora_admin__:createAdminToken",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",dropOutboxEntry:"__lunora_admin__:dropOutboxEntry",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",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",getScheduleOutbox:"__lunora_admin__:getScheduleOutbox",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",listAdminTokens:"__lunora_admin__:listAdminTokens",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",retryOutboxEntry:"__lunora_admin__:retryOutboxEntry",resolveIssue:"__lunora_admin__:resolveIssue",revokeAdminToken:"__lunora_admin__:revokeAdminToken",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",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",verifyAdminToken:"__lunora_admin__:verifyAdminToken",writeRow:"__lunora_admin__:writeRow"},ee=50,N=500,te=30,ne=200,c="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},re=e=>{const{[y]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...n}:{...n,...G(t)}},oe=(e,t)=>{if(!e.includes(c))return{columns:e,rows:t};const n=[];for(const i of t){const a=i[c],_=typeof a=="string"?x(a):void 0;if(_===void 0)return{columns:e,rows:t};const l=Object.fromEntries(Object.entries(i).filter(([u])=>u!==c));n.push({...l,...re(_)})}const r=e.filter(i=>i!==c),o=[],s=new Set(r);for(const i of n)for(const a of Object.keys(i))s.has(a)||(s.add(a),o.push(a));return{columns:[...r,...o],rows:n}},g=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,O=(e,t,n)=>Math.min(Math.max(e,t),n),q=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},He=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)$(r)||n.push({name:r,rowCount:q(e,d(r))});return n},U=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if($(t)||!U(e,t))throw new m("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},j=100,v=(e,t)=>{if(t>j)throw new m("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(j)} — remove some filters or narrow the search`)},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",se=new Set(["gt","gte","lt","lte"]),ae=e=>e.operator==="contains"?H(e.value)==="":se.has(e.operator)&&e.value==="",P=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new m("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},T=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(c);if(!(!r&&!o)){if(r){if(n.length>0)throw new m("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:d(e),params:[]}}return{expression:`json_extract(${d(c)}, ?)`,params:[P(e,n)]}}},ie=/^-?\d+$/u,R=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ie.test(r))throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},_e=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,le=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new m("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},ce=(e,t,n)=>{if(t.includes(e.column))throw new m("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(c))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new m("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=le(e.value),s=P(e.column,r),i=d(c),a=`SELECT 1 FROM json_each(${i}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${s}[0]`,s,...o.params,`${s}[1]`,`${s}[2]`,...o.params],sql:`CASE WHEN json_extract(${i}, ?) IS NOT '${F}' THEN EXISTS (${a}) WHEN json_extract(${i}, ?) IS 'arr' THEN EXISTS (${a}) ELSE 0 END`}},de=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return J(e)?JSON.stringify(X(e)):void 0}catch(t){throw new m("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",me=(e,t,n)=>{const r=de(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new m("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let s="'integer', 'real'";return typeof e.value=="string"?s="'text'":typeof e.value=="boolean"&&(s="'true', 'false'"),{params:[...n,...n,R(e,void 0)],sql:`(json_type(${d(c)}, ?) IN (${s}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const s=`json_type(${d(c)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,i=R(e,void 0);return o==="eq"?{params:[...n,...n,i],sql:`(${s})`}:{params:[...n,...n,...n,i],sql:`(${t} IS NOT NULL AND NOT (${s}))`}}},fe=/["\\\u0000-\u001F]/u,W=e=>fe.test(e)?"":e,B=(e,t,n,r)=>{const o=`'${F}'`,s=f=>`(instr(${f}, ${o}) > 0 OR instr(${f}, ${String.raw`'\u'`}) > 0)`,i=s(e),a=r.prefilter===void 0?[]:[r.prefilter],_=r.root===void 0?"":", ?",l=r.root===void 0?[]:[r.root],u=[...r.prefilter===void 0?[]:[g(e)],`EXISTS (SELECT 1 FROM json_tree(${e}${_}) AS j WHERE ${n.sql})`],E=[s(`t.${e}`),...r.prefilter===void 0?[]:[g(`t.${e}`)]],p=`(${u.join(" AND ")})`;return{params:[...a,...l,...n.params,...a,...l,...n.params],sql:`CASE WHEN ${i} THEN ${e} COLLATE BINARY IN (WITH RECURSIVE
|
|
2
|
-
__wf_framed AS MATERIALIZED (SELECT DISTINCT t.${e} COLLATE BINARY AS doc FROM ${t} AS t WHERE ${E.join(" AND ")}),
|
|
3
|
-
__wf_docs AS MATERIALIZED (SELECT doc, row_number() OVER () AS n FROM __wf_framed),
|
|
4
|
-
__wf_raw AS (SELECT d.n, j.id, j.parent, j.key, j.type, j.atom, j.value, j.fullkey FROM __wf_docs AS d, json_tree(d.doc${_}) AS j),
|
|
5
|
-
__wf_flags AS MATERIALIZED (SELECT n, parent AS id,
|
|
6
|
-
max(CASE WHEN typeof(key) = 'integer' AND key = 0 AND type = 'text' AND atom = ${o} THEN 1 ELSE 0 END) AS tagged,
|
|
7
|
-
count(CASE WHEN typeof(key) = 'integer' AND ((key = 0 AND atom = ${o}) OR (key = 1 AND atom = 'arr')) THEN 1 END) = 2 AS shaped
|
|
8
|
-
FROM __wf_raw WHERE parent IS NOT NULL GROUP BY n, parent),
|
|
9
|
-
__wf_tree AS MATERIALIZED (SELECT __wf_raw.*, coalesce(f.tagged, 0) AS tagged_parent, coalesce(f.shaped, 0) AS shaped_parent FROM __wf_raw LEFT JOIN __wf_flags AS f ON f.n = __wf_raw.n AND f.id = __wf_raw.parent),
|
|
10
|
-
__wf_steps AS MATERIALIZED (SELECT n, id, parent FROM __wf_tree WHERE typeof(key) = 'integer' AND key = 2 AND shaped_parent),
|
|
11
|
-
__wf_runs(n, id, k) AS MATERIALIZED (SELECT s.n, s.id, 1 FROM __wf_steps AS s LEFT JOIN __wf_steps AS p ON p.n = s.n AND p.id = s.parent WHERE p.id IS NULL UNION ALL SELECT c.n, c.id, r.k + 1 FROM __wf_runs AS r JOIN __wf_steps AS c ON c.n = r.n AND c.parent = r.id),
|
|
12
|
-
__wf_excluded AS MATERIALIZED (SELECT j.n, j.id FROM __wf_tree AS j LEFT JOIN __wf_runs AS p ON p.n = j.n AND p.id = j.parent WHERE typeof(j.key) = 'integer' AND j.key IN (0, 1) AND j.tagged_parent AND coalesce(p.k, 0) % 2 = 0),
|
|
13
|
-
__wf_framedMatches AS (SELECT d.doc FROM __wf_docs AS d JOIN (SELECT DISTINCT j.n FROM __wf_tree AS j LEFT JOIN __wf_excluded AS e ON e.n = j.n AND e.id = j.id WHERE ${n.sql} AND e.id IS NULL) AS m ON m.n = d.n)
|
|
14
|
-
SELECT doc FROM __wf_framedMatches) ELSE ${p} END`}},Ee=(e,t,n,r)=>{const o={params:[r],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")}`},s=B(t,e,o,{prefilter:W(r),root:n});return{params:[n,n,r,n,n,r,n,...s.params],sql:`CASE WHEN json_type(${t}, ?) IN ('text', 'integer', 'real') THEN ${g(`json_extract(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('true', 'false') THEN ${g(`json_type(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('array', 'object') THEN ${s.sql} ELSE 0 END`}},pe=(e,{expression:t,kind:n,pathParameters:r,physical:o,table:s})=>{const i=e.path??[];if(n==="bigint")throw new m("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const a=H(e.value);return i.length===0&&o?{params:[a],sql:g(t)}:i.length===0?Ee(s,d(c),r[0],a):{params:[...r,...r,a],sql:`(json_type(${d(c)}, ?) IN ('text', 'integer', 'real') AND ${g(t)})`}},Se=(e,t,n,r)=>{if(e.operator==="has")return ce(e,t,n);const o=e.path??[],s=T(e.column,t,o);if(s===void 0||ae(e))return;const{expression:i,params:a}=s,_=t.includes(e.column)||o.length>0?void 0:n?.[e.column];if(e.operator==="contains")return pe(e,{expression:i,kind:_,pathParameters:a,physical:t.includes(e.column),table:r});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:a,sql:`${i} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(o.length>0){const l=me(e,i,a);if(l!==void 0)return l}return{params:[...a,R(e,_)],sql:`${i} ${I[e.operator]} ?`}},ge=new Set(["date","timestamp"]),Ae=[`$.${y}`,`$."${y}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Ne=(e,t)=>{const n={params:[t],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${Ae}`};return B(d(c),e,n,{prefilter:W(t)})},Te=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,he=e=>{const t=Te.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const s=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(s).getUTCDate()!==o)return;let i;return o!==void 0?i=Date.UTC(n,(r??1)-1,o+1):r===void 0?i=Date.UTC(n+1,0,1):i=Date.UTC(n,r,1),{from:s,to:i}},ye=(e,t,n)=>t.map(r=>r===c?Ne(e,n):{params:[n],sql:g(d(r))}),be=(e,t,n)=>{const r=e.map(s=>({params:[n.from,n.to],sql:`(${d(s)} >= ? AND ${d(s)} < ?)`})),o=Object.keys(t??{}).filter(s=>!e.includes(s)&&ge.has(t?.[s]??""));return o.length>0&&e.includes(c)&&r.push({params:[JSON.stringify(o),n.from,n.to],sql:`EXISTS (SELECT 1 FROM json_each(${d(c)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`}),r},M=(e,t,n,r,o)=>{const s=[],i=[];if(n!==""&&t.length>0){const a=ye(e,t,n),_=he(n);_!==void 0&&a.push(...be(t,o,_)),s.push(`(${a.map(l=>l.sql).join(" OR ")})`),i.push(...a.flatMap(l=>l.params))}for(const a of r??[]){const _=Se(a,t,o,e);_!==void 0&&(s.push(`(${_.sql})`),i.push(..._.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},we=(e,t)=>{if(e===void 0)return;const n=T(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Pe=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??ee),1,N),o=Math.max(0,Math.trunc(t.offset??0)),s=d(n),i=b(e,s),a=t.search?.trim()??"",_=h=>{if(t.refs===void 0)return h;const w={};for(const D of h.columns){const k=t.refs[D];k!==void 0&&(w[D]=k)}return Object.keys(w).length>0?{...h,refs:w}:h},l=M(s,i,a,t.filters,t.columnKinds),u=we(t.orderBy,i),E=l===void 0?"":` WHERE ${l.where}`,p=u===void 0?"":` ORDER BY ${u.sql}`,f=l?.parameters??[],A=u?.params??[];v(n,f.length+A.length+2);let S;t.skipCount||(S=l===void 0?q(e,s):Number(e.exec(`SELECT COUNT(*) AS c FROM ${s}${E}`,...f).one().c));const Q=e.exec(`SELECT * FROM ${s}${E}${p} LIMIT ? OFFSET ?`,...f,...A,r,o).toArray();return _({...oe(i,Q),sqlColumns:i,total:S})},We=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??N),1,N),o=d(n),s=b(e,o),i=t.search?.trim()??"";for(const S of t.filters??[])if(T(S.column,s,S.path??[])===void 0)throw new m("BAD_REQUEST",`unknown column: ${S.column}`);const a=M(o,s,i,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new m("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],l=[];a!==void 0&&(_.push(a.where),l.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),l.push(t.after));const u=_.length===0?"":` WHERE ${_.join(" AND ")}`,E=t.after===void 0?"":" ORDER BY id";v(n,l.length+1);const p=e.exec(`SELECT id FROM ${o}${u}${E} LIMIT ?`,...l,r+1).toArray(),f=p.length>r,A=p.slice(0,r).map(S=>S.id);return{hasMore:f,ids:A}},Ie=(e,t,n,r)=>{const o=new Set(n.filter(i=>i!==c));if(!n.includes(c))return o;for(const i of Object.keys(r??{}))o.add(i);const s=e.exec(`SELECT ${d(c)} AS doc FROM ${t} LIMIT ?`,N).toArray();for(const{doc:i}of s){const a=typeof i=="string"?x(i):void 0;if(a!==void 0)for(const _ of Object.keys(a))o.add(_)}return o},Be=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),s=b(e,o);if(!Ie(e,o,s,t.columnKinds).has(n))throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=T(n,s);if(i===void 0)throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=O(Math.trunc(t.limit??te),1,ne),_=t.search?.trim()??"",l=M(o,s,_,t.filters,t.columnKinds),u=l===void 0?"":` WHERE ${l.where}`,E=l?.parameters??[];v(r,i.params.length*2+E.length+1);const p=e.exec(`SELECT ${i.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${i.expression} ORDER BY count DESC LIMIT ?`,...i.params,...E,...i.params,a+1).toArray(),f=p.length>a,A=s.includes(n)?void 0:t.columnKinds?.[n];return{truncated:f,values:p.slice(0,a).map(S=>({count:Number(S.count),value:_e(S.value,A)}))}},Qe=(e,t,n)=>{const r={},o=n.slice(0,N);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[s,i]of Object.entries(t)){if($(s)||!U(e,s))continue;const a=d(s),_=b(e,a);for(const l of i){const u=T(l,_);if(u===void 0)continue;const E=Y("sqlite",Z(K.raw(u.expression),o,!1)),p=e.exec(`SELECT id, ${u.expression} AS ref FROM ${a} WHERE ${E.sql}`,...u.params,...u.params,...E.params).toArray();for(const f of p)r[f.ref]?.push({column:l,id:f.id,table:s})}}return{references:r,storageColumns:t}},Ge=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,s)=>{const i=Object.values(o.subs??{}).map(a=>({args:a.args,functionPath:a.functionPath,table:a.table}));return{admin:o.admin===!0,id:s,subscriptions:i}}),r=n.reduce((o,s)=>o+s.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},Re=20,Je=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ke=()=>({drains:0,pairsSkipped:0}),Ve=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ye=(e,t,n)=>({run:e.run+t,served:e.served+n}),Ze=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),ze=(e,t=Re)=>{const n=new Map,r=new Map,o=e.filter(a=>a.authenticated!==!1);for(const a of o){for(const _ of Object.values(a.shapes??{})){const l=_.name??"(unknown shape)";n.set(l,(n.get(l)??0)+1)}for(const _ of a.whispers??[])r.set(_,(r.get(_)??0)+1)}const s=[...[...n].map(([a,_])=>({kind:"shape",subscribers:_,topic:a})),...[...r].map(([a,_])=>({kind:"whisper",subscribers:_,topic:a}))];return s.sort((a,_)=>_.subscribers-a.subscribers||a.topic.localeCompare(_.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:o.length}};export{Ue as ADMIN_FUNCTIONS,Fe as ADMIN_FUNCTION_PREFIX,Re as DEFAULT_FANOUT_TOPIC_LIMIT,qe as FLAGS_FUNCTION_PREFIX,N as MAX_PAGE_SIZE,xe as RELATION_FUNCTION_PREFIX,Je as createFanoutCounters,Ke as createGlobalPollCounters,Xe as createShapeProbeCounters,he as datePrefixRange,Be as facetColumn,Qe as findStorageReferences,$ as isInternalTableName,ae as isVacuousFilterClause,He as listTables,Pe as readTablePage,Ze as recordFanoutPass,Ve as recordGlobalPollPass,Ye as recordShapeProbePass,We as selectMatchingIds,ze as summarizeFanoutTopics,Ge as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{q as $t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as Gn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ct,selectIndexForGroupBy as jn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as ji,backfillRankIndexes as Hi,backfillSearchIndexes as Ki}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Qi,applyCdcChanges as Vi,bumpCdcEpoch as Ji,cdcCanVouchFor as zi,cdcForkedError as Yi,cdcSeqLeavingRows as Xi,cdcTouchesTables as Zi,cdcTrimmedError as es,compactCdcDocs as ts,cursorBelowRetainedFloor as ns,minCdcReplayableSeq as os,minCdcSeq as rs,readCdcChangeKeys as is,readCdcChanges as ss,readCdcCursor as cs,readCdcEpoch as as,trimCdcChanges as ds}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as Zn}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as eo,j as ht,D as ie,r as xe,W as to,k as le,b as Ue,A as at,a as Oe,m as ue,e as fe,s as no,t as oo,u as ro,i as io,q as Gt,h as pn,g as so}from"./do-sql-105TONaE.mjs";import{renderSql as gn,unionAll as yn,WORKERD_SQLITE_LIMITS as mn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as co,u as ao}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as lo,boundingBoxGeohashes as uo,haversineMeters as fo,pointInBoundingBox as ho}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as wo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as po,assertPatchAllowed as go,operatorFields as yo,readPatchField as jt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as mo,encodeCursor as wt,nullsOrderSuffix as Eo,normalizeOrderKeys as Ht,uniqueIndexFields as $o,buildSeekWhere as Ro,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as En}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as vo,encodePartitionKey as _o,RANK_TIEBREAK as To,rankPivotConditionSql as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Io,withUnknownIndexKeys as xo,indexKeysForRow as bo,buildIndexRange as Co}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Mo,isPushableWhere as Do}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ko,findRelated as Lo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as dt,findManyPage as Fo,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as pt,resolveWith as Uo,relationHooks as Oo,applyOnDelete as Go,fanOutScalarCounts as jo}from"./applyInsertDefaults-BJ4dP3OL.mjs";import{guardWriter as Ho}from"./RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{mayHoldProjectedValue as Ko}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as No}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Qo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as us,migrateClientWatermark as fs,readClientWatermark as hs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ps,readIdempotent as gs,trimIdempotent as ys,writeIdempotent as ms}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as Ss,selectShapeRows as vs}from"./selectShapeMembers-Dqx_m7BF.mjs";const Vo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Jo=()=>new $("INVALID_CURSOR","invalid cursor"),Yt=16,Xt=8,z=1024,Rt=(n,r)=>r.query(n),zo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const E of n)(u?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Yo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Xo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new $("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Xt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new $("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const E=Rt(u,o).length;if(E>Yt)throw new $("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Yt)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Zo=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},er=n=>Math.min(n.offset+n.numItems+1,z),tr=n=>btoa(`search:${String(n)}`),nr=n=>{let r;try{r=Vo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},or=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?nr(n.cursor):0;if(o===void 0)throw Jo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},rr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?tr(o):null,isDone:!s,page:n.slice(r.offset,o)}},ir=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},$n=500,Rn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??$n},Sn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},sr=32,cr=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Qe(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Qe(ht(n)),rangeTypeGuard:(n,r)=>Qe(eo(n,r)),serialize:Ce},ar=n=>n===void 0?"":Eo(n==="first"),_n=n=>{const r=n.map(o=>`${ht(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${ht("id")} ${mo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},dr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Tn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),lr=n=>{const r=Tn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},ur=(n,r)=>{const o=n.order,s=lr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:Tn(n),uniqueBy:$o(r.indexes,c)}):Ht([{_creationTime:o}],c)},fr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[dr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},hr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,sr):n.want},gt=(n,r,o,s,c,u,g)=>{const E=ur(s,o),y=_n(E),d=[],{filters:b,want:_}=u;let v=u.cursor??void 0,x=hr(u);if(_===0)return{documents:d,orderKeys:E};for(;;){const W=Z(fr(s,E,v,u.endCursor),Ye,ze),q=vn(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,q.text,...q.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),b.every(ee=>ee(U))&&d.push(U)===_)return{documents:d,orderKeys:E};if(x===void 0||B.length<x)return{documents:d,orderKeys:E};v=wt(U,E),x=Math.max(x,Math.min(x*2,cr))}},wr=(n,r,o,s,c,u,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=gt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?wt(B,q):null}}const{documents:d,orderKeys:b}=gt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),_=d.length>y,v=_?d.slice(0,y):d,x=v.at(-1);return{continueCursor:_&&x?wt(x,b):null,isDone:!_,page:v}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),pr=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Zt=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),yr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),mr="SELECT changes() AS changed",en=new Map,Er="",$r=n=>{const r=JSON.stringify(n),o=en.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${Er}`),{sql:c}=gn("sqlite",a`${yn(s)} LIMIT 1`);return en.set(r,c),c},Rr=(n,r)=>r.map(()=>n),Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vr=n=>{if(!Sr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},yt=n=>{if(n.includes("\0"))throw new $("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},_r=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?pt(n,u,s)._id:u._id;typeof g=="string"&&yt(g)}},tn=50,je=Math.floor(mn.boundParams/3),nn=mn.boundParams,Tr=128,Ve=n=>new $("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Sn(n,Rn(r,o,Ve),o,Ve)},on=async(n,r,o,s,c)=>{const u=Rn(s,c,Ve),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Sn(Math.max(await n.count(r,{where:o}),g.length),u,c,Ve),g},Ar=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ir=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},xr=(n,r,o,s,c)=>{const u=Rt(o.query,$t(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),E=`${g}__vocab`,y=u.length-1,d=u.map((q,B)=>{const U=Yo(q,B===y),j=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(B))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(E)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),b=u.map((q,B)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(B))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),_=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${yn(d)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(b.map(q=>a`${q} > 0`),a` AND `)}`,v=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${_}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;v.length>0&&(x=a`${x} WHERE ${a.join(v,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const W=[];for(const q of K(n,x)){const B=pn(q);if(B){const U=q.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},br=(n,r,o,s,c)=>{const u=$t(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const E=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;E.length>0&&(y=a`${y} WHERE ${a.join(E,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ir(s)))}`;const d=K(n,y).toArray(),b=[];for(const _ of d){const v=pn(_);if(!v)continue;const x=zo(Pn(v,o.definition),g);x>0&&b.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return b.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),b.slice(0,s).map(_=>({document:_.doc,score:_.score}))},lt=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Cr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c.sw,".within() sw corner",r,o.indexName),lt(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .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 o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Mr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Dr=(n,r)=>{const o=Mr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=fo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return ho(o,r.within)?{creationTime:s,distance:0}:void 0},kr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?lo(o.near.point,o.near.radiusMeters):uo(o.within),u=so(r,o.indexName),g=c.map(_=>a`(g.${a.identifier("__geohash__")} >= ${_} AND g.${a.identifier("__geohash__")} < ${`${_}{`})`),E=[a`(${a.join(g,a` OR `)})`];s&&E.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(E,a` AND `)}`,d=K(n,y).toArray(),b=[];for(const _ of d){const v=xe(_),x=v?Dr(v,o):void 0;v&&x&&b.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return b.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),b},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Lr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,E=kr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},rn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:E}=o;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,d=Lr(n,r,E,y?void 0:u,s,g);return y?In(d,c,u,b=>b.document):d},sn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ko(s))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:E,relation:y}=c,d=`__rel_${String(r)}`,b=o.at(-1)??E;r+=1,n(y.table,G);const _=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Qe(`${Gt(d,v)} = ${Gt(b,_)}`);o.push(d);const W=Z(u,s,ze);o.pop();const q=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(d)," WHERE ",q,")");return g?be("NOT ",B):B}};return s};class Br extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wr=/\s/u,qr=String.fromCodePoint(0),cn=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Wr.test(o)||o.includes(qr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const y=Ae(E.softDeleteMode,void 0),d=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,ue):void 0},_=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,Ye,ze):void 0},v=()=>[...d.inMemoryFilters,...d.verifyFilters];let x=0;const W=S=>{const{search:M}=d;if(!M)throw new $("INTERNAL","runSearchFetch called without a staged search");Nn(ro(n),o,E);const L=d.inMemoryFilters.length>0,F=ir(L?void 0:S),k=io(n);if(k&&!Qn(n,o,M.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=b(),te=k?xr(n,o,M,F,pe):br(n,o,M,F,pe);!L&&S===void 0&&Zo(te);const ge=v();return x=te.length,ge.length>0?In(te,ge,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=or(S);return rr(q(er(M)),M)},U=()=>{if(d.search||d.geo||d.indexName===void 0){c(void 0);return}c(Co(o,d.indexName,d.indexFields,d.sqlConditions,Ce))},j=S=>{U();let M=0;const L=(()=>{if(d.search){const F=q(S);return M=x,F}return d.geo?rn(n,o,d,b(),v(),S,F=>{M=F}).map(F=>F.document):gt(n,o,E,d,_(),{filters:v(),selective:d.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return u(Math.max(M,L.length)),L},ee=()=>{if(!d.search&&!d.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const M=(()=>{if(d.search){const L=W(void 0);return S=x,L}return rn(n,o,d,b(),v(),void 0,L=>{S=L})})();return u(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=xn(n,r,o,s,c,u,{...d,indexFields:[...d.indexFields],inMemoryFilters:[...d.inMemoryFilters],sqlConditions:[...d.sqlConditions],verifyFilters:[...d.verifyFilters]});if(d.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Tr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Mo(S);return M!==void 0&&Do(M,E.shape)?(d.pushedWhere=Q(d.pushedWhere,M),d.verifyFilters.push(S)):d.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return d.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(U(),d.search){const F=B(S);return u(F.page.length),F}if(d.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=wr(n,o,E,d,S,_(),{all:v(),selective:d.inMemoryFilters.length>0},F=>{M+=F});return u(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Br(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(E.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(d.geo=F,M(Cr(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=E.indexes.find(F=>F.name===S);if(!L)throw new $("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),d.indexName=S,d.indexFields=L.fields,M&&M(Ar(d)),N},withSearchIndex(S,M){const L=(E.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(d.search=F,M(Xo(F,o,$t(L.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,r,o,s)=>{const c=o;for(const[u,g]of oo(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},an=5,dn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],Ke=n=>ln.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!ln.includes(r))):n,Pr=/unique constraint failed/i,Ur=n=>n instanceof Error&&Pr.test(n.message),Or=/string or blob too big/iu,Gr=(n,r)=>{if(!(!(n instanceof Error)||!Or.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Ur(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Gr(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,mr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,r,o,s,c,u,g)=>{const E=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],x=s[_],W=x?.direction==="desc"?"desc":"asc",q=v===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:Ao(v,u[_],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<_;j+=1)B.push(a`${a.identifier(o[j])} IS ${u[j]}`);B.push(q);const[U]=B;E.push(B.length===1&&U!==void 0?U:a`(${a.join(B,a` AND `)})`)}const y=E.length>0?a.join(E,a` OR `):a`1 = 0`,d=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:d.c,total:b.c}},jr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:E,op:y}of r.get(g)??[]){if(E===s||zt(n,E,y))return!0;c.has(E)||(c.add(E),u.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||zt(n,s,"delete")||o(s)).map(([s])=>s))},Hr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ft=new WeakMap,Kr=(n,r)=>{let o=ft.get(r.tables);if(!ft.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ft.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Nr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,E=ao(u);typeof g!="string"?r.recordReadBytes(E):o===void 0?r.recordDocumentRead(`${g}\0${String(E)}`,E):r.recordDocumentRead(`${o}\0${g}`,E)}}},Qr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),d=o===void 0?void 0:Kr(c,o);let b=!1;const _=v=>{Nr(v,r,d)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})_([x]),v.push(x);return v},g.one=()=>{b=!0;try{const v=E();return _([v]),v}finally{b=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})b||_([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===to?c:Reflect.get(c,u,c)})},Vr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Jr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=co(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},Je=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},bn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Jr.get(c);return(...E)=>{const y=Reflect.apply(u,s,E);return g!==void 0?Promise.resolve(y).then(d=>(Je(d,g,r,o),d)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?bn(y,r,o):y}}}),zr=new Set(["findFirst","findFirstOrThrow","findMany"]),Yr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>En(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:u(g.page)}:u([g])[0]}},fn=256,Et=4096,Xr=1024*1024,Zr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,E=fn,y=0;for(;;){const d=await n([r[0],{...c,cursor:g,limit:E},...r.slice(2)]);if(Array.isArray(d))return Je(d,"rows",o,s),[...u,...d];const b=s.headroom().readBytes;if(Je(d,"page",o,s),u.push(...d.page),d.isDone||typeof d.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=d.continueCursor,y+=s.headroom().readBytes-b,E=y>0?Math.min(Et,Math.max(fn,Math.floor(Xr*u.length/y))):Et}},ei=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>bn(Reflect.apply(c,o,g),String(g[0]),r);const u=Vr.get(s);return u===void 0?c:async(...g)=>{const E=zr.has(s)?Yr(g):void 0;let y=E?.args??g;const d=String(g[0]),b=y[1],_=s==="findMany"&&typeof b?.endCursor=="string",v=s==="findMany"&&typeof b?.limit!="number"&&!_;if(_&&typeof b.limit!="number"&&(y=[y[0],{...b,limit:Et},...y.slice(2)]),v){const W=await Zr(q=>Reflect.apply(c,o,q),y,d,r);return E===void 0?W:E.project(W,u)}const x=await Reflect.apply(c,o,y);return Je(x,u,d,r),E===void 0?x:E.project(x,u)}}}),hn=new WeakMap,wn=new WeakMap,ti=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=hn.get(n)??{value:void 0},u=wn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};hn.set(e,c),wn.set(e,u),g=ti(e)}return g},y=Qr(n.sql,s,n.schema),{schema:d}=n,b=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(d.tables,e))throw new $("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=ko(d),x=new Map;for(const e of v){const t=i=>(d.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new $("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},q=qo(d,n.inTransaction),B=jr(d),U=Hr(d),j=()=>n.inTransaction?.()===!0,ee=e=>d.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=d.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(Io(w))),l.push(...xo(i,bo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),M=e=>{Ut(d.tables[e])&&S(Vt,Vt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:me}=n,Ee=n.clock??(()=>Date.now()),St=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,$e=ei(n.globalDb,s),ce=n.auth??{identity:null,userId:null},_t=n.cdc??!1,Ze=vt,Cn=No({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Re=(e,t,i,l)=>{_t&&!Ut(d.tables[e])&&Vn(y,Ee(),e,t,i,l)},Tt=(e,t,i,l)=>{const w=d.tables[e];if(w?.dropStalePatchesMode!==!0||!_t)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=yo(w,i);return Object.keys(Ke(i)).some(m=>!h.has(m)&&Pt(jt(f,m))!==Pt(jt(l,m)))},ae=e=>d.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},It=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return b({key:p,op:"insert",row:{...i,_id:p},table:t}),p},xt=(e,t)=>At(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),xt(e,t)),Mn=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:d,tableName:t}),Dn=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),jo((R,P)=>w.count(R,P),e,t,i,l);const p=d.tables[e];if(!p)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},m=Q(Q(h,l),f),A=await De(m,e,void 0),C=Z(A,ue),I=fe(t);let T=a`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;C&&(T=a`${T} WHERE ${C}`),T=a`${T} GROUP BY ${I}`;const D=K(y,T).toArray();return new Map(D.map(R=>[R.__fk__,R.count]))},kt=new Set;for(const[e,t]of Object.entries(d.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>tn)throw u.value-=1,new se(`trigger recursion exceeded ${String(tn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qo({ctx:Bn,event:i,op:t,schema:d,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=Xn({broadcast:b,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>me?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:d,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.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})},Bt=e=>Object.entries(d.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?$e:void 0,ot=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Bt(t);for(let l=0;l<i.length;l+=nn){const w=i.slice(l,l+nn),[p]=he(y,$r(w),...Rr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:le(m??{}),row:h,tableName:f}}},Wt={assertRankPartitionLocal:Ft,ensureRankBackfilled:nt,onRead:k,rowToDocument:xe,schema:d,sql:y},kn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Ln=(e,t,i,l)=>Tt(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Mn:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:d,tableName:e}),m=Mt?Fr(l):Ye,A=Z(h,m,ze),C=vn(e,A,_n(f),w);return{limit:p,orderKeys:f,statement:C}},O={system:Cn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const R=Kn(l.aggregateIndexes,t.op,t.field,t.where);if(R){tt(e,R.index);const P=it(R.index.by??[],R.key),Y=rt(e,R.index.name),X=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${P}`).toArray()[0];return st(t.op,X)}}sn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(f,ue),A=Pe(t.op),C=fe(t.field);let I=a`SELECT ${a.raw(A)}(${C}) AS value FROM ${a.identifier(e)}`;m&&(I=a`${I} WHERE ${m}`);const D=K(y,I).toArray()[0]?.value;return D??null},asId(e,t){const i=cn(d,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=Gn(t);if(w.restrictsCounts)throw new ct(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!m){const T=Hn(l.aggregateIndexes,w.where);if(T){tt(e,T.index);const D=it(T.index.by??[],T.key),R=rt(e,T.index.name),P=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(R)} WHERE ${Oe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(h,ue);let C=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(C=a`${C} WHERE ${A}`),K(y,C).one().count},async delete(e,t,i){_(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const T=Te(e);T&&await ot(T,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=d.tables[f],m=i?.hard===!0,A=!m&&h?.softDeleteMode?h:void 0,C=A?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Go({deletedId:t,deletedReference:T=>p[T],findHolders:async(T,D,R,P)=>(await et(T).findMany(T,{...P,includeDeleted:m,where:{[D]:R}})).page,onCascade:(T,D)=>et(T).delete(T,D,i),onRestrict:T=>{throw new se(T,"restrict")},onSetNull:(T,D,R)=>et(T).patch(T,D,{[R]:null}),schema:d,tableName:f}),Se(f),ve(f),A&&C){const T={[C]:Ee()},D={...p,...ee(f),...T,_id:t};ut(A,T,D,ce),Ne(y,f,Zt(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const R=N(f,p,D);me?.invalidate(f,t,R),Re(f,t,"update",D),b({indexKeys:R,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,yr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const I=N(f,p);me?.invalidate(f,t,I),Re(f,t,"delete"),b({indexKeys:I,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??$n),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:i})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(w===void 0?O.delete(e,m,l):ot(w,e,[m],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){_(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await on(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return ot(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new wo(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,Zn),i.findMany(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,l,t,k),m=he(y,h.text,...h.params).toArray();w&&s?.recordRead(m.length);const A=[];for(const I of m){const T=xe(I);T&&(A.push(T),!w&&typeof T._id=="string"&&k(e,T._id))}const C=Fo(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:f});return t.with&&await Uo({fetcher:xt,groupedCounter:Dn,parents:C.page,...Oo(t),schema:d,tableName:e,with:t.with}),{...C,page:En(C.page,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(M(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Bt(t))M(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!m){const R=jn(l.aggregateIndexes,w.op,w.field,t.by,t.where),P=R===void 0?0:Object.keys(R.partial).length,Y=R?.index.by?.length??0;if(R&&(P===0||P===Y)){tt(e,R.index);const X=rt(e,R.index.name),V=Object.keys(R.partial),de=[];if(V.length===(R.index.by??[]).length&&V.length>0){const Be=it(R.index.by??[],R.partial),We=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...R.partial},value:st(w.op,We[0])}),de}const Wn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)}`).toArray();for(const Be of Wn){const We=Un(JSON.parse(Be.key));de.push({key:We,value:st(w.op,Be)})}return de}}for(const R of[...t.by,w.field]){if(R===void 0)continue;const P=R===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${R}" } })`:`groupBy(${e}, { by: [..."${R}"] })`;sn(l,R,P)}const A=Z(h,ue),C=t.by.map(R=>a`${fe(R)} AS ${a.identifier(R)}`);if(w.op==="count")C.push(a`COUNT(*) AS value`);else{const{field:R}=w;if(R===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);C.push(a`${a.raw(Pe(w.op))}(${fe(R)}) AS value`)}let I=a`SELECT ${a.join(C,a`, `)} FROM ${a.identifier(e)}`;A&&(I=a`${I} WHERE ${A}`),I=a`${I} GROUP BY ${a.join(t.by.map(R=>fe(R)),a`, `)}`;const T=K(y,I).toArray(),D=[];for(const R of T){const P={};for(const X of t.by)P[X]=no(l.shape[X],R[X]??null);const{value:Y}=R;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return It(l,e,t,i,!0);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,pt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(vr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?(yt(f._id),h=f._id):h=St();const m=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),A={...f,...ee(e),_creationTime:m,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:h,op:"insert",table:e}),p||W(e,A),Se(e),ve(e),mt(y,e,pr(e),[h,m,le(A)]),Lt(e,h,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:h,op:"insert",table:e}),await ye({doc:A,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const m=[];_r(d.tables[e],t,i?.allowExplicitId,ce);for(const A of t)J(A);for(const A of t){const C=await l.insert(e,A,{allowExplicitId:i?.allowExplicitId});b({key:C,op:"insert",row:{...A,_id:C},table:e}),m.push(C)}return m}const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let m=0;m<t.length;m+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((m,A)=>{const C=pt(w,m,ce),I=f===void 0?C:Ge(f,C,{supplied:m}),T=i?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;T!==void 0&&yt(T);const D=T??St(),R=i?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Ee(),P={...I,...p[Math.floor(A/je)],_creationTime:R,_id:D};return{creationTime:R,document:P,id:D}});for(const m of h)J(m.document);for(let m=0;m<h.length;m+=je){const A=a.join(h.slice(m,m+je).map(I=>a`(${I.id}, ${I.creationTime}, ${le(I.document)})`),a`, `),C=gn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${A}`);mt(y,e,C.sql,C.params)}for(const{document:m,id:A}of h)Lt(e,A,m),await ge({doc:m,id:A,op:"insert",table:e});return h.map(m=>m.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(m){if(l&&m instanceof se&&m.kind==="unique")w.push(null);else throw m}return w},normalizeId(e,t){return cn(d,e,t)},async patch(e,t,i,l){_(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);if(k(h,t),dn("patch",i),Tt(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const A=po(m,i,f),C={...f,...Ke(A),...ee(h),_id:t};ut(m,A,C,ce);const I=Ge(m,C,{only:new Set(Object.keys(A)),previous:()=>f,tolerateStoredNull:!0});go(l,f,I),ne(h,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:f,table:h}),W(h,I,f),Se(h),ve(h),Ne(y,h,Zt(h),[le(I),t,p]),Fe(h,t,I,f),Le(h,t,I),ke(h,f,I),_e(h,t,f,I);const T=N(h,f,I);me?.invalidate(h,t,T),Re(h,t,"update",I),b({indexKeys:T,key:t,op:"update",row:I,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:f,table:h}),await ye({doc:I,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=an;w+=1){const p=await Fn(e,t,i,w<an,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){_(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await on(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Lo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):xn(y,d,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(te(e,t,"rank"),l)return k(e,G),l.rank(e,t,i);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new ct(e);k(e,G),nt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),m=p.sortBy.map((V,de)=>Qt(de)),A=m.map(V=>Me(V)).join(", "),C=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[I]=C;if(I===void 0)return null;let T=I.__partition__;const D=Q(i.baseWhere,i.where);dt(D,d,e,"rank");const R=vo(p,D);if(R){const V=_o(p.partitionBy??[],R);if(V!==T)return null;T=V}const P=m.map(V=>I[V]),{before:Y,total:X}=un(y,h,m,p.sortBy,T,P,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(m=>m.name===t);if(!w)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new ct(e);k(e,G),nt(e,w);const p=Nt(e,w.name),f=w.sortBy.map((m,A)=>Qt(A)),h=w.sortBy.map((m,A)=>Ce(i.sortValues[A]??null));return un(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage");const l=H(e,"rankPage");if(te(e,t,"rank"),l)return k(e,G),l.rankPage(e,t,i);const{continueCursor:w,hasMore:p,rows:f}=Ot(Wt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Ot(Wt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const l=d.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){_(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const P=Te(e);if(P){J(i),await P.replace(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);dn("replace",i);const A=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,C=typeof f._creationTime=="number"?f._creationTime:void 0,I=A??C??Ee(),T={...i,...ee(h),_creationTime:I,_id:t};ut(m,i,T,ce);const D=l?.allowExplicitId===!0,R=Ge(m,T,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...R},id:t,op:"update",previous:f,table:h}),D||W(h,R,f),Se(h),ve(h),Ne(y,h,gr(h),[I,le(R),t,p]),Fe(h,t,R,f),Le(h,t,R),ke(h,f,R),_e(h,t,f,R),me?.invalidate(h,t,N(h,f,R)),Re(h,t,"update",R),b({indexKeys:N(h,f,R),key:t,op:"update",row:R,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:R,id:t,op:"update",previous:f,table:h}),await ye({doc:R,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(d.tables).filter(([h,m])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!d.tables[h])throw new $("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const m=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:w}}},Bn={db:O,scheduler:vt};return n.enforceRls===!0?Ho(O,d,(e,t)=>re(e,t)?.tableName,v):O};export{Qi as CDC_LOG_TABLE,ps as IDEMPOTENCY_TABLE,Br as NotUniqueError,us as advanceClientWatermark,Vi as applyCdcChanges,dn as assertNoExplicitUndefined,yt as assertStorableRowId,vr as assertValidClientId,ji as backfillAggregateIndexes,Hi as backfillRankIndexes,Ki as backfillSearchIndexes,Ji as bumpCdcEpoch,zi as cdcCanVouchFor,Yi as cdcForkedError,Xi as cdcSeqLeavingRows,Zi as cdcTouchesTables,es as cdcTrimmedError,ts as compactCdcDocs,ti as createShardCtxDb,ns as cursorBelowRetainedFloor,Qr as meterReadBytes,fs as migrateClientWatermark,os as minCdcReplayableSeq,rs as minCdcSeq,cn as normalizeIdStructurally,is as readCdcChangeKeys,ss as readCdcChanges,cs as readCdcCursor,as as readCdcEpoch,hs as readClientWatermark,gs as readIdempotent,$s as runShardMigrations,Ss as selectShapeMembers,vs as selectShapeRows,Ke as stripReservedPatchFields,ds as trimCdcChanges,ys as trimIdempotent,ms as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as f}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const p=200,v=(e,o)=>{const t=r=>{const a=e.tables[r];return a!==void 0&&a.shardMode?.kind!=="global"};return(o&&o.length>0?[...o]:Object.keys(e.tables)).filter(r=>t(r))},E=async function*(e,o,t=p){let r=null,a=!1;for(;!a;){const n=await e.findMany(o,{cursor:r,includeDeleted:!0,limit:t});for(const s of n.page)yield{doc:s,table:o};r=n.continueCursor,a=n.isDone||r===null}},j=async function*(e,o,t){const r=v(o,t.tables),a=t.batchSize??p;for(const n of r)yield*E(e,n,a)},O=new Set(["_creationTime","_id"]),_=(e,o)=>{for(const[t,r]of Object.entries(e.shape)){const a=o[t];if(a===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(a)}catch(s){const i=s instanceof Error?s.message:String(s);return`field "${t}": ${i}`}}},A=(e,o,t)=>{const r=e.tables[o];if(!r)return`unknown table: ${o}`;if(r.shardMode?.kind==="global")return`table "${o}" is a global (.global()) table and is not importable through the shard import path`;const a=Object.fromEntries(Object.entries(t).filter(([n])=>!O.has(n)));for(const n of Object.keys(a))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${o}"`;return _(r,a)},y=async(e,o,t)=>{if(e.lookupById){const r=await e.lookupById(t);return r===null?void 0:r.tableName}return await e.get(o,t)===null?void 0:o},R=async(e,o,t)=>{try{return await y(e,o,t)}catch{return}},h=e=>u in e?Object.fromEntries(Object.entries(e).filter(([o])=>o!==u)):e,m=(e,o,t)=>{const{table:r}=o;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:t,message:"row is missing `table`",table:r};if(!o.doc||typeof o.doc!="object"||Array.isArray(o.doc))return{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r};const a=A(e,r,h(o.doc));return a===void 0?void 0:{code:"VALIDATION_ERROR",line:t,message:a,table:r}},g=(e,o,t)=>{const r=e.tables[o.table];return r===void 0?{code:"BAD_ROW",line:t,message:`unknown table: ${o.table}`,table:o.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:t,message:`table "${o.table}" is a global (.global()) table and is not importable through the shard import path`,table:o.table}:typeof o.doc?._id=="string"?void 0:{code:"BAD_ROW",line:t,message:"a delete row needs the `_id` to delete",table:o.table}},S=async(e,o,t,r)=>{const a=g(o,t,r);if(a!==void 0)return{error:a,kind:"error"};const n=t.doc._id;try{const s=await y(e,t.table,n);return s===void 0?{kind:"absent"}:s!==t.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${s}", not "${t.table}"`,table:t.table},kind:"error"}:(await e.delete(t.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(s){const{body:i}=f(s,{fallbackCode:"DELETE_FAILED"});return{error:{code:i.code,line:r,message:i.message,table:t.table},kind:"error"}}},I=async(e,o,t,r,a)=>{const n=m(o,t,r);if(n!==void 0)return{error:n,kind:"error"};const{table:s}=t,i=h(t.doc),d=typeof i._id=="string"?i._id:void 0,l=d===void 0?void 0:await R(e,s,d);if(l!==void 0&&l!==s)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(d)}" already belongs to table "${l}"`,table:s},kind:"error"};if(l===s&&d!==void 0){if(a!=="replace")return{kind:"conflict"};try{const c={...i};return delete c._id,await e.replace(s,d,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:b}=f(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:b.code,line:r,message:b.message,table:s},kind:"error"}}}try{return await e.insert(s,i,{allowExplicitId:!0}),{kind:"inserted",table:s}}catch(c){const{body:b}=f(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:b.code,line:r,message:b.message,table:s},kind:"error"}}},k=(e,o,t)=>e.op==="delete"?t?void 0:{code:"BAD_ROW",line:o,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:o,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},D=async(e,o,t,r,a,n)=>{const s=k(t,r,n);return s!==void 0?{error:s,kind:"error"}:t.op==="delete"?S(e,o,t,r):I(e,o,t,r,a)},w=async(e,o,t)=>{const r=[],a={};let n=0,s=0,i=0,d=(t.startLine??1)-1;for(const l of t.rows){if(d+=1,t.dryRun===!0){const b=k(l,d,t.deletes===!0)??(l.op==="delete"?g(o,l,d):m(o,l,d));b!==void 0&&r.push(b);continue}const c=await D(e,o,l,d,t.onConflict??"skip",t.deletes===!0);switch(c.kind){case"absent":break;case"conflict":{n+=1;break}case"deleted":{s+=1;break}case"error":{r.push(c.error);break}case"replaced":{i+=1;break}default:a[c.table]=(a[c.table]??0)+1}}return{conflicts:n,deleted:s,errors:r,inserted:a,replaced:i}},B=e=>{const o=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:o}},L=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},x=e=>{const o=Array.isArray(e.rows)?e.rows:[],t=[];for(const a of o){if(!a||typeof a!="object")continue;const n=a;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){t.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}t.push({doc:n.doc,...L(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:t,startLine:r}};export{j as exportShardRows,w as importShardRows,B as parseExportShardArgs,x as parseImportShardArgs,v as selectExportTables,A as validateImportRow};
|