@lunora/shard-engine 1.0.0-alpha.215 → 1.0.0-alpha.217
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 +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NotUniqueError-CPAltXX4.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-IBU5qtmg.mjs → defineEngineContractSuite-DfQt-wuj.mjs} +1 -1
- package/dist/packem_shared/{sql-engine.d-CMrMcDfK.d.mts → sql-engine.d-D-Bc5Xkd.d.mts} +4 -0
- package/dist/packem_shared/{sql-engine.d-CMrMcDfK.d.ts → sql-engine.d-D-Bc5Xkd.d.ts} +4 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.d.ts +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-C_IDBwvG.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DfQt-wuj.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DatabaseWriterLike, d as SchemaLike, T as TriggerContextLike, e as TriggerEventLike, f as TriggerOpLike, g as TriggerTimingLike, S as SqlExec, h as SearchIndexDefinitionLike, W as WhereInput, i as RestrictableQueryOptions, j as SchedulerLike, A as AggregateIndexDefinitionLike, k as AggregateOp, l as RankIndexDefinitionLike, M as MutationDelta, m as TableDefinitionLike, n as RankDirection, o as RankPageRowKey, p as RankPageOptions, C as ColumnMetaLike, q as SortDirection, P as PatchWriteOptions, O as OrderKey, r as OrderByInput, V as ValidatorLike, K as KeyRange, s as RelationEdge, t as RelatedStart, u as RelatedOptions, v as RelatedPage, w as KeyedRelationDefinitionLike, Q as QueryArgs, x as QueryPage, y as ServerDefaultContextLike, z as ResolveWithOptions, B as SocketAttachment, E as ResolvedShape, F as ShapeSubscriptionQuery, G as ShardSocketLike, H as SubscriptionIdentity, I as TransactionLimits, a as SqlCursor, J as IndexKeyEntry } from "./packem_shared/sql-engine.d-
|
|
2
|
-
export { type L as AggregateOptions, type N as AggregateResult, type U as BroadcastDelta, type X as CacheEntry, type Y as Clock, Z as CompanionMemo, type _ as CountArgs, type $ as CrossShardCountArgs, type a0 as CrossShardReadArgs, type a1 as CtxDbOptions, a2 as DEFAULT_TRANSACTION_LIMITS, type a3 as FanOutBudget, type a4 as FieldOperators, type a5 as GeoFilterBuilderLike, type a6 as GeoIndexDefinitionLike, type a7 as GeoScoredDocument, type a8 as GroupByEntry, type a9 as GroupByOptions, type aa as GuardableSchema, type ab as IdGenerator, type ac as IndexDefinitionLike, type ad as IndexRangeBuilderLike, type ae as KeyedRelationWriteInfo, type af as LifecycleDispatchInfo, type ag as LifecycleEvent, type ah as NestedWith, ai as NotUniqueError, type aj as NullPlacement, type ak as OnDeleteActionLike, type al as PaginationOptions, type am as PatchVerifier, type an as QueryPlan, ao as RELATION_EXISTS_KEY, type R as RangeOperandType, type ap as RankBeforeOptions, type aq as RankBeforeResult, type ar as RankOptions, type as as RankPage, type at as RankPageRow, type au as RankResult, type av as RankSortKeyLike, aw as ReactiveCache, type ax as ReactiveCacheOptions, type ay as ReadHook, type az as RelatedDirection, type aA as RelatedNode, type aB as RelatedStartReference, type aC as RelationDefinitionLike, type aD as RelationWriteInfo, type aE as RelationWriteMap, type c as RenderedSql, type aF as ResolveWithResult, type aG as RpcRequest, type aH as SchedulableWorkflowReferenceLike, type aI as ScheduledFunctionDoc, type aJ as ScoredDocument, type aK as SearchFilterBuilderLike, type aL as SearchScoredDocument, type aM as ShardRankPageResult, type b as SqlEngine, type aN as StorageMetadata, type aO as SubscriptionEnvelope, type aP as SubscriptionQuery, type aQ as SystemDatabaseReader, type aR as SystemDoc, type aS as SystemQuery, type aT as SystemReaderOptions, type aU as SystemReaderSchedulerLike, type aV as SystemReaderStorageLike, type aW as SystemTableName, type aX as TableReaderLike, type aY as ThroughRelationWriteInfo, type aZ as TransactionHeadroom, a_ as TransactionHeadroomTracker, type a$ as TransactionLimitKind, type b0 as TransactionLimitWarning, type b1 as TriggerDefinitionLike, b2 as WORKERD_SQLITE_LIMITS, type b3 as WithInput, type b4 as WriteEvent, type b5 as WriteHook, b6 as assertNoExplicitUndefined, b7 as assertStorableRowId, b8 as assertValidClientId, b9 as buildIndexRange, ba as clearCompanionSignatures, bb as createShardCtxDb, bc as createSystemReader, bd as describeRelationWrites, be as indexKeysForRow, bf as keysTouchRanges, bg as normalizeIdStructurally, bh as reactiveCacheKey, bi as stripReservedPatchFields } from "./packem_shared/sql-engine.d-
|
|
1
|
+
import { D as DatabaseWriterLike, d as SchemaLike, T as TriggerContextLike, e as TriggerEventLike, f as TriggerOpLike, g as TriggerTimingLike, S as SqlExec, h as SearchIndexDefinitionLike, W as WhereInput, i as RestrictableQueryOptions, j as SchedulerLike, A as AggregateIndexDefinitionLike, k as AggregateOp, l as RankIndexDefinitionLike, M as MutationDelta, m as TableDefinitionLike, n as RankDirection, o as RankPageRowKey, p as RankPageOptions, C as ColumnMetaLike, q as SortDirection, P as PatchWriteOptions, O as OrderKey, r as OrderByInput, V as ValidatorLike, K as KeyRange, s as RelationEdge, t as RelatedStart, u as RelatedOptions, v as RelatedPage, w as KeyedRelationDefinitionLike, Q as QueryArgs, x as QueryPage, y as ServerDefaultContextLike, z as ResolveWithOptions, B as SocketAttachment, E as ResolvedShape, F as ShapeSubscriptionQuery, G as ShardSocketLike, H as SubscriptionIdentity, I as TransactionLimits, a as SqlCursor, J as IndexKeyEntry } from "./packem_shared/sql-engine.d-D-Bc5Xkd.mjs";
|
|
2
|
+
export { type L as AggregateOptions, type N as AggregateResult, type U as BroadcastDelta, type X as CacheEntry, type Y as Clock, Z as CompanionMemo, type _ as CountArgs, type $ as CrossShardCountArgs, type a0 as CrossShardReadArgs, type a1 as CtxDbOptions, a2 as DEFAULT_TRANSACTION_LIMITS, type a3 as FanOutBudget, type a4 as FieldOperators, type a5 as GeoFilterBuilderLike, type a6 as GeoIndexDefinitionLike, type a7 as GeoScoredDocument, type a8 as GroupByEntry, type a9 as GroupByOptions, type aa as GuardableSchema, type ab as IdGenerator, type ac as IndexDefinitionLike, type ad as IndexRangeBuilderLike, type ae as KeyedRelationWriteInfo, type af as LifecycleDispatchInfo, type ag as LifecycleEvent, type ah as NestedWith, ai as NotUniqueError, type aj as NullPlacement, type ak as OnDeleteActionLike, type al as PaginationOptions, type am as PatchVerifier, type an as QueryPlan, ao as RELATION_EXISTS_KEY, type R as RangeOperandType, type ap as RankBeforeOptions, type aq as RankBeforeResult, type ar as RankOptions, type as as RankPage, type at as RankPageRow, type au as RankResult, type av as RankSortKeyLike, aw as ReactiveCache, type ax as ReactiveCacheOptions, type ay as ReadHook, type az as RelatedDirection, type aA as RelatedNode, type aB as RelatedStartReference, type aC as RelationDefinitionLike, type aD as RelationWriteInfo, type aE as RelationWriteMap, type c as RenderedSql, type aF as ResolveWithResult, type aG as RpcRequest, type aH as SchedulableWorkflowReferenceLike, type aI as ScheduledFunctionDoc, type aJ as ScoredDocument, type aK as SearchFilterBuilderLike, type aL as SearchScoredDocument, type aM as ShardRankPageResult, type b as SqlEngine, type aN as StorageMetadata, type aO as SubscriptionEnvelope, type aP as SubscriptionQuery, type aQ as SystemDatabaseReader, type aR as SystemDoc, type aS as SystemQuery, type aT as SystemReaderOptions, type aU as SystemReaderSchedulerLike, type aV as SystemReaderStorageLike, type aW as SystemTableName, type aX as TableReaderLike, type aY as ThroughRelationWriteInfo, type aZ as TransactionHeadroom, a_ as TransactionHeadroomTracker, type a$ as TransactionLimitKind, type b0 as TransactionLimitWarning, type b1 as TriggerDefinitionLike, b2 as WORKERD_SQLITE_LIMITS, type b3 as WithInput, type b4 as WriteEvent, type b5 as WriteHook, b6 as assertNoExplicitUndefined, b7 as assertStorableRowId, b8 as assertValidClientId, b9 as buildIndexRange, ba as clearCompanionSignatures, bb as createShardCtxDb, bc as createSystemReader, bd as describeRelationWrites, be as indexKeysForRow, bf as keysTouchRanges, bg as normalizeIdStructurally, bh as reactiveCacheKey, bi as stripReservedPatchFields } from "./packem_shared/sql-engine.d-D-Bc5Xkd.mjs";
|
|
3
3
|
import { LunoraError } from '@lunora/errors';
|
|
4
4
|
import { R2BucketLike, ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
|
|
5
5
|
export { stableStringify, stableWireKey } from '@lunora/wire';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DatabaseWriterLike, d as SchemaLike, T as TriggerContextLike, e as TriggerEventLike, f as TriggerOpLike, g as TriggerTimingLike, S as SqlExec, h as SearchIndexDefinitionLike, W as WhereInput, i as RestrictableQueryOptions, j as SchedulerLike, A as AggregateIndexDefinitionLike, k as AggregateOp, l as RankIndexDefinitionLike, M as MutationDelta, m as TableDefinitionLike, n as RankDirection, o as RankPageRowKey, p as RankPageOptions, C as ColumnMetaLike, q as SortDirection, P as PatchWriteOptions, O as OrderKey, r as OrderByInput, V as ValidatorLike, K as KeyRange, s as RelationEdge, t as RelatedStart, u as RelatedOptions, v as RelatedPage, w as KeyedRelationDefinitionLike, Q as QueryArgs, x as QueryPage, y as ServerDefaultContextLike, z as ResolveWithOptions, B as SocketAttachment, E as ResolvedShape, F as ShapeSubscriptionQuery, G as ShardSocketLike, H as SubscriptionIdentity, I as TransactionLimits, a as SqlCursor, J as IndexKeyEntry } from "./packem_shared/sql-engine.d-
|
|
2
|
-
export { type L as AggregateOptions, type N as AggregateResult, type U as BroadcastDelta, type X as CacheEntry, type Y as Clock, Z as CompanionMemo, type _ as CountArgs, type $ as CrossShardCountArgs, type a0 as CrossShardReadArgs, type a1 as CtxDbOptions, a2 as DEFAULT_TRANSACTION_LIMITS, type a3 as FanOutBudget, type a4 as FieldOperators, type a5 as GeoFilterBuilderLike, type a6 as GeoIndexDefinitionLike, type a7 as GeoScoredDocument, type a8 as GroupByEntry, type a9 as GroupByOptions, type aa as GuardableSchema, type ab as IdGenerator, type ac as IndexDefinitionLike, type ad as IndexRangeBuilderLike, type ae as KeyedRelationWriteInfo, type af as LifecycleDispatchInfo, type ag as LifecycleEvent, type ah as NestedWith, ai as NotUniqueError, type aj as NullPlacement, type ak as OnDeleteActionLike, type al as PaginationOptions, type am as PatchVerifier, type an as QueryPlan, ao as RELATION_EXISTS_KEY, type R as RangeOperandType, type ap as RankBeforeOptions, type aq as RankBeforeResult, type ar as RankOptions, type as as RankPage, type at as RankPageRow, type au as RankResult, type av as RankSortKeyLike, aw as ReactiveCache, type ax as ReactiveCacheOptions, type ay as ReadHook, type az as RelatedDirection, type aA as RelatedNode, type aB as RelatedStartReference, type aC as RelationDefinitionLike, type aD as RelationWriteInfo, type aE as RelationWriteMap, type c as RenderedSql, type aF as ResolveWithResult, type aG as RpcRequest, type aH as SchedulableWorkflowReferenceLike, type aI as ScheduledFunctionDoc, type aJ as ScoredDocument, type aK as SearchFilterBuilderLike, type aL as SearchScoredDocument, type aM as ShardRankPageResult, type b as SqlEngine, type aN as StorageMetadata, type aO as SubscriptionEnvelope, type aP as SubscriptionQuery, type aQ as SystemDatabaseReader, type aR as SystemDoc, type aS as SystemQuery, type aT as SystemReaderOptions, type aU as SystemReaderSchedulerLike, type aV as SystemReaderStorageLike, type aW as SystemTableName, type aX as TableReaderLike, type aY as ThroughRelationWriteInfo, type aZ as TransactionHeadroom, a_ as TransactionHeadroomTracker, type a$ as TransactionLimitKind, type b0 as TransactionLimitWarning, type b1 as TriggerDefinitionLike, b2 as WORKERD_SQLITE_LIMITS, type b3 as WithInput, type b4 as WriteEvent, type b5 as WriteHook, b6 as assertNoExplicitUndefined, b7 as assertStorableRowId, b8 as assertValidClientId, b9 as buildIndexRange, ba as clearCompanionSignatures, bb as createShardCtxDb, bc as createSystemReader, bd as describeRelationWrites, be as indexKeysForRow, bf as keysTouchRanges, bg as normalizeIdStructurally, bh as reactiveCacheKey, bi as stripReservedPatchFields } from "./packem_shared/sql-engine.d-
|
|
1
|
+
import { D as DatabaseWriterLike, d as SchemaLike, T as TriggerContextLike, e as TriggerEventLike, f as TriggerOpLike, g as TriggerTimingLike, S as SqlExec, h as SearchIndexDefinitionLike, W as WhereInput, i as RestrictableQueryOptions, j as SchedulerLike, A as AggregateIndexDefinitionLike, k as AggregateOp, l as RankIndexDefinitionLike, M as MutationDelta, m as TableDefinitionLike, n as RankDirection, o as RankPageRowKey, p as RankPageOptions, C as ColumnMetaLike, q as SortDirection, P as PatchWriteOptions, O as OrderKey, r as OrderByInput, V as ValidatorLike, K as KeyRange, s as RelationEdge, t as RelatedStart, u as RelatedOptions, v as RelatedPage, w as KeyedRelationDefinitionLike, Q as QueryArgs, x as QueryPage, y as ServerDefaultContextLike, z as ResolveWithOptions, B as SocketAttachment, E as ResolvedShape, F as ShapeSubscriptionQuery, G as ShardSocketLike, H as SubscriptionIdentity, I as TransactionLimits, a as SqlCursor, J as IndexKeyEntry } from "./packem_shared/sql-engine.d-D-Bc5Xkd.js";
|
|
2
|
+
export { type L as AggregateOptions, type N as AggregateResult, type U as BroadcastDelta, type X as CacheEntry, type Y as Clock, Z as CompanionMemo, type _ as CountArgs, type $ as CrossShardCountArgs, type a0 as CrossShardReadArgs, type a1 as CtxDbOptions, a2 as DEFAULT_TRANSACTION_LIMITS, type a3 as FanOutBudget, type a4 as FieldOperators, type a5 as GeoFilterBuilderLike, type a6 as GeoIndexDefinitionLike, type a7 as GeoScoredDocument, type a8 as GroupByEntry, type a9 as GroupByOptions, type aa as GuardableSchema, type ab as IdGenerator, type ac as IndexDefinitionLike, type ad as IndexRangeBuilderLike, type ae as KeyedRelationWriteInfo, type af as LifecycleDispatchInfo, type ag as LifecycleEvent, type ah as NestedWith, ai as NotUniqueError, type aj as NullPlacement, type ak as OnDeleteActionLike, type al as PaginationOptions, type am as PatchVerifier, type an as QueryPlan, ao as RELATION_EXISTS_KEY, type R as RangeOperandType, type ap as RankBeforeOptions, type aq as RankBeforeResult, type ar as RankOptions, type as as RankPage, type at as RankPageRow, type au as RankResult, type av as RankSortKeyLike, aw as ReactiveCache, type ax as ReactiveCacheOptions, type ay as ReadHook, type az as RelatedDirection, type aA as RelatedNode, type aB as RelatedStartReference, type aC as RelationDefinitionLike, type aD as RelationWriteInfo, type aE as RelationWriteMap, type c as RenderedSql, type aF as ResolveWithResult, type aG as RpcRequest, type aH as SchedulableWorkflowReferenceLike, type aI as ScheduledFunctionDoc, type aJ as ScoredDocument, type aK as SearchFilterBuilderLike, type aL as SearchScoredDocument, type aM as ShardRankPageResult, type b as SqlEngine, type aN as StorageMetadata, type aO as SubscriptionEnvelope, type aP as SubscriptionQuery, type aQ as SystemDatabaseReader, type aR as SystemDoc, type aS as SystemQuery, type aT as SystemReaderOptions, type aU as SystemReaderSchedulerLike, type aV as SystemReaderStorageLike, type aW as SystemTableName, type aX as TableReaderLike, type aY as ThroughRelationWriteInfo, type aZ as TransactionHeadroom, a_ as TransactionHeadroomTracker, type a$ as TransactionLimitKind, type b0 as TransactionLimitWarning, type b1 as TriggerDefinitionLike, b2 as WORKERD_SQLITE_LIMITS, type b3 as WithInput, type b4 as WriteEvent, type b5 as WriteHook, b6 as assertNoExplicitUndefined, b7 as assertStorableRowId, b8 as assertValidClientId, b9 as buildIndexRange, ba as clearCompanionSignatures, bb as createShardCtxDb, bc as createSystemReader, bd as describeRelationWrites, be as indexKeysForRow, bf as keysTouchRanges, bg as normalizeIdStructurally, bh as reactiveCacheKey, bi as stripReservedPatchFields } from "./packem_shared/sql-engine.d-D-Bc5Xkd.js";
|
|
3
3
|
import { LunoraError } from '@lunora/errors';
|
|
4
4
|
import { R2BucketLike, ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
|
|
5
5
|
export { stableStringify, stableWireKey } from '@lunora/wire';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,replaceRefusal as s,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BxhBKedl.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CDwEWaFF.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 C,encodeAggregateKey as _,foldAggregateTally as g,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as O,mergeWhere as D,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 w,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-CGyZ2LNx.mjs";import{NotUniqueError as G,assertNoExplicitUndefined as K,assertStorableRowId as q,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-C_IDBwvG.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BkCo8Dpf.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 ie,cdcForkedError as se,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-DchHJJ5G.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as Ce,readArchivedCdcChanges as _e,readCdcArchivedThrough as ge,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-B3UKVQ9U.mjs";import{CLIENT_WATERMARK_TABLE as Oe,advanceClientWatermark as De,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as we}from"./packem_shared/COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{CompanionMemo as ve,clearCompanionSignatures as Ge}from"./packem_shared/CompanionMemo-CYnosDCb.mjs";import{createCompanionSync as qe}from"./packem_shared/createCompanionSync-D5cqtwqR.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as Qe,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as ir}from"./packem_shared/clearMemoryTables-CIfrwTj8.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-De_JKnna.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 Cr,trimScheduleOutbox as _r}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs";import{S as br,m as Lr,r as Or,w as Dr}from"./packem_shared/ctx-db-search-state-Bv_NxB1g.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 wr,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs";import{selectShapeMembers as Gr,selectShapeRows as Kr}from"./packem_shared/selectShapeMembers-BP30uxpp.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs";import{SCAN_DEP as Qr,createDependencyTracker as zr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{D as Zr,g as $r,i as eo,j as ro,q as oo,r as ao,t as to,a as io}from"./packem_shared/do-sql-DT8JBpG8.mjs";import{appendStreamChunk as no,claimStreamRun as lo,deleteStreamRun as mo,finishStreamRun as co,migrateDurableStreams as po,readStreamChunks as So,readStreamRun as uo,trimStreamRuns as fo}from"./packem_shared/appendStreamChunk-DIxOE9q_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as xo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-BikgXQLq.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as Co}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Lo,normalizeSourceDocument as Oo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Po,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as Fo,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-LugivbOG.mjs";import{isSoftDeleted as Bo,isSourceDue as wo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as vo}from"./packem_shared/isSoftDeleted-Dc3VHgrR.mjs";import{ftsRowidMapName as Ko,groupUnmappedRows as qo}from"./packem_shared/ftsRowidMapName-CGnFBC6P.mjs";import{GEO_DEFAULT_PRECISION as Ho,boundingBoxCenter as Xo,boundingBoxGeohashes as Vo,coveringGeohashes as Qo,encodeGeohash as zo,haversineMeters as Yo,pointInBoundingBox as jo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Zo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as ea,IMPORT_STAGE_TTL_MS as ra,advanceImportManifest as oa,assertImportSessionId as aa,dropImportManifest as ta,dropImportSession as ia,markShardImportCommitted as sa,readImportManifest as na,readShardImportSession as la,stageImportRows as da,stagedImportIds as ma,stagedImportPage as ca,sweepImportStaging as pa,touchImportManifest as Sa,touchShardImportSession as ua}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ea,DEFAULT_FANOUT_TOPIC_LIMIT as xa,FLAGS_FUNCTION_PREFIX as ha,MAX_PAGE_SIZE as Ra,RELATION_FUNCTION_PREFIX as Aa,createFanoutCounters as Ia,createGlobalPollCounters as Ca,createShapeProbeCounters as _a,facetColumn as ga,findStorageReferences as ba,isVacuousFilterClause as La,listTables as Oa,readTablePage as Da,recordFanoutPass as Ma,recordGlobalPollPass as Pa,recordShapeProbePass as ya,selectMatchingIds as Fa,summarizeFanoutTopics as ka,summarizeSubscriptions as Na}from"./packem_shared/ADMIN_FUNCTIONS-voPpYb3p.mjs";import{MAIL_RETENTION as wa,MAIL_TABLE as Ua,clearCapturedMail as va,ensureMailTable as Ga,readCapturedMail as Ka,recordCapturedMail as qa}from"./packem_shared/MAIL_RETENTION-C0LZvTbG.mjs";import{NotFoundError as Ha}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Va,operatorFields as Qa,patchDependsOnRow as za,readPatchField as Ya,resolvePatch as ja}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Za,readBookmark as $a}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as rt,applySelect as ot,buildSeekBeforeWhere as at,buildSeekWhere as tt,decodeCursor as it,encodeCursor as st,equalityPinnedFields as nt,normalizeOrderKeys as lt,nullsFirstOf as dt,nullsOrderSuffix as mt,softDeleteScope as ct,tiebreakDirectionFor as pt,uniqueIndexFields as St}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as ft,clearQueueMessages as Tt,isLossyBody as Et,readQueueMessageById as xt,readQueueMessages as ht,recordQueueMessages as Rt}from"./packem_shared/QUEUE_TABLE-CWUNphDm.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as Ct,matchesRankStaticWhere as _t,rankKeyFromDoc as gt,rankTableName as bt,resolveRankPartition as Lt,sortColumnName as Ot}from"./packem_shared/RANK_TIEBREAK-BknRdgt8.mjs";import{ReactiveCache as Mt,reactiveCacheKey as Pt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ft,listReactorStates as kt,migrateReactorState as Nt,reactorNeedsRun as Bt,readReactorState as wt,writeReactorState as Ut}from"./packem_shared/REACTOR_STATE_TABLE-B2x69RYJ.mjs";import{ADMIN_WILDCARD as Gt,UNVOUCHABLE_DEP as Kt,createReadFootprint as qt,markUnvouchableReads as Wt}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as Xt,indexKeysForRow as Vt,keysTouchRanges as Qt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Yt,whereFilter as jt,whereOfFilter as Jt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as $t,RELATED_DEPTH_DECAY as ei,RELATED_MAX_DEPTH as ri,RELATED_MAX_LIMIT as oi,deriveRelationEdges as ai,findRelated as ti}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as si,assertFlatPredicate as ni,assertShapeShardable as li,composeReadPredicate as di,containsRelationPredicate as mi,findManyPage as ci,isRelationPredicate as pi,resolveRelationPredicates as Si}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs";import{describeRelationWrites as fi}from"./packem_shared/describeRelationWrites-BKd7YU5R.mjs";import{applyInsertDefaults as Ei,applyOnDelete as xi,distinctValues as hi,fanOutScalarCounts as Ri,relationHooks as Ai,resolveWith as Ii,runRowValidators as Ci}from"./packem_shared/applyInsertDefaults-Bt6LYmPD.mjs";import{D as gi,c as bi,n as Li,r as Oi,s as Di}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Pi,OwnerRelay as yi,RelayMember as Fi,createRelayLink as ki}from"./packem_shared/DEFAULT_MAX_RELAYS-BcyWWSdU.mjs";import{createReplicaLink as Bi,gateReplicaDispatch as wi,handleReplicaControl as Ui}from"./packem_shared/createReplicaLink-auEtD_6G.mjs";import{buildReprojectionMigration as Gi,countLegacyRows as Ki,reprojectableFields as qi,reprojectionTables as Wi}from"./packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs";import{RLS_UNWRAP_SYMBOL as Xi,RlsRequiredError as Vi,guardWriter as Qi}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{default as Yi}from"./packem_shared/runSql-BBRXi81G.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CrLtKTuR.mjs";import{ShapeDiffCache as ms,createShapeDiffCache as cs,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as us,diffGlobalMembership as fs,encodeRowsPatch as Ts,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as hs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Cs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as gs,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Os}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{WORKERD_SQLITE_LIMITS as Ms}from"./packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{BIGINT_KEY_DIGITS as ys,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 Us,awaitWsDrain as vs,deltaTableFor as Gs,subscriptionFrames as Ks,subscriptionListDeltas as qs,trySendFrame as Ws}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as Xs,recordChangedKeys as Vs,writeTouchesMemo as Qs}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-ktYeluAa.mjs";import{VECTOR_BACKFILL_MAX_PAGES as mn,backfillVectorIndexes as cn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs";import{RELATION_EXISTS_KEY as Sn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as fn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as En,siblingSecretOf as xn,signSiblingBody as hn,verifySiblingBody as Rn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as In,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as gn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Ln}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-DeOECCjz.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ea as ADMIN_FUNCTION_PREFIX,fn as ADMIN_TOKEN_TABLE,Gt as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,N as AUDIT_LOG_TABLE,ys as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,Oe as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,rt as CURSOR_PREFIX,ve as CompanionMemo,Js as ConflictError,O as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,xa as DEFAULT_FANOUT_TOPIC_LIMIT,si as DEFAULT_MAX_RELATION_KEYS,Pi as DEFAULT_MAX_RELAYS,gi as DEFAULT_PROMOTION_THRESHOLDS,$s as DEFAULT_TRANSACTION_LIMITS,Us as DELTA_PLACEHOLDER_TABLE,Zr as DOC_COLUMN,Eo as DurableStreamRunner,ha as FLAGS_FUNCTION_PREFIX,Ho as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,Zo as GlobalPollTick,Je as IDEMPOTENCY_TABLE,ea as IMPORT_MANIFEST_TTL_MS,ra as IMPORT_STAGE_TTL_MS,wa as MAIL_RETENTION,Ua as MAIL_TABLE,xo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,Ra as MAX_PAGE_SIZE,gs as MAX_SQL_ROWS,Ha as NotFoundError,G as NotUniqueError,yi as OwnerRelay,ft as QUEUE_TABLE,It as RANK_TIEBREAK,Ft as REACTOR_STATE_TABLE,$t as RELATED_DEFAULT_LIMIT,ei as RELATED_DEPTH_DECAY,ri as RELATED_MAX_DEPTH,oi as RELATED_MAX_LIMIT,Sn as RELATION_EXISTS_KEY,Aa as RELATION_FUNCTION_PREFIX,En as RELAY_SIGNATURE_HEADER,In as REPROJECTION_MIGRATION_PREFIX,Xi as RLS_UNWRAP_SYMBOL,Mt as ReactiveCache,Fi as RelayMember,Vi as RlsRequiredError,Qr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ms as ShapeDiffCache,hs as ShardRunner,en as TransactionHeadroomTracker,Kt as UNVOUCHABLE_DEP,mn as VECTOR_BACKFILL_MAX_PAGES,Ms as WORKERD_SQLITE_LIMITS,m as adminTokenExists,De as advanceClientWatermark,oa as advanceImportManifest,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,no as appendStreamChunk,ae as applyCdcChanges,Ei as applyInsertDefaults,xi as applyOnDelete,ot as applySelect,Ie as archiveCdcSegment,Za as armRestore,ni as assertFlatPredicate,aa as assertImportSessionId,K as assertNoExplicitUndefined,Va as assertPatchAllowed,bs as assertReadonly,li as assertShapeShardable,q as assertStorableRowId,W as assertValidClientId,vs as awaitWsDrain,z as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,cn as backfillVectorIndexes,Fs as bigintSqlKey,Xo as boundingBoxCenter,Vo as boundingBoxGeohashes,Xt as buildIndexRange,us as buildPokeFrames,Gi as buildReprojectionMigration,at as buildSeekBeforeWhere,tt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,te as bumpCdcEpoch,Ce as cdcArchiveRewound,ie as cdcCanVouchFor,se as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,lo as claimStreamRun,bi as clampPromotionThresholds,va as clearCapturedMail,Ge as clearCompanionSignatures,ar as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,me as compactCdcDocs,di as composeReadPredicate,nr as computeRankPage,mi as containsRelationPredicate,Ki as countLegacyRows,Qo as coveringGeohashes,c as createAdminTokenRecord,qe as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,Ca as createGlobalPollCounters,qt as createReadFootprint,ki as createRelayLink,Bi as createReplicaLink,cs as createShapeDiffCache,_a as createShapeProbeCounters,H as createShardCtxDb,Ys as createSystemReader,ce as cursorBelowRetainedFloor,Ro as decideDurableAttach,ks as decodeBigintSqlKey,it as decodeCursor,Ns as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Gs as deltaTableFor,Yr as depKey,ai as deriveRelationEdges,fi as describeRelationWrites,go as diffExternalSource,fs as diffGlobalMembership,hi as distinctValues,ta as dropImportManifest,ia as dropImportSession,pr as dropScheduleOutbox,_ as encodeAggregateKey,st as encodeCursor,zo as encodeGeohash,Ct as encodePartitionKey,Ts as encodeRowsPatch,w as ensureAuditTable,Ga as ensureMailTable,Io as envOptionalPositiveInt,Co as envPositiveInt,nt as equalityPinnedFields,o as exportShardRows,ga as facetColumn,Ri as fanOutScalarCounts,ci as findManyPage,ti as findRelated,ba as findStorageReferences,co as finishStreamRun,Bs as float64SqlKey,g as foldAggregateTally,Sr as forgetScheduleOutbox,Ko as ftsRowidMapName,wi as gateReplicaDispatch,$r as geoTableName,ps as globalShapeReadKey,qo as groupUnmappedRows,Qi as guardWriter,Ui as handleReplicaControl,ur as hasScheduleOutboxEntry,on as hasTrigger,Yo as haversineMeters,a as importShardRows,Vt as indexKeysForRow,is as isDevEnvironment,eo as isFtsAvailable,gn as isInternalTableName,Et as isLossyBody,tr as isMemoryTable,Yt as isPushableWhere,pi as isRelationPredicate,Bo as isSoftDeleted,wo as isSourceDue,sn as isTtlExpired,La as isVacuousFilterClause,ro as jsonPath,Qt as keysTouchRanges,Lo as liftSourceId,Ls as lintReadonlySql,p as listAdminTokens,kt as listReactorStates,Oa as listTables,sa as markShardImportCommitted,Wt as markUnvouchableReads,_t as matchesRankStaticWhere,x as matchesStaticWhere,Po as materializeExternalRows,yo as materializeExternalRowsIncremental,ir as memoryTableNames,Xs as mergeChangedKeys,D as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,po as migrateDurableStreams,Qe as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,Nt as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Li as nextPromotionState,nn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,lt as normalizeOrderKeys,Oo as normalizeSourceDocument,Do as normalizeSourceValue,dt as nullsFirstOf,mt as nullsOrderSuffix,Qa as operatorFields,Tr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,za as patchDependsOnRow,M as planAggregateLookup,jo as pointInBoundingBox,Er as probeScheduleOutbox,Es as projectColumns,Uo as pullExternalSourceIncrementalTick,vo as pullExternalSourceTick,oo as qualifiedJsonPath,Ln as quoteIdentifier,gt as rankKeyFromDoc,bt as rankTableName,Pt as reactiveCacheKey,Bt as reactorNeedsRun,b as readAggregateValue,_e as readArchivedCdcChanges,U as readAuditLog,$a as readBookmark,Ka as readCapturedMail,ge as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,we as readCommitSeq,ss as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Fo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,$e as readIdempotent,na as readImportManifest,Hr as readMigrationStatus,Ya as readPatchField,xt as readQueueMessageById,ht as readQueueMessages,wt as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Or as readSearchBackfillState,Br as readShapePokeCursor,la as readShardImportSession,So as readStreamChunks,uo as readStreamRun,Da as readTablePage,qa as recordCapturedMail,Vs as recordChangedKeys,Ma as recordFanoutPass,Pa as recordGlobalPollPass,Rt as recordQueueMessages,Ir as recordScheduleOutbox,es as recordSchemaVersion,ya as recordShapeProbePass,Ai as relationHooks,Oi as relayCountFor,s as replaceRefusal,qi as reprojectableFields,Cn as reprojectionMigrationId,Wi as reprojectionTables,Cr as requeueScheduleOutbox,ja as resolvePatch,Lt as resolveRankPartition,lr as resolveRankSeekTuple,Si as resolveRelationPredicates,Ii as resolveWith,S as revokeAdminTokenRecord,ao as rowToDocument,Xr as runDataMigration,ko as runExternalSourceTick,Os as runReadonlySql,Ci as runRowValidators,Dn as runShardMigrations,Cs as runSocketPool,Yi as runSql,an as runTriggers,ln as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,Fa as selectMatchingIds,Gr as selectShapeMembers,Kr as selectShapeRows,os as serializeSqlValue,Di as shapeRoutingKey,xn as siblingSecretOf,hn as signSiblingBody,ct as softDeleteScope,Ot as sortColumnName,Pn as stableStringify,yn as stableWireKey,da as stageImportRows,ma as stagedImportIds,ca as stagedImportPage,V as stripReservedPatchFields,As as stubByName,Ks as subscriptionFrames,qs as subscriptionListDeltas,ka as summarizeFanoutTopics,Na as summarizeSubscriptions,pa as sweepImportStaging,to as tableColumns,jr as tableFromDepKey,R as throwingScheduler,pt as tiebreakDirectionFor,Sa as touchImportManifest,ua as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,_r as trimScheduleOutbox,fo as trimStreamRuns,io as tryRowToDocument,Ws as trySendFrame,St as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,Rn as verifySiblingBody,jt as whereFilter,Jt as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,Ut as writeReactorState,Dr as writeSearchBackfillState,wr as writeShapePokeCursor,Ur as writeShapePokeCursors,Qs as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,replaceRefusal as s,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BxhBKedl.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CDwEWaFF.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 C,encodeAggregateKey as _,foldAggregateTally as g,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as O,mergeWhere as D,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 w,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-CGyZ2LNx.mjs";import{NotUniqueError as G,assertNoExplicitUndefined as K,assertStorableRowId as q,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-CPAltXX4.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BkCo8Dpf.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 ie,cdcForkedError as se,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-DchHJJ5G.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as Ce,readArchivedCdcChanges as _e,readCdcArchivedThrough as ge,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-B3UKVQ9U.mjs";import{CLIENT_WATERMARK_TABLE as Oe,advanceClientWatermark as De,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as we}from"./packem_shared/COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{CompanionMemo as ve,clearCompanionSignatures as Ge}from"./packem_shared/CompanionMemo-CYnosDCb.mjs";import{createCompanionSync as qe}from"./packem_shared/createCompanionSync-D5cqtwqR.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as Qe,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as ir}from"./packem_shared/clearMemoryTables-CIfrwTj8.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-De_JKnna.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 Cr,trimScheduleOutbox as _r}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs";import{S as br,m as Lr,r as Or,w as Dr}from"./packem_shared/ctx-db-search-state-Bv_NxB1g.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 wr,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs";import{selectShapeMembers as Gr,selectShapeRows as Kr}from"./packem_shared/selectShapeMembers-BP30uxpp.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs";import{SCAN_DEP as Qr,createDependencyTracker as zr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{D as Zr,g as $r,i as eo,j as ro,q as oo,r as ao,t as to,a as io}from"./packem_shared/do-sql-DT8JBpG8.mjs";import{appendStreamChunk as no,claimStreamRun as lo,deleteStreamRun as mo,finishStreamRun as co,migrateDurableStreams as po,readStreamChunks as So,readStreamRun as uo,trimStreamRuns as fo}from"./packem_shared/appendStreamChunk-DIxOE9q_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as xo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-BikgXQLq.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as Co}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Lo,normalizeSourceDocument as Oo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Po,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as Fo,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-LugivbOG.mjs";import{isSoftDeleted as Bo,isSourceDue as wo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as vo}from"./packem_shared/isSoftDeleted-Dc3VHgrR.mjs";import{ftsRowidMapName as Ko,groupUnmappedRows as qo}from"./packem_shared/ftsRowidMapName-CGnFBC6P.mjs";import{GEO_DEFAULT_PRECISION as Ho,boundingBoxCenter as Xo,boundingBoxGeohashes as Vo,coveringGeohashes as Qo,encodeGeohash as zo,haversineMeters as Yo,pointInBoundingBox as jo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Zo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as ea,IMPORT_STAGE_TTL_MS as ra,advanceImportManifest as oa,assertImportSessionId as aa,dropImportManifest as ta,dropImportSession as ia,markShardImportCommitted as sa,readImportManifest as na,readShardImportSession as la,stageImportRows as da,stagedImportIds as ma,stagedImportPage as ca,sweepImportStaging as pa,touchImportManifest as Sa,touchShardImportSession as ua}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ea,DEFAULT_FANOUT_TOPIC_LIMIT as xa,FLAGS_FUNCTION_PREFIX as ha,MAX_PAGE_SIZE as Ra,RELATION_FUNCTION_PREFIX as Aa,createFanoutCounters as Ia,createGlobalPollCounters as Ca,createShapeProbeCounters as _a,facetColumn as ga,findStorageReferences as ba,isVacuousFilterClause as La,listTables as Oa,readTablePage as Da,recordFanoutPass as Ma,recordGlobalPollPass as Pa,recordShapeProbePass as ya,selectMatchingIds as Fa,summarizeFanoutTopics as ka,summarizeSubscriptions as Na}from"./packem_shared/ADMIN_FUNCTIONS-voPpYb3p.mjs";import{MAIL_RETENTION as wa,MAIL_TABLE as Ua,clearCapturedMail as va,ensureMailTable as Ga,readCapturedMail as Ka,recordCapturedMail as qa}from"./packem_shared/MAIL_RETENTION-C0LZvTbG.mjs";import{NotFoundError as Ha}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Va,operatorFields as Qa,patchDependsOnRow as za,readPatchField as Ya,resolvePatch as ja}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Za,readBookmark as $a}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as rt,applySelect as ot,buildSeekBeforeWhere as at,buildSeekWhere as tt,decodeCursor as it,encodeCursor as st,equalityPinnedFields as nt,normalizeOrderKeys as lt,nullsFirstOf as dt,nullsOrderSuffix as mt,softDeleteScope as ct,tiebreakDirectionFor as pt,uniqueIndexFields as St}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as ft,clearQueueMessages as Tt,isLossyBody as Et,readQueueMessageById as xt,readQueueMessages as ht,recordQueueMessages as Rt}from"./packem_shared/QUEUE_TABLE-CWUNphDm.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as Ct,matchesRankStaticWhere as _t,rankKeyFromDoc as gt,rankTableName as bt,resolveRankPartition as Lt,sortColumnName as Ot}from"./packem_shared/RANK_TIEBREAK-BknRdgt8.mjs";import{ReactiveCache as Mt,reactiveCacheKey as Pt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ft,listReactorStates as kt,migrateReactorState as Nt,reactorNeedsRun as Bt,readReactorState as wt,writeReactorState as Ut}from"./packem_shared/REACTOR_STATE_TABLE-B2x69RYJ.mjs";import{ADMIN_WILDCARD as Gt,UNVOUCHABLE_DEP as Kt,createReadFootprint as qt,markUnvouchableReads as Wt}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as Xt,indexKeysForRow as Vt,keysTouchRanges as Qt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Yt,whereFilter as jt,whereOfFilter as Jt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as $t,RELATED_DEPTH_DECAY as ei,RELATED_MAX_DEPTH as ri,RELATED_MAX_LIMIT as oi,deriveRelationEdges as ai,findRelated as ti}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as si,assertFlatPredicate as ni,assertShapeShardable as li,composeReadPredicate as di,containsRelationPredicate as mi,findManyPage as ci,isRelationPredicate as pi,resolveRelationPredicates as Si}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs";import{describeRelationWrites as fi}from"./packem_shared/describeRelationWrites-BKd7YU5R.mjs";import{applyInsertDefaults as Ei,applyOnDelete as xi,distinctValues as hi,fanOutScalarCounts as Ri,relationHooks as Ai,resolveWith as Ii,runRowValidators as Ci}from"./packem_shared/applyInsertDefaults-Bt6LYmPD.mjs";import{D as gi,c as bi,n as Li,r as Oi,s as Di}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Pi,OwnerRelay as yi,RelayMember as Fi,createRelayLink as ki}from"./packem_shared/DEFAULT_MAX_RELAYS-BcyWWSdU.mjs";import{createReplicaLink as Bi,gateReplicaDispatch as wi,handleReplicaControl as Ui}from"./packem_shared/createReplicaLink-auEtD_6G.mjs";import{buildReprojectionMigration as Gi,countLegacyRows as Ki,reprojectableFields as qi,reprojectionTables as Wi}from"./packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs";import{RLS_UNWRAP_SYMBOL as Xi,RlsRequiredError as Vi,guardWriter as Qi}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{default as Yi}from"./packem_shared/runSql-BBRXi81G.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CrLtKTuR.mjs";import{ShapeDiffCache as ms,createShapeDiffCache as cs,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as us,diffGlobalMembership as fs,encodeRowsPatch as Ts,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as hs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Cs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as gs,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Os}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{WORKERD_SQLITE_LIMITS as Ms}from"./packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{BIGINT_KEY_DIGITS as ys,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 Us,awaitWsDrain as vs,deltaTableFor as Gs,subscriptionFrames as Ks,subscriptionListDeltas as qs,trySendFrame as Ws}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as Xs,recordChangedKeys as Vs,writeTouchesMemo as Qs}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-ktYeluAa.mjs";import{VECTOR_BACKFILL_MAX_PAGES as mn,backfillVectorIndexes as cn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs";import{RELATION_EXISTS_KEY as Sn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as fn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as En,siblingSecretOf as xn,signSiblingBody as hn,verifySiblingBody as Rn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as In,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as gn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Ln}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-DeOECCjz.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ea as ADMIN_FUNCTION_PREFIX,fn as ADMIN_TOKEN_TABLE,Gt as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,N as AUDIT_LOG_TABLE,ys as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,Oe as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,rt as CURSOR_PREFIX,ve as CompanionMemo,Js as ConflictError,O as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,xa as DEFAULT_FANOUT_TOPIC_LIMIT,si as DEFAULT_MAX_RELATION_KEYS,Pi as DEFAULT_MAX_RELAYS,gi as DEFAULT_PROMOTION_THRESHOLDS,$s as DEFAULT_TRANSACTION_LIMITS,Us as DELTA_PLACEHOLDER_TABLE,Zr as DOC_COLUMN,Eo as DurableStreamRunner,ha as FLAGS_FUNCTION_PREFIX,Ho as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,Zo as GlobalPollTick,Je as IDEMPOTENCY_TABLE,ea as IMPORT_MANIFEST_TTL_MS,ra as IMPORT_STAGE_TTL_MS,wa as MAIL_RETENTION,Ua as MAIL_TABLE,xo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,Ra as MAX_PAGE_SIZE,gs as MAX_SQL_ROWS,Ha as NotFoundError,G as NotUniqueError,yi as OwnerRelay,ft as QUEUE_TABLE,It as RANK_TIEBREAK,Ft as REACTOR_STATE_TABLE,$t as RELATED_DEFAULT_LIMIT,ei as RELATED_DEPTH_DECAY,ri as RELATED_MAX_DEPTH,oi as RELATED_MAX_LIMIT,Sn as RELATION_EXISTS_KEY,Aa as RELATION_FUNCTION_PREFIX,En as RELAY_SIGNATURE_HEADER,In as REPROJECTION_MIGRATION_PREFIX,Xi as RLS_UNWRAP_SYMBOL,Mt as ReactiveCache,Fi as RelayMember,Vi as RlsRequiredError,Qr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ms as ShapeDiffCache,hs as ShardRunner,en as TransactionHeadroomTracker,Kt as UNVOUCHABLE_DEP,mn as VECTOR_BACKFILL_MAX_PAGES,Ms as WORKERD_SQLITE_LIMITS,m as adminTokenExists,De as advanceClientWatermark,oa as advanceImportManifest,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,no as appendStreamChunk,ae as applyCdcChanges,Ei as applyInsertDefaults,xi as applyOnDelete,ot as applySelect,Ie as archiveCdcSegment,Za as armRestore,ni as assertFlatPredicate,aa as assertImportSessionId,K as assertNoExplicitUndefined,Va as assertPatchAllowed,bs as assertReadonly,li as assertShapeShardable,q as assertStorableRowId,W as assertValidClientId,vs as awaitWsDrain,z as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,cn as backfillVectorIndexes,Fs as bigintSqlKey,Xo as boundingBoxCenter,Vo as boundingBoxGeohashes,Xt as buildIndexRange,us as buildPokeFrames,Gi as buildReprojectionMigration,at as buildSeekBeforeWhere,tt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,te as bumpCdcEpoch,Ce as cdcArchiveRewound,ie as cdcCanVouchFor,se as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,lo as claimStreamRun,bi as clampPromotionThresholds,va as clearCapturedMail,Ge as clearCompanionSignatures,ar as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,me as compactCdcDocs,di as composeReadPredicate,nr as computeRankPage,mi as containsRelationPredicate,Ki as countLegacyRows,Qo as coveringGeohashes,c as createAdminTokenRecord,qe as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,Ca as createGlobalPollCounters,qt as createReadFootprint,ki as createRelayLink,Bi as createReplicaLink,cs as createShapeDiffCache,_a as createShapeProbeCounters,H as createShardCtxDb,Ys as createSystemReader,ce as cursorBelowRetainedFloor,Ro as decideDurableAttach,ks as decodeBigintSqlKey,it as decodeCursor,Ns as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Gs as deltaTableFor,Yr as depKey,ai as deriveRelationEdges,fi as describeRelationWrites,go as diffExternalSource,fs as diffGlobalMembership,hi as distinctValues,ta as dropImportManifest,ia as dropImportSession,pr as dropScheduleOutbox,_ as encodeAggregateKey,st as encodeCursor,zo as encodeGeohash,Ct as encodePartitionKey,Ts as encodeRowsPatch,w as ensureAuditTable,Ga as ensureMailTable,Io as envOptionalPositiveInt,Co as envPositiveInt,nt as equalityPinnedFields,o as exportShardRows,ga as facetColumn,Ri as fanOutScalarCounts,ci as findManyPage,ti as findRelated,ba as findStorageReferences,co as finishStreamRun,Bs as float64SqlKey,g as foldAggregateTally,Sr as forgetScheduleOutbox,Ko as ftsRowidMapName,wi as gateReplicaDispatch,$r as geoTableName,ps as globalShapeReadKey,qo as groupUnmappedRows,Qi as guardWriter,Ui as handleReplicaControl,ur as hasScheduleOutboxEntry,on as hasTrigger,Yo as haversineMeters,a as importShardRows,Vt as indexKeysForRow,is as isDevEnvironment,eo as isFtsAvailable,gn as isInternalTableName,Et as isLossyBody,tr as isMemoryTable,Yt as isPushableWhere,pi as isRelationPredicate,Bo as isSoftDeleted,wo as isSourceDue,sn as isTtlExpired,La as isVacuousFilterClause,ro as jsonPath,Qt as keysTouchRanges,Lo as liftSourceId,Ls as lintReadonlySql,p as listAdminTokens,kt as listReactorStates,Oa as listTables,sa as markShardImportCommitted,Wt as markUnvouchableReads,_t as matchesRankStaticWhere,x as matchesStaticWhere,Po as materializeExternalRows,yo as materializeExternalRowsIncremental,ir as memoryTableNames,Xs as mergeChangedKeys,D as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,po as migrateDurableStreams,Qe as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,Nt as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Li as nextPromotionState,nn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,lt as normalizeOrderKeys,Oo as normalizeSourceDocument,Do as normalizeSourceValue,dt as nullsFirstOf,mt as nullsOrderSuffix,Qa as operatorFields,Tr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,za as patchDependsOnRow,M as planAggregateLookup,jo as pointInBoundingBox,Er as probeScheduleOutbox,Es as projectColumns,Uo as pullExternalSourceIncrementalTick,vo as pullExternalSourceTick,oo as qualifiedJsonPath,Ln as quoteIdentifier,gt as rankKeyFromDoc,bt as rankTableName,Pt as reactiveCacheKey,Bt as reactorNeedsRun,b as readAggregateValue,_e as readArchivedCdcChanges,U as readAuditLog,$a as readBookmark,Ka as readCapturedMail,ge as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,we as readCommitSeq,ss as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Fo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,$e as readIdempotent,na as readImportManifest,Hr as readMigrationStatus,Ya as readPatchField,xt as readQueueMessageById,ht as readQueueMessages,wt as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Or as readSearchBackfillState,Br as readShapePokeCursor,la as readShardImportSession,So as readStreamChunks,uo as readStreamRun,Da as readTablePage,qa as recordCapturedMail,Vs as recordChangedKeys,Ma as recordFanoutPass,Pa as recordGlobalPollPass,Rt as recordQueueMessages,Ir as recordScheduleOutbox,es as recordSchemaVersion,ya as recordShapeProbePass,Ai as relationHooks,Oi as relayCountFor,s as replaceRefusal,qi as reprojectableFields,Cn as reprojectionMigrationId,Wi as reprojectionTables,Cr as requeueScheduleOutbox,ja as resolvePatch,Lt as resolveRankPartition,lr as resolveRankSeekTuple,Si as resolveRelationPredicates,Ii as resolveWith,S as revokeAdminTokenRecord,ao as rowToDocument,Xr as runDataMigration,ko as runExternalSourceTick,Os as runReadonlySql,Ci as runRowValidators,Dn as runShardMigrations,Cs as runSocketPool,Yi as runSql,an as runTriggers,ln as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,Fa as selectMatchingIds,Gr as selectShapeMembers,Kr as selectShapeRows,os as serializeSqlValue,Di as shapeRoutingKey,xn as siblingSecretOf,hn as signSiblingBody,ct as softDeleteScope,Ot as sortColumnName,Pn as stableStringify,yn as stableWireKey,da as stageImportRows,ma as stagedImportIds,ca as stagedImportPage,V as stripReservedPatchFields,As as stubByName,Ks as subscriptionFrames,qs as subscriptionListDeltas,ka as summarizeFanoutTopics,Na as summarizeSubscriptions,pa as sweepImportStaging,to as tableColumns,jr as tableFromDepKey,R as throwingScheduler,pt as tiebreakDirectionFor,Sa as touchImportManifest,ua as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,_r as trimScheduleOutbox,fo as trimStreamRuns,io as tryRowToDocument,Ws as trySendFrame,St as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,Rn as verifySiblingBody,jt as whereFilter,Jt as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,Ut as writeReactorState,Dr as writeSearchBackfillState,wr as writeShapePokeCursor,Ur as writeShapePokeCursors,Qs as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{q as At}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as to,l as Ge,s as no}from"./fts-companion-Cfz-hJum.mjs";import{decodeWire as oo,stableWireKey as Nt}from"@lunora/wire";import{sql as h}from"drizzle-orm";import{throwingScheduler as ro,aggregateSqlFunction as je,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as lt,encodeAggregateKey as ft,readAggregateValue as ut}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ht,selectIndexForGroupBy as io,selectIndexForCount as so,selectIndexForAggregate as co}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as ao,searchIndexCoversTable as lo}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{backfillAggregateIndexes as gs,backfillRankIndexes as ys,backfillSearchIndexes as $s}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{appendCdcChange as fo,readCdcDocAtOrBefore as uo}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{CDC_LOG_TABLE as ms,applyCdcChanges as vs,bumpCdcEpoch as Ss,cdcCanVouchFor as Rs,cdcForkedError as _s,cdcSeqLeavingRows as Ts,cdcTouchesTables as As,cdcTrimmedError as Is,compactCdcDocs as bs,cursorBelowRetainedFloor as Cs,minCdcReplayableSeq as xs,minCdcSeq as Ms,readCdcChangeKeys as Ds,readCdcChanges as ks,readCdcCursor as Ls,readCdcEpoch as Fs,trimCdcChanges as Ws}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{allocateCommitSeq as ho,COMMIT_SEQ_FIELD as wo}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{createCompanionSync as po}from"./createCompanionSync-D5cqtwqR.mjs";import{isMemoryTable as zt}from"./clearMemoryTables-CIfrwTj8.mjs";import{computeRankPage as Vt}from"./computeRankPage-De_JKnna.mjs";import{SCAN_DEP as G,PRIMARY_READ as go}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as H}from"./runDrizzle-DAtZbzBn.mjs";import{b as yo,j as Et,D as ie,r as Me,W as $o,e as le,h as Eo,t as mo,u as vo,i as So,q as Jt,a as _n,g as Ro}from"./do-sql-DT8JBpG8.mjs";import{AGG_VALUE as He,AGG_COUNT as wt,AGG_KEY as Ke,doWhereSqlStrategy as ye,jsonPathSql as $e}from"./AGG_COUNT-DzvM-UU5.mjs";import{renderSql as Tn,unionAll as An}from"./param-Y0zw_1Cv.mjs";import{a as _o,u as To}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as Ao,boundingBoxGeohashes as Io,haversineMeters as bo,pointInBoundingBox as Co}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as xo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Mo,assertPatchAllowed as Do,operatorFields as ko,readPatchField as Yt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Lo,encodeCursor as mt,nullsOrderSuffix as Fo,normalizeOrderKeys as Xt,uniqueIndexFields as Wo,buildSeekWhere as Bo,decodeCursor as Zt,buildSeekBeforeWhere as Po,softDeleteScope as Ce,applySelect as In}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as en,sortColumnName as tn,resolveRankPartition as qo,encodePartitionKey as Oo,RANK_TIEBREAK as Uo}from"./RANK_TIEBREAK-BknRdgt8.mjs";import Go from"./rankPivotConditionSql-CUX4Vuhv.mjs";import{UNVOUCHABLE_DEP as nn}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as jo,withUnknownIndexKeys as Ho,indexKeysForRow as Ko,buildIndexRange as No}from"./buildIndexRange-BTChxh3k.mjs";import Ee from"./runSql-BBRXi81G.mjs";import{r as Ye,j as De,c as ne,t as et,i as on}from"./where-sql-AVR5KloI.mjs";import{serializeSqlValue as ke}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Le}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Qo,isPushableWhere as zo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Vo,findRelated as Jo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as pt,findManyPage as Yo,relationPredicateTables as Xo,resolveRelationPredicates as Zo,composeReadPredicate as er}from"./DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs";import{bindRelationWrites as tr,describeSchemaRelationWrites as nr}from"./describeRelationWrites-BKd7YU5R.mjs";import{runRowValidators as Ne,transformOnlyDefinition as or,applyInsertDefaults as vt,resolveWith as rr,relationHooks as ir,applyOnDelete as sr,fanOutScalarCounts as cr,CASCADE_MAX_ROWS as ar}from"./applyInsertDefaults-Bt6LYmPD.mjs";import{guardWriter as dr}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{WORKERD_SQLITE_LIMITS as bn}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{mayHoldProjectedValue as lr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as fr}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fe}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as rn,runTriggers as ur}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ps,migrateClientWatermark as qs,readClientWatermark as Os}from"./CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{IDEMPOTENCY_TABLE as Gs,readIdempotent as js,trimIdempotent as Hs,writeIdempotent as Ks}from"./IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{runShardMigrations as Qs}from"./runShardMigrations-DeOECCjz.mjs";import{selectShapeMembers as Vs,selectShapeRows as Js}from"./selectShapeMembers-BP30uxpp.mjs";const hr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},wr=()=>new v("INVALID_CURSOR","invalid cursor"),sn=16,cn=8,Z=1024,It=(n,i)=>i.query(n),pr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,a]of i.entries()){const w=s===i.length-1;let g=0;for(const m of n)(w?m.startsWith(a):m===a)&&(g+=1);if(g===0)return 0;o+=g}return o},gr=(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 a=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:a+String.fromCodePoint(s)}},yr=(n,i,o)=>{const s={eq:(a,w)=>{if(!n.definition.filterFields?.includes(a))throw new v("INTERNAL",`field "${a}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=cn)throw new v("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(cn)} .eq() filters are supported per search query`);return n.filters.push({field:a,value:w}),s},search:(a,w)=>{const g=n;if(a!==g.definition.field)throw new v("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${a}"`);const m=It(w,o).length;if(m>sn)throw new v("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(sn)} search terms are supported (got ${String(m)})`);return g.field=a,g.query=w,g.hasQuery=!0,s}};return s},$r=n=>{if(n.length>Z)throw new v("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),mr=n=>btoa(`search:${String(n)}`),vr=n=>{let i;try{i=hr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Sr=n=>{if(typeof n.endCursor=="string")throw new v("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 v("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?vr(n.cursor):0;if(o===void 0)throw wr();if(o+i>=Z)throw new v("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}},Rr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?mr(o):null,isDone:!s,page:n.slice(i.offset,o)}},_r=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 v("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Cn=500,xn=(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??Cn},Mn=(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)`)},Tr=32,Ar=1024,Dn=(n,i,o,s)=>{const a=`SELECT id, _creationTime, ${Le(ie)} FROM ${Le(n)}`,w=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Ye(`${a} ${w}`):De(`${a} WHERE `,i,` ${w}`)},tt={fieldRef:n=>Ye(Et(n)),rangeTypeGuard:(n,i)=>Ye(yo(n,i)),serialize:ke},Ir=n=>n===void 0?"":Fo(n==="first"),kn=n=>{const i=n.map(o=>`${Et(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ir(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${Et("id")} ${Lo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},br={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ln=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Cr=n=>{const i=Ln(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},xr=(n,i)=>{const o=n.order,s=Cr(n),{shape:a}=i;return s.length>0?Xt(s.map(w=>({[w]:o})),a,{pinned:Ln(n),uniqueBy:Wo(i.indexes,a)}):Xt([{_creationTime:o}],a)},Mr=(n,i,o,s)=>{const a=n.sqlConditions.map(w=>({[w.field]:{[br[w.comparator]??"eq"]:w.value}}));if(o&&a.push(Bo(i,Zt(o))),s&&a.push(Po(i,Zt(s))),a.length!==0)return a.length===1?a[0]:{AND:a}},Dr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Tr):n.want},St=(n,i,o,s,a,w,g)=>{const m=xr(s,o),y=kn(m),p=[],{filters:x,want:T}=w;let A=w.cursor??void 0,C=Dr(w);if(T===0)return{documents:p,orderKeys:m};for(;;){const B=ne(Mr(s,m,A,w.endCursor),tt,et),q=Dn(i,a&&B?De(B," AND ",a):a??B,y,C),F=Ee(n,q.text,...q.params).toArray();let O={};g(F.length);for(const K of F)if(O=Me(K),x.every(ue=>ue(O))&&p.push(O)===T)return{documents:p,orderKeys:m};if(C===void 0||F.length<C)return{documents:p,orderKeys:m};A=mt(O,m),C=Math.max(C,Math.min(C*2,Ar))}},kr=(n,i,o,s,a,w,g,m)=>{const y=Math.max(0,Math.floor(a.numItems));if(typeof a.endCursor=="string"){const{documents:B,orderKeys:q}=St(n,i,o,s,w,{cursor:a.cursor,endCursor:a.endCursor,filters:g.all,selective:g.selective,want:void 0},m),F=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:a.endCursor,isDone:!0,page:B,splitCursor:F?mt(F,q):null}}const{documents:p,orderKeys:x}=St(n,i,o,s,w,{cursor:a.cursor,filters:g.all,selective:g.selective,want:y+1},m),T=p.length>y,A=T?p.slice(0,y):p,C=A.at(-1);return{continueCursor:T&&C?mt(C,x):null,isDone:!T,page:A}},nt=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const a=n(Le(o));return i.set(o,a),a}},me=Le(ie),Lr=nt(n=>`INSERT INTO ${n} (id, _creationTime, ${me}) VALUES (?, ?, ?)`),an=nt(n=>`UPDATE ${n} SET ${me} = ? WHERE id = ? AND ${me} = ?`),Fr=nt(n=>`UPDATE ${n} SET _creationTime = ?, ${me} = ? WHERE id = ? AND ${me} = ?`),Wr=nt(n=>`DELETE FROM ${n} WHERE id = ? AND ${me} = ?`),Br="SELECT changes() AS changed",dn=new Map,Pr="",qr=n=>{const i=JSON.stringify(n),o=dn.get(i);if(o!==void 0)return o;const s=n.map(w=>h`SELECT ${h.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${h.identifier(ie)} FROM ${h.identifier(w)} WHERE id = ${Pr}`),{sql:a}=Tn("sqlite",h`${An(s)} LIMIT 1`);return dn.set(i,a),a},Or=(n,i)=>i.map(()=>n),Ur=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Gr=n=>{if(!Ur.test(n))throw new v("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new v("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},jr=(n,i,o,s)=>{if(o!==!0)return;const a=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const g=a?vt(n,w,s)._id:w._id;typeof g=="string"&&Rt(g)}},ln=50,Qe=Math.floor(bn.boundParams/3),fn=bn.boundParams,Hr=128,Xe=n=>new v("BATCH_LIMIT_EXCEEDED",n,{status:400}),ze=(n,i,o)=>{Mn(n,xn(i,o,Xe),o,Xe)},un=async(n,i,o,s,a)=>{const w=xn(s,a,Xe),{page:g}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>w&&Mn(Math.max(await n.count(i,{where:o}),g.length),w,a,Xe),g},Kr=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},Nr=n=>Math.max(n,Z),Fn=(n,i)=>{const o=n.filters.map(s=>h`${$e(s.field)} = ${ke(s.value)}`);return i&&o.push(i),o},Qr=(n,i,o,s,a)=>{const w=It(o.query,At(o.definition.language));if(w.length===0)return[];const g=to(i,o.indexName),m=`${g}__vocab`,y=w.length-1,p=w.map((q,F)=>{const O=gr(q,F===y),K=O.exact?h`${h.identifier("term")} = ${O.lower}`:h`${h.identifier("term")} >= ${O.lower} AND ${h.identifier("term")} < ${O.upper}`;return h`SELECT ${h.identifier("doc")}, ${h.raw(String(F))} AS ${h.identifier("__term__")}, COUNT(*) AS ${h.identifier("__n__")} FROM ${h.identifier(m)} WHERE ${K} GROUP BY ${h.identifier("doc")}`}),x=w.map((q,F)=>h`SUM(CASE WHEN u.${h.identifier("__term__")} = ${h.raw(String(F))} THEN u.${h.identifier("__n__")} ELSE 0 END)`),T=h`SELECT f.${h.identifier(Ge)} AS ${h.identifier(Ge)}, ${h.join(x,h` + `)} AS ${h.identifier("__score__")} FROM (${An(p)}) u JOIN ${h.identifier(g)} f ON f.rowid = u.${h.identifier("doc")} GROUP BY f.${h.identifier(Ge)} HAVING ${h.join(x.map(q=>h`${q} > 0`),h` AND `)}`,A=Fn(o,a);let C=h`SELECT m.id, m._creationTime, m.${h.identifier(ie)}, s.${h.identifier("__score__")} AS ${h.identifier("__score__")} FROM (${T}) s JOIN ${h.identifier(i)} m ON m.id = s.${h.identifier(Ge)}`;A.length>0&&(C=h`${C} WHERE ${h.join(A,h` AND `)}`),C=h`${C} ORDER BY s.${h.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${h.raw(String(s))}`;const B=[];for(const q of H(n,C)){const F=_n(q);if(F){const O=q.__score__;B.push({document:F,score:typeof O=="number"?O:Number(O??0)})}}return B},zr=(n,i,o,s,a)=>{const w=At(o.definition.language),g=It(o.query,w);if(g.length===0)return[];const m=Fn(o,a);let y=h`SELECT id, _creationTime, ${h.identifier(ie)} FROM ${h.identifier(i)}`;m.length>0&&(y=h`${y} WHERE ${h.join(m,h` AND `)}`),y=h`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${h.raw(String(Nr(s)))}`;const p=H(n,y).toArray(),x=[];for(const T of p){const A=_n(T);if(!A)continue;const C=pr(no(A,o.definition),g);C>0&&x.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:C})}return x.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),x.slice(0,s).map(T=>({document:T.doc,score:T.score}))},gt=(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 v("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Vr=(n,i)=>{const o=n,s={near:(a,w)=>{if(o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(a,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:a.lat,lng:a.lng},radiusMeters:w},s},within:a=>{if(o.near)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(a.sw,".within() sw corner",i,o.indexName),gt(a.ne,".within() ne corner",i,o.indexName),a.sw.lat>a.ne.lat)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(a.sw.lng>a.ne.lng)throw new v("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:a.ne.lat,lng:a.ne.lng},sw:{lat:a.sw.lat,lng:a.sw.lng}},s}};return s},Jr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:a}=o;return typeof s=="number"&&typeof a=="number"?{lat:s,lng:a}:void 0},Yr=(n,i)=>{const o=Jr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const a=bo(i.near.point,o);return a<=i.near.radiusMeters?{creationTime:s,distance:a}:void 0}return Co(o,i.within)?{creationTime:s,distance:0}:void 0},Xr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const a=o.near?Ao(o.near.point,o.near.radiusMeters):Io(o.within),w=Ro(i,o.indexName),g=a.map(T=>h`(g.${h.identifier("__geohash__")} >= ${T} AND g.${h.identifier("__geohash__")} < ${`${T}{`})`),m=[h`(${h.join(g,h` OR `)})`];s&&m.push(s);const y=h`SELECT m.id, m._creationTime, m.${h.identifier(ie)} FROM ${h.identifier(w)} g JOIN ${h.identifier(i)} m ON m.id = g.${h.identifier("__id__")} WHERE ${h.join(m,h` AND `)}`,p=H(n,y).toArray(),x=[];for(const T of p){const A=Me(T),C=A?Yr(A,o):void 0;A&&C&&x.push({creationTime:C.creationTime,distance:C.distance,doc:A})}return x.sort((T,A)=>T.distance-A.distance||A.creationTime-T.creationTime),x},Wn=(n,i,o,s)=>{const a=[];for(const w of n)if(i.every(g=>g(s(w)))&&(a.push(w),typeof o=="number"&&a.length>=o))break;return a},Zr=(n,i,o,s,a,w=()=>{})=>{const g=o.within!==void 0,m=Xr(n,i,o,a).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return w(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},hn=(n,i,o,s,a,w,g=()=>{})=>{const{geo:m}=o;if(!m)throw new v("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=a.length>0,p=Zr(n,i,m,y?void 0:w,s,g);return y?Wn(p,a,w,x=>x.document):p},wn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&lr(s))throw new v("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)`)},ei=n=>{let i=0;const o=[],s={...tt,relationExists:a=>{const{childWhere:w,negated:g,parentTable:m,relation:y}=a,p=`__rel_${String(i)}`,x=o.at(-1)??m;i+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,C=Ye(`${Jt(p,A)} = ${Jt(x,T)}`);o.push(p);const B=ne(w,s,et);o.pop();const q=B===void 0?C:De(C," AND ",B),F=De("EXISTS (SELECT 1 FROM ",on(y.table)," AS ",on(p)," WHERE ",q,")");return g?De("NOT ",F):F}};return s};class ti extends v{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ni=/\s/u,oi=String.fromCodePoint(0),pn=(n,i,o)=>{if(!n.tables[i])throw new v("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ni.test(o)||o.includes(oi)?null:o},Bn=(n,i,o,s=()=>{},a=()=>{},w=()=>{},g)=>{const m=i.tables[o];if(!m)throw new v("INTERNAL",`unknown table: ${o}`);const y=Ce(m.softDeleteMode,void 0),p=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},x=()=>{const R=Q(y,p.pushedWhere);return R?ne(R,ye):void 0},T=()=>{const R=Q(y,p.pushedWhere);return R?ne(R,tt,et):void 0},A=()=>[...p.inMemoryFilters,...p.verifyFilters];let C=0;const B=R=>{const{search:M}=p;if(!M)throw new v("INTERNAL","runSearchFetch called without a staged search");ao(vo(n),o,m);const k=p.inMemoryFilters.length>0,L=_r(k?void 0:R),se=So(n);if(se&&!lo(n,o,M.definition))throw new v("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 P=x(),ce=se?Qr(n,o,M,L,P):zr(n,o,M,L,P);!k&&R===void 0&&$r(ce);const ae=A();return C=ce.length,ae.length>0?Wn(ce,ae,R,ve=>ve.document):ce},q=R=>B(R).map(M=>M.document),F=R=>{const M=Sr(R);return Rr(q(Er(M)),M)},O=()=>{if(p.search||p.geo||p.indexName===void 0){a(void 0);return}a(No(o,p.indexName,p.indexFields,p.sqlConditions,ke))},K=R=>{O();let M=0;const k=(()=>{if(p.search){const L=q(R);return M=C,L}return p.geo?hn(n,o,p,x(),A(),R,L=>{M=L}).map(L=>L.document):St(n,o,m,p,T(),{filters:A(),selective:p.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},L=>{M+=L}).documents})();return w(Math.max(M,k.length)),k},ue=()=>{if(!p.search&&!p.geo)throw new v("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let R=0;const M=(()=>{if(p.search){const k=B(void 0);return R=C,k}return hn(n,o,p,x(),A(),void 0,k=>{R=k})})();return w(Math.max(R,M.length)),M},z={async*[Symbol.asyncIterator](){const R=Bn(n,i,o,s,a,w,{...p,indexFields:[...p.indexFields],inMemoryFilters:[...p.inMemoryFilters],sqlConditions:[...p.sqlConditions],verifyFilters:[...p.verifyFilters]});if(p.search){yield*await R.collect();return}let M;for(;;){const k=await R.paginate({cursor:M??null,numItems:Hr});if(yield*k.page,k.isDone||k.continueCursor===null)return;M=k.continueCursor}},async collect(){return K(void 0)},async collectWithScores(){return ue()},filter(R){const M=Qo(R);return M!==void 0&&zo(M,m.shape)?(p.pushedWhere=Q(p.pushedWhere,M),p.verifyFilters.push(R)):p.inMemoryFilters.push(R),z},async first(){return K(1)[0]??null},order(R){return p.order=R==="desc"?"desc":"asc",z},async paginate(R){let M=0;if(O(),p.search){const L=F(R);return w(L.page.length),L}if(p.geo)throw new v("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=kr(n,o,m,p,R,T(),{all:A(),selective:p.inMemoryFilters.length>0},L=>{M+=L});return w(Math.max(M,k.page.length)),k},async take(R){return K(R)},async unique(){const R=K(2);if(R.length>1)throw new ti(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,M){const k=(m.geoIndexes??[]).find(se=>se.name===R);if(!k)throw new v("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const L={definition:k,indexName:R};if(p.geo=L,M(Vr(L,o)),!L.near&&!L.within)throw new v("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(R,M){const k=m.indexes.find(L=>L.name===R);if(!k)throw new v("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),p.indexName=R,p.indexFields=k.fields,M&&M(Kr(p)),z},withSearchIndex(R,M){const k=(m.searchIndexes??[]).find(se=>se.name===R);if(!k)throw new v("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const L={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:R,query:""};if(p.search=L,M(yr(L,o,At(k.language))),!L.hasQuery)throw new v("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return z}};return z},yt=(n,i,o,s)=>{const a=o;for(const[w,g]of mo(n)){if(g.serverDefault){w in i&&(a[w]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(w in i)&&(a[w]=g.onUpdateFn())}},gn=5,yn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new v("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},$n=["_commitSeq","_creationTime","_id"],Ve=n=>$n.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!$n.includes(i))):n,ri=/unique constraint failed/i,ii=n=>n instanceof Error&&ri.test(n.message),si=/string or blob too big/iu,ci=(n,i)=>{if(!(!(n instanceof Error)||!si.test(n.message)))throw new v("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.`)},_t=(n,i,o,s)=>{try{Ee(n,o,...s)}catch(a){throw ii(a)?new fe(`unique constraint violation on "${i}"`,"unique"):(ci(a,i),a)}},Je=(n,i,o,s)=>{if(_t(n,i,o,s),Ee(n,Br).one().changed===0)throw new fe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},En=(n,i,o,s,a,w,g)=>{const m=[];for(let T=0;T<o.length+1;T+=1){const A=o[T],C=s[T],B=C?.direction==="desc"?"desc":"asc",q=A===void 0||C===void 0?h`${h.identifier(Uo)} < ${g}`:Go(A,w[T],B,!1);if(q===void 0)continue;const F=[];for(let K=0;K<T;K+=1)F.push(h`${h.identifier(o[K])} IS ${w[K]}`);F.push(q);const[O]=F;m.push(F.length===1&&O!==void 0?O:h`(${h.join(F,h` AND `)})`)}const y=m.length>0?h.join(m,h` OR `):h`1 = 0`,p=H(n,h`SELECT COUNT(*) AS c FROM ${h.identifier(i)} WHERE ${h.identifier("__partition__")} = ${a} AND (${y})`).one(),x=H(n,h`SELECT COUNT(*) AS c FROM ${h.identifier(i)} WHERE ${h.identifier("__partition__")} = ${a}`).one();return{before:p.c,total:x.c}},ai=n=>{const i=new Map;for(const[s,a]of Object.entries(n.tables))for(const w of Object.values(a.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:s,op:w.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const a=new Set,w=[s];for(let g=w.pop();g!==void 0;g=w.pop())for(const{holder:m,op:y}of i.get(g)??[]){if(m===s||rn(n,m,y))return!0;a.has(m)||(a.add(m),w.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([s,a])=>a.shardMode?.kind==="global"||rn(n,s,"delete")||o(s)).map(([s])=>s))},di=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},mn=new WeakMap,li=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const a of n)o.call(s,a,a,i)},has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.values()});return i},fi=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const[a,w]of n)o.call(s,w,a,i)},get:o=>n.get(o),has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.entries()});return i},ui=n=>{const i=mn.get(n);if(i!==void 0)return i;const o=Object.freeze(Vo(n).map(g=>Object.freeze(g))),s=new Map,a=g=>(n.tables[g]?.shardMode?.kind??"root")==="root";for(const g of o)!g.array&&a(g.sourceTable)&&a(g.targetTable)&&s.set(g.sourceTable,[...s.get(g.sourceTable)??[],g]);for(const g of s.values())Object.freeze(g);const w={checkedForeignKeys:s,deleteRereadTables:li(ai(n)),relationEdges:o,relationWrites:nr(n),softDeleteFields:fi(di(n))};return mn.set(n,w),w},$t=new WeakMap,hi=(n,i)=>{let o=$t.get(i.tables);if(!$t.has(i.tables)){const a=Object.keys(i.tables).map(w=>w.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=a.length===0?void 0:new RegExp(`"(${a.join("|")})"`,"gu"),$t.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const a of n.matchAll(o))s.add(a[1]);return s.size===1?[...s][0]:void 0},wi=(n,i,o)=>{for(const s of n){const a=s,w=a?.[ie];if(typeof w=="string"){const g=a?.id,m=To(w);typeof g!="string"?i.recordReadBytes(m):o===void 0?i.recordDocumentRead(`${g}\0${String(m)}`,m):i.recordDocumentRead(`${o}\0${g}`,m)}}},pi=(n,i,o)=>{if(i===void 0)return n;const s=(a,...w)=>{const g=n.exec(a,...w),m=g.one.bind(g),y=g[Symbol.iterator].bind(g),p=o===void 0?void 0:hi(a,o);let x=!1;const T=A=>{wi(A,i,p)};return g.toArray=()=>{const A=[];for(const C of{[Symbol.iterator]:y})T([C]),A.push(C);return A},g.one=()=>{x=!0;try{const A=m();return T([A]),A}finally{x=!1}},g[Symbol.iterator]=function*(){for(const C of{[Symbol.iterator]:y})x||T([C]),yield C},g};return new Proxy(n,{get:(a,w)=>w==="exec"?s:w===$o?a:Reflect.get(a,w,a)})},gi=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),yi=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=_o(n);if(s===void 0)return;const a=n._id;typeof a=="string"?o.recordDocumentRead(`global\0${i}\0${a}`,s):o.recordReadBytes(s)},Ze=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const a=n;switch(i){case"lookup":{xe(a.row,typeof a.tableName=="string"?a.tableName:o,s);return}case"page":{for(const w of a.page??[])xe(w,o,s);return}case"rows":{for(const w of Array.isArray(n)?n:[n])xe(w,o,s);return}default:for(const w of Array.isArray(n)?n:[])xe(w.document,o,s)}},Pn=(n,i,o)=>new Proxy(n,{get:(s,a)=>{const w=Reflect.get(s,a,s);if(typeof w!="function")return w;if(a===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(w,s,[]))xe(y,i,o),yield y};const g=yi.get(a);return(...m)=>{const y=Reflect.apply(w,s,m);return g!==void 0?Promise.resolve(y).then(p=>(Ze(p,g,i,o),p)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Pn(y,i,o):y}}}),$i=new Set(["findFirst","findFirstOrThrow","findMany"]),Ei=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),a=s.with,w=g=>In(g,o,a);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:w(g.page)}:w([g])[0]}},vn=256,Tt=4096,mi=1024*1024,vi=async(n,i,o,s)=>{const a=i[1]??{},w=[];let{cursor:g}=a,m=vn,y=0;for(;;){const p=await n([i[0],{...a,cursor:g,limit:m},...i.slice(2)]);if(Array.isArray(p))return Ze(p,"rows",o,s),[...w,...p];const x=s.headroom().readBytes;if(Ze(p,"page",o,s),w.push(...p.page),p.isDone||typeof p.continueCursor!="string")return{continueCursor:null,isDone:!0,page:w};g=p.continueCursor,y+=s.headroom().readBytes-x,m=y>0?Math.min(Tt,Math.max(vn,Math.floor(mi*w.length/y))):Tt}},Si=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const a=Reflect.get(o,s,o);if(typeof a!="function")return a;if(s==="query")return(...g)=>Pn(Reflect.apply(a,o,g),String(g[0]),i);const w=gi.get(s);return w===void 0?a:async(...g)=>{const m=$i.has(s)?Ei(g):void 0;let y=m?.args??g;const p=String(g[0]),x=y[1],T=s==="findMany"&&typeof x?.endCursor=="string",A=s==="findMany"&&typeof x?.limit!="number"&&!T;if(T&&typeof x.limit!="number"&&(y=[y[0],{...x,limit:Tt},...y.slice(2)]),A){const B=await vi(q=>Reflect.apply(a,o,q),y,p,i);return m===void 0?B:m.project(B,w)}const C=await Reflect.apply(a,o,y);return Ze(C,w,p,i),m===void 0?C:m.project(C,w)}}}),Sn=new WeakMap,Rn=new WeakMap,Ri=500,_i=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,a=Sn.get(n)??{value:void 0},w=Rn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};Sn.set(e,a),Rn.set(e,w),g=_i(e)}return g},y=pi(n.sql,s,n.schema),{schema:p}=n,x=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(p.tables,e))throw new v("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},{checkedForeignKeys:A,deleteRereadTables:C,relationEdges:B,relationWrites:q,softDeleteFields:F}=ui(p),O=(e,t,r)=>{for(const c of A.get(e)??[]){const d=t[c.column];if(typeof d!="string"||r?.[c.column]===d||c.targetTable===e&&t._id===d)continue;if(H(y,h`SELECT 1 FROM ${h.identifier(c.targetTable)} WHERE id = ${d} LIMIT 1`).toArray().length===0)throw new v("VALIDATION_ERROR",`${c.name} references ${c.targetTable} row "${d}", which does not exist`)}},K=tr(q,n.inTransaction),ue=()=>n.inTransaction?.()===!0,z=e=>p.tables[e]?.commitOrderedMode!==!0?{}:((a.value===void 0||!ue())&&(a.value=ho(y)),{[wo]:a.value}),R=(e,...t)=>{const r=p.tables[e]?.indexes??[],c=[];let d;for(const u of t)u&&(typeof u._id=="string"&&u._id!==d&&(d=u._id,c.push(jo(d))),c.push(...Ho(r,Ko(r,u,ke))));return c.length>0?c:void 0},M=n.onRead??(()=>{}),k=e=>{zt(p.tables[e])&&M(nn,nn)},L=n.onReadRange??(e=>{M(e.table,G)}),se=e=>{k(e.table),L(e)},P=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),k(e),M(e,t,r)},ce=(e,t)=>{const r=e.row._id;P(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ae=n.onIndexUse??(()=>{}),ve=n.onWrite??(()=>{}),ee=e=>{s?.recordWrite(e)},Se=async e=>{ee(e.doc),await ve(e)},{cache:he}=n,Re=n.clock??(()=>Date.now()),bt=n.idGenerator??(()=>crypto.randomUUID()),Ct=n.scheduler??ro,_e=Si(n.globalDb,s),we=n.auth??{identity:null,userId:null},xt=n.cdc??!1,ot=Ct,qn=fr({scheduler:typeof ot.list=="function"&&typeof ot.get=="function"?ot:void 0,storage:n.storage}),Te=(e,t,r,c)=>{xt&&!zt(p.tables[e])&&fo(y,Re(),e,t,r,c)},Mt=(e,t,r,c)=>{const d=p.tables[e];if(d?.dropStalePatchesMode!==!0||!xt)return!1;const u=i?.();if(u===void 0)return!1;const l=uo(y,e,t,u);if(l===void 0)return!1;const f=ko(d,r);return Object.keys(Ve(r)).some(E=>!f.has(E)&&Nt(Yt(l,E))!==Nt(Yt(c,E)))},te=e=>p.tables[e]?.shardMode?.kind==="global",Dt=(e,t)=>{if(te(e)){if(!_e)throw new v("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return _e}return U},rt=e=>Dt(e,"cascade"),j=(e,t)=>{if(te(e)){if(!_e)throw new v("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return _e}},Ae=(e,t)=>{P(e,G);for(const r of Xo(Q(t.baseWhere,t.where),p,e,t.relationBaseWhere))P(r,G)},Y=(e,t,r)=>{he?.invalidateTable(t),x({key:r,op:e,table:t})},kt=(e,t,r)=>{x({key:r,op:"insert",row:{...t,_id:r},table:e})},it=async(e,t,r,c,d)=>{d&&ee(r);const u=await e.insert(t,r,c);return kt(t,r,u),u},Lt=async(e,t,r,c)=>{if(e.insertMany===void 0){const u=[];for(const l of r)u.push(await it(e,t,l,{allowExplicitId:c},!1));return u}const d=await e.insertMany(t,r,{allowExplicitId:c,limit:Number.POSITIVE_INFINITY,onStored:(u,l)=>{for(const[f,E]of u.entries()){const b=r[l+f];if(b===void 0)throw new v("INTERNAL",`insertMany on global table '${t}' reported row ${String(l+f)} of ${String(r.length)}`);kt(t,b,E)}}});return r.map((u,l)=>{const f=d[l];if(typeof f!="string")throw new v("INTERNAL",`insertMany on global table '${t}' returned no id for row ${String(l)}`);return f})},On=async(e,t,r)=>{if(e.patchMany===void 0)throw new v("INTERNAL",`patchMany on global table '${t}' needs a global writer with patchMany`);for(const{patch:d}of r)ee(d);const c=new Set;try{return await e.patchMany(t,r,{limit:Number.POSITIVE_INFINITY,onStored:d=>{for(const u of d)c.add(u),Y("update",t,u)}})}finally{for(const{id:d}of r)c.has(d)||(c.add(d),Y("update",t,d))}},Un=(e,t)=>Dt(e,"relation load").findMany(e,t),Gn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ft=e=>{for(const t of e===void 0?[]:Gn(e))te(t)&&P(t,G)},Wt=(e,t)=>{const r=p.tables[e]?.relationMap??{};for(const[c,d]of Object.entries(t??{})){if(c==="_count"){for(const l of Object.keys(typeof d=="object"?d:{}))Ft(r[l]);continue}const u=r[c];u===void 0||d===void 0||d===!1||(Ft(u),typeof d=="object"&&Wt(u.table,d.with))}},st=(e,t)=>(te(e)&&(P(e,G),Wt(e,t.with)),Un(e,t)),jn=e=>!te(e.table),Bt=n.relationExistsPushDown??"auto",Pt=Bt!=="never",{maxRelationKeys:qt}=n,Fe=(e,t,r)=>Zo(e,{fetcher:st,maxRelationKeys:qt,relationBaseWhere:r,schema:p,tableName:t}),Hn=async(e,t,r,c,d)=>{const u=j(e,"relation grouped count");if(u)return Ae(e,{relationBaseWhere:d,where:c}),cr((W,N)=>u.count(W,{relationBaseWhere:d,where:N}),e,t,r,c);const l=p.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);P(e,G);const f=Ce(l.softDeleteMode,void 0),E={[t]:{in:r}},b=Q(Q(E,c),f),_=await Fe(b,e,d),D=ne(_,ye),S=$e(t);let I=h`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${h.identifier(e)}`;D&&(I=h`${I} WHERE ${D}`),I=h`${I} GROUP BY ${S}`;const $=H(y,I).toArray();return new Map($.map(W=>[W.__fk__,W.count]))},Ot=new Set;for(const[e,t]of Object.entries(p.tables))for(const r of Object.values(t.triggerMap??{}))Ot.add(`${e} ${r.timing} ${r.op}`);const oe=(e,t,r)=>Ot.has(`${e} ${t} ${r}`),re=async(e,t,r)=>{if(w.value+=1,w.value>ln)throw w.value-=1,new fe(`trigger recursion exceeded ${String(ln)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await ur({ctx:Zn,event:r,op:t,schema:p,tableName:r.table,timing:e})}finally{w.value-=1}},{ensureBackfilledForTable:Ie,ensureBackfilledIndex:ct,ensureRankBackfilled:at,ensureRankBackfilledForTable:be,syncAggregates:We,syncCompanionsForInsert:dt,syncGeo:Be,syncRanks:pe,syncSearch:Pe}=po({broadcast:x,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,r)=>he?.invalidate(e,t,R(e,r)),recordCdc:Te,schema:p,sql:y,verified:n.companionMemo?.verified}),Kn=async(e,t)=>{const r=t.filter(({document:c,id:d})=>{try{return dt(e,d,c),!0}catch(u){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${d}" in "${e}" could not be synced:`,u),!1}});for(const{document:c,id:d}of r)if(X(d,e)?.docJson===le(c))try{await ve({doc:c,id:d,op:"insert",table:e})}catch(u){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${d}" in "${e}" failed:`,u)}},Ut=(e,t,r)=>{const{shardMode:c}=t;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(r.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${c.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})},Gt=e=>Object.entries(p.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),de=e=>e===void 0||te(e)?_e:void 0,Nn=e=>Object.entries(p.tables).flatMap(([t,r])=>te(t)?Object.values(r.relationMap??{}).flatMap(c=>c.through!==void 0||c.kind!=="one"||c.table!==e?[]:c.onDelete!=="cascade"&&c.onDelete!=="set null"?[]:[{action:c.onDelete==="cascade"?"delete":"update",field:c.field,holderTable:t,references:c.references}]):[]),Qn=async(e,t,r,c)=>r==="_id"?c:(await e.get(t,c))?.[r],zn=async(e,t,r,c,d)=>{const u=[];let l;do{const f=await e.findMany(t,{cursor:l,includeDeleted:d,limit:Ri,where:{[r]:c}});for(const E of f.page)u.push(String(E._id));l=f.isDone?void 0:f.continueCursor??void 0}while(l!==void 0&&u.length<=ar);return u},Vn=async(e,t,r,c,d,u)=>{const{action:l,field:f,holderTable:E,references:b}=r,_=await Qn(e,t,b,c);if(_==null)return{effects:[],toExpand:[]};const D=await zn(e,E,f,_,u),S=D.filter($=>!d.announced.has(`${l}:${E}:${$}`)),I=l==="delete"?D.filter($=>!d.expanded.has(`${E}:${$}`)):[];for(const $ of S)d.announced.add(`${l}:${E}:${$}`);for(const $ of I)d.expanded.add(`${E}:${$}`);return{effects:S.map($=>({id:$,op:l,table:E})),toExpand:I}},jt=async(e,t,r,c,d)=>{const u=[];for(const l of Nn(t))for(const f of r){const E=await Vn(e,t,l,f,c,d);u.push(...E.effects),E.toExpand.length>0&&u.push(...await jt(e,l.holderTable,E.toExpand,c,d))}return u},qe=async(e,t,r,c,d=!1)=>{for(let l=0;l<r.length;l+=1)ee(void 0);const u=c?.skipOnDelete===!0?[]:await jt(e,t,r,{announced:new Set,expanded:new Set},c?.hard===!0);try{if(d&&e.deleteMany!==void 0){const l=new Set;try{return await e.deleteMany(t,r,{limit:Number.POSITIVE_INFINITY,onStored:f=>{for(const E of f)l.add(E),Y("delete",t,E)}})}finally{for(const f of new Set(r))l.has(f)||Y("delete",t,f)}}for(const l of r)try{await e.delete(t,l,c)}finally{Y("delete",t,l)}return{deleted:r.length}}finally{for(const l of u)Y(l.op,l.table,l.id)}},X=(e,t)=>{const r=Gt(t);for(let c=0;c<r.length;c+=fn){const d=r.slice(c,c+fn),[u]=Ee(y,qr(d),...Or(e,d)).toArray();if(!u)continue;const l=u.__t__,f=Me(u);if(typeof l!="string"||!f)return;const E=u[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:f,tableName:l}}},Ht={assertRankPartitionLocal:Ut,ensureRankBackfilled:at,onRead:P,rowToDocument:Me,schema:p,sql:y},Jn=(e,t,r)=>{const c=ne(r,ye);return c===void 0||H(y,h`SELECT 1 FROM ${h.identifier(e)} WHERE ${h.identifier("id")} = ${t} AND ${c}`).toArray().length>0},Yn=(e,t,r,c)=>Mt(e,t,r,c)?(o?.({fields:Object.keys(Ve(r)),id:t,table:e}),!0):!1,Xn=async(e,t,r,c,d)=>{const u=X(t,e);if(!u)return{applied:!1,doc:null};if(P(e,t),!Jn(e,t,r.where)||Yn(e,t,r.patch,u.row))return{applied:!1,doc:u.row};try{await d(r.patch)}catch(l){if(l instanceof fe&&l.kind==="occ"&&c)return;throw l}return{applied:!0,doc:X(t,e)?.row??null}},Kt=async(e,t,r,c)=>{const{fetchLimit:d,limit:u,orderKeys:l,predicate:f}=await er(t,r,{canPushExists:Pt?jn:void 0,existsPushMode:Bt==="always"?"always":"auto",fetcher:st,maxRelationKeys:qt,schema:p,tableName:e}),E=Pt?ei(c):tt,b=ne(f,E,et),_=Dn(e,b,kn(l),d);return{limit:u,orderKeys:l,statement:_}},U={system:qn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return Ae(e,t),r.aggregate(e,t);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);if(je(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 v("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);P(e,G);const d=Ce(c.softDeleteMode,void 0),u=Q(Q(t.baseWhere,t.where),d),l=await Fe(u,e,t.relationBaseWhere),f=l!==u;if(c.aggregateIndexes&&!t.baseWhere&&!f){const $=co(c.aggregateIndexes,t.op,t.field,t.where);if($){ct(e,$.index);const W=ft($.index.by??[],$.key),N=lt(e,$.index.name),V=H(y,h`SELECT ${He} AS value, ${wt} AS count FROM ${h.identifier(N)} WHERE ${Ke} = ${W}`).toArray()[0];return ut(t.op,V)}}wn(c,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=ne(l,ye),b=je(t.op),_=$e(t.field);let D=h`SELECT ${h.raw(b)}(${_}) AS value FROM ${h.identifier(e)}`;E&&(D=h`${D} WHERE ${E}`);const I=H(y,D).toArray()[0]?.value;return I??null},asId(e,t){const r=pn(p,e,t);if(r===null)throw new v("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return Ae(e,Qt(t)),r.count(e,t);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const d=Qt(t);if(d.restrictsCounts)throw new ht(e);P(e,G);const u=Ce(c.softDeleteMode,void 0),l=Q(Q(d.baseWhere,d.where),u),f=await Fe(l,e,d.relationBaseWhere),E=f!==l;if(c.aggregateIndexes&&!d.baseWhere&&!E){const S=so(c.aggregateIndexes,d.where);if(S){ct(e,S.index);const I=ft(S.index.by??[],S.key),$=lt(e,S.index.name),W=H(y,h`SELECT ${He} AS value FROM ${h.identifier($)} WHERE ${Ke} = ${I}`).toArray();return W[0]===void 0?0:W[0].value??0}}const b=ne(f,ye);let _=h`SELECT COUNT(*) AS count FROM ${h.identifier(e)}`;return b&&(_=h`${_} WHERE ${b}`),H(y,_).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const c=X(t,e);if(!c){const S=de(e);S&&await qe(S,e,[t],r);return}const{docJson:d,row:u,tableName:l}=c,f=p.tables[l],E=r?.hard===!0,b=!E&&f?.softDeleteMode?f:void 0,_=b?.softDeleteMode?.field;if(_&&u[_]!==null&&u[_]!==void 0)return;if(oe(l,"before","delete")&&await re("before","delete",{id:t,op:"delete",previous:u,table:l}),r?.skipOnDelete!==!0&&await sr({deletedId:t,deletedReference:S=>u[S],findHolders:async(S,I,$,W)=>(await rt(S).findMany(S,{...W,includeDeleted:E,where:{[I]:$}})).page,onCascade:(S,I)=>rt(S).delete(S,I,r),onRestrict:S=>{throw new fe(S,"restrict")},onSetNull:(S,I,$)=>rt(S).patch(S,I,{[$]:null}),schema:p,tableName:l}),Ie(l),be(l),b&&_){const S={[_]:Re()},I={...u,...z(l),...S,_id:t};yt(b,S,I,we),Je(y,l,an(l),[le(I),t,d]),Pe(l,t,I,u),Be(l,t,void 0),We(l,u,I),pe(l,t,u,void 0);const $=R(l,u,I);he?.invalidate(l,t,$),Te(l,t,"update",I),x({indexKeys:$,key:t,op:"update",row:I,table:l}),oe(l,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:u,table:l}),await Se({id:t,op:"delete",table:l});return}Je(y,l,Wr(l),[t,d]),Pe(l,t,void 0),Be(l,t,void 0),We(l,u,void 0),pe(l,t,u,void 0);const D=R(l,u);he?.invalidate(l,t,D),Te(l,t,"delete"),x({indexKeys:D,key:t,op:"delete",table:l}),oe(l,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:u,table:l}),await Se({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!p.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Cn),c=t?.hard===void 0?void 0:{hard:t.hard},d=j(e,"deleteAll");let u=0;for(;;){const f=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(E=>String(E._id));if(f.length===0)break;for(const E of f)await(d===void 0?U.delete(e,E,c):qe(d,e,[E],c)),u+=1;if(f.length<r)break}return{deleted:u}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),ze(t.length,r?.limit,"deleteMany");const c=te(e)?de(e):void 0;if(c)return qe(c,e,t,void 0,!0);for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const c=j(e,"deleteWhere"),u=(await un(c??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(c)return qe(c,e,u,void 0,!0);if(U.deleteMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,u,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 xo(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return Ae(e,t),t.consistency==="primary"&&M(e,go),r.findMany(e,t);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const d=!t.where&&!t.baseWhere;d?P(e,G):P(e);const{limit:u,orderKeys:l,statement:f}=await Kt(e,c,t,P),E=Ee(y,f.text,...f.params).toArray();d&&s?.recordRead(E.length);const b=[];for(const D of E){const S=Me(D);S&&(b.push(S),!d&&typeof S._id=="string"&&P(e,S._id))}const _=Yo(b,{endCursor:t.endCursor,limit:u,omitContinueCursor:t.omitContinueCursor,orderKeys:l});return t.with&&await rr({fetcher:st,groupedCounter:Hn,parents:_.page,...ir(t),schema:p,tableName:e,with:t.with}),{..._,page:In(_.page,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const{statement:d}=await Kt(e,c,t,()=>{}),u=Ee(y,`EXPLAIN QUERY PLAN ${d.text}`,...d.params).toArray();return{params:d.params,plan:u.map(l=>String(l.detail)),sql:d.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const r=X(t,e);if(!r){const c=de(e);return c?(M(e,t,!0),c.get(e,t)):(k(e),M(e,t,!0),null)}return ce(r,t),r.row},async lookupById(e,t){const r=X(e,t);if(!r){for(const c of Gt(t))k(c),M(c,e,!0);return null}return ce(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=j(e,"groupBy");if(r)return Ae(e,t),r.groupBy(e,t);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);P(e,G);const d=t.agg??{op:"count"};if(je(d.op),d.op!=="count"&&!d.field)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${d.op}" } }): "field" is required for non-count reducers`);const u=Ce(c.softDeleteMode,void 0),l=Q(Q(t.baseWhere,t.where),u),f=await Fe(l,e,t.relationBaseWhere),E=f!==l;if(c.aggregateIndexes&&!t.baseWhere&&!E){const $=io(c.aggregateIndexes,d.op,d.field,t.by,t.where),W=$===void 0?0:Object.keys($.partial).length,N=$?.index.by?.length??0;if($&&(W===0||W===N)){ct(e,$.index);const V=lt(e,$.index.name),J=Object.keys($.partial),ge=[];if(J.length===($.index.by??[]).length&&J.length>0){const Oe=ft($.index.by??[],$.partial),Ue=H(y,h`SELECT ${He} AS value, ${wt} AS count FROM ${h.identifier(V)} WHERE ${Ke} = ${Oe}`).toArray();return Ue.length>0&&ge.push({key:{...$.partial},value:ut(d.op,Ue[0])}),ge}const eo=H(y,h`SELECT ${Ke} AS key, ${He} AS value, ${wt} AS count FROM ${h.identifier(V)}`).toArray();for(const Oe of eo){const Ue=oo(JSON.parse(Oe.key));ge.push({key:Ue,value:ut(d.op,Oe)})}return ge}}for(const $ of[...t.by,d.field]){if($===void 0)continue;const W=$===d.field?`groupBy(${e}, { agg: { op: "${d.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;wn(c,$,W)}const b=ne(f,ye),_=t.by.map($=>h`${$e($)} AS ${h.identifier($)}`);if(d.op==="count")_.push(h`COUNT(*) AS value`);else{const{field:$}=d;if($===void 0)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${d.op}" } }): "field" is required for non-count reducers`);_.push(h`${h.raw(je(d.op))}(${$e($)}) AS value`)}let D=h`SELECT ${h.join(_,h`, `)} FROM ${h.identifier(e)}`;b&&(D=h`${D} WHERE ${b}`),D=h`${D} GROUP BY ${h.join(t.by.map($=>$e($)),h`, `)}`;const S=H(y,D).toArray(),I=[];for(const $ of S){const W={};for(const V of t.by)W[V]=Eo(c.shape[V],$[V]??null);const{value:N}=$;I.push({key:W,value:N==null?null:Number(N)})}return I},async insert(e,t,r){const c=j(e,"insert");if(c)return it(c,e,t,r,!0);const d=p.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);const u=r?.allowExplicitId===!0,l=Ne(d,vt(d,t,we),{supplied:t,table:e,trusted:u});let f;r?.clientId!==void 0?(Gr(r.clientId),f=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(Rt(l._id),f=l._id):f=bt();const E=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:Re(),b={...l,...z(e),_creationTime:E,_id:f};return oe(e,"before","insert")&&await re("before","insert",{doc:{...b},id:f,op:"insert",table:e}),u||O(e,b),Ie(e),be(e),_t(y,e,Lr(e),[f,E,le(b)]),dt(e,f,b),oe(e,"after","insert")&&await re("after","insert",{doc:b,id:f,op:"insert",table:e}),await Se({doc:b,id:f,op:"insert",table:e}),f},async insertManyUnsafe(e,t,r){if(ze(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const c=j(e,"insert");if(c){jr(p.tables[e],t,r?.allowExplicitId,we);for(const _ of t)ee(_);return Lt(c,e,t,r?.allowExplicitId)}const d=p.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);Ie(e),be(e);const u=[];for(let _=0;_<t.length;_+=Qe)u.push(z(e));const l=r?.allowExplicitId===!0?void 0:or(d),f=t.map((_,D)=>{const S=vt(d,_,we),I=l===void 0?S:Ne(l,S,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const W=$??bt(),N=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Re(),V={...I,...u[Math.floor(D/Qe)],_creationTime:N,_id:W};return{creationTime:N,document:V,id:W}});for(const _ of f)ee(_.document);const E=async _=>{for(const{document:D,id:S}of _)dt(e,S,D);for(const{document:D,id:S}of _)await ve({doc:D,id:S,op:"insert",table:e})};let b=0;try{for(let _=0;_<f.length;_+=Qe){const D=f.slice(_,_+Qe),S=h.join(D.map($=>h`(${$.id}, ${$.creationTime}, ${le($.document)})`),h`, `),I=Tn("sqlite",h`INSERT INTO ${h.identifier(e)} (id, _creationTime, ${h.identifier(ie)}) VALUES ${S}`);_t(y,e,I.sql,I.params),b=_+D.length}}catch(_){throw await Kn(e,f.slice(0,b)),_}return await E(f),f.map(_=>_.id)},async insertMany(e,t,r){ze(t.length,r?.limit,"insertMany");const c=r?.skipDuplicates===!0,d=[],u=j(e,"insert");if(u){for(const f of t)ee(f);if(!c)return Lt(u,e,t,void 0)}const l=async f=>u?it(u,e,f,void 0,!1):U.insert(e,f);for(const f of t)try{d.push(await l(f))}catch(E){if(c&&E instanceof fe&&E.kind==="unique")d.push(null);else throw E}return d},normalizeId(e,t){return pn(p,e,t)},async patch(e,t,r,c){T(e,"ctx.db.patch(table, id, values)");const d=X(t,e);if(!d){const $=de(e);if($){ee(r);try{await $.patch(e,t,r,c)}finally{Y("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:u,row:l,tableName:f}=d,E=p.tables[f];if(!E)throw new v("INTERNAL",`unknown table: ${f}`);if(P(f,t),yn("patch",r),Mt(f,t,r,l)){o?.({fields:Object.keys(Ve(r)),id:t,table:f});return}const b=Mo(E,r,l),_={...l,...Ve(b),...z(f),_id:t};yt(E,b,_,we);const D=new Set(Object.keys(b)),S=Ne(E,_,{only:D,patched:D,previous:()=>l,table:f,tolerateStoredNull:!0});Do(c,l,S),oe(f,"before","update")&&await re("before","update",{doc:{...S},id:t,op:"update",previous:l,table:f}),O(f,S,l),Ie(f),be(f),Je(y,f,an(f),[le(S),t,u]),Pe(f,t,S,l),Be(f,t,S),We(f,l,S),pe(f,t,l,S);const I=R(f,l,S);he?.invalidate(f,t,I),Te(f,t,"update",S),x({indexKeys:I,key:t,op:"update",row:S,table:f}),oe(f,"after","update")&&await re("after","update",{doc:S,id:t,op:"update",previous:l,table:f}),await Se({doc:S,id:t,op:"update",table:f})},async patchIf(e,t,r){const c=j(e,"patchIf");if(c){if(c.patchIf===void 0)throw new v("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);ee(r.patch);let d;try{d=await c.patchIf(e,t,r)}catch(u){throw Y("update",e,t),u}return d.applied&&Y("update",e,t),d}if(!p.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);for(let d=1;d<=gn;d+=1){const u=await Xn(e,t,r,d<gn,l=>U.patch(e,t,l,{verify:r.verify}));if(u!==void 0)return u}throw new fe(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),ze(t.length,r?.limit,"patchMany");const c=te(e)?de(e):void 0;if(c?.patchMany!==void 0)return On(c,e,t);for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const c=j(e,"patchWhere")??U,u=(await un(c,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,u,r),{patched:u.length}},async related(e,t){return Jo(U,B,e,t)},relationEdges:B,deleteRereadTables:C,inTransaction:ue,softDeleteFields:F,relationWrites:K,query(e){const t=j(e,"query");return t?(P(e,G),t.query(e)):Bn(y,p,e,ae,r=>{r?se(r):P(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const c=j(e,"rank");if(ae(e,t,"rank"),c)return P(e,G),c.rank(e,t,r);const d=p.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);const u=d.rankIndexes?.find(J=>J.name===t);if(!u)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ut(e,d,u),r.restrictsCounts)throw new ht(e);P(e,G),at(e,u);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const f=en(e,u.name),E=u.sortBy.map((J,ge)=>tn(ge)),b=E.map(J=>Le(J)).join(", "),_=H(y,h`SELECT ${h.identifier("__partition__")}, ${h.raw(b)} FROM ${h.identifier(f)} WHERE ${h.identifier("__id__")} = ${l}`).toArray(),[D]=_;if(D===void 0)return null;let S=D.__partition__;const I=Q(r.baseWhere,r.where);pt(I,p,e,"rank");const $=qo(u,I);if($){const J=Oo(u.partitionBy??[],$);if(J!==S)return null;S=J}const W=E.map(J=>D[J]),{before:N,total:V}=En(y,f,E,u.sortBy,S,W,l);return{position:N+1,total:V}},async rankBefore(e,t,r){if(te(e))throw new v("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=p.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const d=c.rankIndexes?.find(E=>E.name===t);if(!d)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ht(e);P(e,G),at(e,d);const u=en(e,d.name),l=d.sortBy.map((E,b)=>tn(b)),f=d.sortBy.map((E,b)=>ke(r.sortValues[b]??null));return En(y,u,l,d.sortBy,r.partitionKey,f,r.rowId)},async rankPage(e,t,r={}){pt(Q(r.baseWhere,r.where),p,e,"rankPage");const c=j(e,"rankPage");if(ae(e,t,"rank"),c)return P(e,G),c.rankPage(e,t,r);const{continueCursor:d,hasMore:u,rows:l}=Vt(Ht,e,t,r);return{continueCursor:d,isDone:!u,page:l.map(f=>f.doc)}},async rankPageRows(e,t,r={}){pt(Q(r.baseWhere,r.where),p,e,"rankPage"),ae(e,t,"rank");const{directions:c,hasMore:d,rows:u}=Vt(Ht,e,t,r);return{directions:c,hasMore:d,rows:u}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=X(t,e);if(!r){const l=de(e);if(l?.restore){try{await l.restore(e,t)}finally{Y("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const c=p.tables[r.tableName]?.softDeleteMode?.field;if(!c)throw new v("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const d=r.row[c]!==null&&r.row[c]!==void 0;await U.patch(e,t,{[c]:null});const u=d?X(t,e)?.row:void 0;u&&(pe(r.tableName,t,u,void 0),pe(r.tableName,t,void 0,u))},async replace(e,t,r,c){T(e,"ctx.db.replace(table, id, document)");const d=X(t,e);if(!d){const W=de(e);if(W){ee(r);try{await W.replace(e,t,r,c)}finally{Y("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:u,row:l,tableName:f}=d,E=p.tables[f];if(!E)throw new v("INTERNAL",`unknown table: ${f}`);yn("replace",r);const b=c?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof l._creationTime=="number"?l._creationTime:void 0,D=b??_??Re(),S={...r,...z(f),_creationTime:D,_id:t};yt(E,r,S,we);const I=c?.allowExplicitId===!0,$=Ne(E,S,{previous:()=>l,supplied:r,table:f,trusted:I});oe(f,"before","update")&&await re("before","update",{doc:{...$},id:t,op:"update",previous:l,table:f}),I||O(f,$,l),Ie(f),be(f),Je(y,f,Fr(f),[D,le($),t,u]),Pe(f,t,$,l),Be(f,t,$),We(f,l,$),pe(f,t,l,$),he?.invalidate(f,t,R(f,l,$)),Te(f,t,"update",$),x({indexKeys:R(f,l,$),key:t,op:"update",row:$,table:f}),oe(f,"after","update")&&await re("after","update",{doc:$,id:t,op:"update",previous:l,table:f}),await Se({doc:$,id:t,op:"update",table:f})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,c=Object.entries(p.tables).filter(([f,E])=>t.has(f)||r!==void 0&&!r.includes(f)?!1:E.shardMode?.kind!=="global").map(([f])=>f);if(r!==void 0){for(const f of r)if(!p.tables[f])throw new v("INTERNAL",`wipeShard: unknown table: ${f}`)}const d={};let u=0;const{deleteAll:l}=U;if(l===void 0)throw new v("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of c){const E=await l(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});d[f]=E.deleted,u+=E.deleted}return{deleted:u,tables:d}}},Zn={db:U,scheduler:Ct};return n.enforceRls===!0?dr(U,p,(e,t)=>X(e,t)?.tableName,B):U};export{ms as CDC_LOG_TABLE,Gs as IDEMPOTENCY_TABLE,ti as NotUniqueError,Ps as advanceClientWatermark,vs as applyCdcChanges,yn as assertNoExplicitUndefined,Rt as assertStorableRowId,Gr as assertValidClientId,gs as backfillAggregateIndexes,ys as backfillRankIndexes,$s as backfillSearchIndexes,Ss as bumpCdcEpoch,Rs as cdcCanVouchFor,_s as cdcForkedError,Ts as cdcSeqLeavingRows,As as cdcTouchesTables,Is as cdcTrimmedError,bs as compactCdcDocs,_i as createShardCtxDb,Cs as cursorBelowRetainedFloor,pi as meterReadBytes,qs as migrateClientWatermark,xs as minCdcReplayableSeq,Ms as minCdcSeq,pn as normalizeIdStructurally,Ds as readCdcChangeKeys,ks as readCdcChanges,Ls as readCdcCursor,Fs as readCdcEpoch,Os as readClientWatermark,js as readIdempotent,Qs as runShardMigrations,Vs as selectShapeMembers,Js as selectShapeRows,Ve as stripReservedPatchFields,Ws as trimCdcChanges,Hs as trimIdempotent,Ks as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-CPAltXX4.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BcyWWSdU.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-DeOECCjz.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};
|
|
@@ -178,6 +178,8 @@ interface SocketAttachment {
|
|
|
178
178
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
179
179
|
socketFunction?: string;
|
|
180
180
|
socketPath?: string;
|
|
181
|
+
subResults?: Record<string, string>;
|
|
182
|
+
subResultsSalt?: string;
|
|
181
183
|
subs: Record<string, SubscriptionQuery>;
|
|
182
184
|
subTables?: Record<string, string[]>;
|
|
183
185
|
userId?: string;
|
|
@@ -635,6 +637,7 @@ interface DatabaseWriterLike {
|
|
|
635
637
|
}>;
|
|
636
638
|
deleteMany?: (table: string, ids: ReadonlyArray<string>, options?: {
|
|
637
639
|
limit?: number;
|
|
640
|
+
onStored?: (ids: ReadonlyArray<string>) => void;
|
|
638
641
|
}) => Promise<{
|
|
639
642
|
deleted: number;
|
|
640
643
|
}>;
|
|
@@ -684,6 +687,7 @@ interface DatabaseWriterLike {
|
|
|
684
687
|
patch: Record<string, unknown>;
|
|
685
688
|
}>, options?: {
|
|
686
689
|
limit?: number;
|
|
690
|
+
onStored?: (ids: ReadonlyArray<string>) => void;
|
|
687
691
|
}) => Promise<{
|
|
688
692
|
patched: number;
|
|
689
693
|
}>;
|
|
@@ -178,6 +178,8 @@ interface SocketAttachment {
|
|
|
178
178
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
179
179
|
socketFunction?: string;
|
|
180
180
|
socketPath?: string;
|
|
181
|
+
subResults?: Record<string, string>;
|
|
182
|
+
subResultsSalt?: string;
|
|
181
183
|
subs: Record<string, SubscriptionQuery>;
|
|
182
184
|
subTables?: Record<string, string[]>;
|
|
183
185
|
userId?: string;
|
|
@@ -635,6 +637,7 @@ interface DatabaseWriterLike {
|
|
|
635
637
|
}>;
|
|
636
638
|
deleteMany?: (table: string, ids: ReadonlyArray<string>, options?: {
|
|
637
639
|
limit?: number;
|
|
640
|
+
onStored?: (ids: ReadonlyArray<string>) => void;
|
|
638
641
|
}) => Promise<{
|
|
639
642
|
deleted: number;
|
|
640
643
|
}>;
|
|
@@ -684,6 +687,7 @@ interface DatabaseWriterLike {
|
|
|
684
687
|
patch: Record<string, unknown>;
|
|
685
688
|
}>, options?: {
|
|
686
689
|
limit?: number;
|
|
690
|
+
onStored?: (ids: ReadonlyArray<string>) => void;
|
|
687
691
|
}) => Promise<{
|
|
688
692
|
patched: number;
|
|
689
693
|
}>;
|
package/dist/sql.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SQL, Name } from 'drizzle-orm';
|
|
2
|
-
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-
|
|
2
|
+
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-D-Bc5Xkd.mjs";
|
|
3
3
|
import '@lunora/errors';
|
|
4
4
|
declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
|
|
5
5
|
interface WhereFragments<T> {
|
package/dist/sql.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SQL, Name } from 'drizzle-orm';
|
|
2
|
-
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-
|
|
2
|
+
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-D-Bc5Xkd.js";
|
|
3
3
|
import '@lunora/errors';
|
|
4
4
|
declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
|
|
5
5
|
interface WhereFragments<T> {
|
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.217",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{q as At}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as eo,l as Ue,s as to}from"./fts-companion-Cfz-hJum.mjs";import{decodeWire as no,stableWireKey as Nt}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{throwingScheduler as oo,aggregateSqlFunction as Ge,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as lt,encodeAggregateKey as ft,readAggregateValue as ut}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ht,selectIndexForGroupBy as ro,selectIndexForCount as io,selectIndexForAggregate as so}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as co,searchIndexCoversTable as ao}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{backfillAggregateIndexes as ps,backfillRankIndexes as gs,backfillSearchIndexes as ys}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{appendCdcChange as lo,readCdcDocAtOrBefore as fo}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{CDC_LOG_TABLE as Es,applyCdcChanges as ms,bumpCdcEpoch as vs,cdcCanVouchFor as Ss,cdcForkedError as Rs,cdcSeqLeavingRows as _s,cdcTouchesTables as Ts,cdcTrimmedError as As,compactCdcDocs as Is,cursorBelowRetainedFloor as bs,minCdcReplayableSeq as Cs,minCdcSeq as xs,readCdcChangeKeys as Ms,readCdcChanges as Ds,readCdcCursor as ks,readCdcEpoch as Ls,trimCdcChanges as Fs}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{allocateCommitSeq as uo,COMMIT_SEQ_FIELD as ho}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{createCompanionSync as wo}from"./createCompanionSync-D5cqtwqR.mjs";import{isMemoryTable as zt}from"./clearMemoryTables-CIfrwTj8.mjs";import{computeRankPage as Vt}from"./computeRankPage-De_JKnna.mjs";import{SCAN_DEP as G,PRIMARY_READ as po}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as H}from"./runDrizzle-DAtZbzBn.mjs";import{b as go,j as Et,D as oe,r as Me,W as yo,e as de,h as $o,t as Eo,u as mo,i as vo,q as Jt,a as _n,g as So}from"./do-sql-DT8JBpG8.mjs";import{AGG_VALUE as je,AGG_COUNT as wt,AGG_KEY as He,doWhereSqlStrategy as ge,jsonPathSql as ye}from"./AGG_COUNT-DzvM-UU5.mjs";import{renderSql as Tn,unionAll as An}from"./param-Y0zw_1Cv.mjs";import{a as Ro,u as _o}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as To,boundingBoxGeohashes as Ao,haversineMeters as Io,pointInBoundingBox as bo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Co}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as xo,assertPatchAllowed as Mo,operatorFields as Do,readPatchField as Yt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as ko,encodeCursor as mt,nullsOrderSuffix as Lo,normalizeOrderKeys as Xt,uniqueIndexFields as Fo,buildSeekWhere as Wo,decodeCursor as Zt,buildSeekBeforeWhere as Bo,softDeleteScope as Ce,applySelect as In}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as en,sortColumnName as tn,resolveRankPartition as qo,encodePartitionKey as Po,RANK_TIEBREAK as Oo}from"./RANK_TIEBREAK-BknRdgt8.mjs";import Uo from"./rankPivotConditionSql-CUX4Vuhv.mjs";import{UNVOUCHABLE_DEP as nn}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Go,withUnknownIndexKeys as jo,indexKeysForRow as Ho,buildIndexRange as Ko}from"./buildIndexRange-BTChxh3k.mjs";import $e from"./runSql-BBRXi81G.mjs";import{r as Je,j as De,c as Z,t as Ze,i as on}from"./where-sql-AVR5KloI.mjs";import{serializeSqlValue as ke}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Le}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as No,isPushableWhere as Qo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as zo,findRelated as Vo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as pt,findManyPage as Jo,relationPredicateTables as Yo,resolveRelationPredicates as Xo,composeReadPredicate as Zo}from"./DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs";import{bindRelationWrites as er,describeSchemaRelationWrites as tr}from"./describeRelationWrites-BKd7YU5R.mjs";import{runRowValidators as Ke,transformOnlyDefinition as nr,applyInsertDefaults as vt,resolveWith as or,relationHooks as rr,applyOnDelete as ir,fanOutScalarCounts as sr,CASCADE_MAX_ROWS as cr}from"./applyInsertDefaults-Bt6LYmPD.mjs";import{guardWriter as ar}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{WORKERD_SQLITE_LIMITS as bn}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{mayHoldProjectedValue as dr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as lr}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as le}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as rn,runTriggers as fr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Bs,migrateClientWatermark as qs,readClientWatermark as Ps}from"./CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{IDEMPOTENCY_TABLE as Us,readIdempotent as Gs,trimIdempotent as js,writeIdempotent as Hs}from"./IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{runShardMigrations as Ns}from"./runShardMigrations-DeOECCjz.mjs";import{selectShapeMembers as zs,selectShapeRows as Vs}from"./selectShapeMembers-BP30uxpp.mjs";const ur=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},hr=()=>new v("INVALID_CURSOR","invalid cursor"),sn=16,cn=8,X=1024,It=(n,i)=>i.query(n),wr=(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 E of n)(h?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},pr=(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)}},gr=(n,i,o)=>{const s={eq:(c,h)=>{if(!n.definition.filterFields?.includes(c))throw new v("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=cn)throw new v("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(cn)} .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 v("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const E=It(h,o).length;if(E>sn)throw new v("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(sn)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=h,g.hasQuery=!0,s}};return s},yr=n=>{if(n.length>X)throw new v("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},$r=n=>Math.min(n.offset+n.numItems+1,X),Er=n=>btoa(`search:${String(n)}`),mr=n=>{let i;try{i=ur(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},vr=n=>{if(typeof n.endCursor=="string")throw new v("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 v("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?mr(n.cursor):0;if(o===void 0)throw hr();if(o+i>=X)throw new v("BAD_REQUEST",`search pagination reaches the ${String(X)}-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,X-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Sr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?Er(o):null,isDone:!s,page:n.slice(i.offset,o)}},Rr=n=>{if(n===void 0)return X+1;if(!Number.isFinite(n))return X;const i=Math.max(0,Math.floor(n));if(i>X)throw new v("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Cn=500,xn=(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??Cn},Mn=(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)`)},_r=32,Tr=1024,Dn=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${Le(oe)} FROM ${Le(n)}`,h=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${c} ${h}`):De(`${c} WHERE `,i,` ${h}`)},et={fieldRef:n=>Je(Et(n)),rangeTypeGuard:(n,i)=>Je(go(n,i)),serialize:ke},Ar=n=>n===void 0?"":Lo(n==="first"),kn=n=>{const i=n.map(o=>`${Et(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${Et("id")} ${ko(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Ir={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ln=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),br=n=>{const i=Ln(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Cr=(n,i)=>{const o=n.order,s=br(n),{shape:c}=i;return s.length>0?Xt(s.map(h=>({[h]:o})),c,{pinned:Ln(n),uniqueBy:Fo(i.indexes,c)}):Xt([{_creationTime:o}],c)},xr=(n,i,o,s)=>{const c=n.sqlConditions.map(h=>({[h.field]:{[Ir[h.comparator]??"eq"]:h.value}}));if(o&&c.push(Wo(i,Zt(o))),s&&c.push(Bo(i,Zt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},Mr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_r):n.want},St=(n,i,o,s,c,h,g)=>{const E=Cr(s,o),y=kn(E),w=[],{filters:x,want:T}=h;let A=h.cursor??void 0,C=Mr(h);if(T===0)return{documents:w,orderKeys:E};for(;;){const B=Z(xr(s,E,A,h.endCursor),et,Ze),P=Dn(i,c&&B?De(B," AND ",c):c??B,y,C),F=$e(n,P.text,...P.params).toArray();let O={};g(F.length);for(const K of F)if(O=Me(K),x.every(fe=>fe(O))&&w.push(O)===T)return{documents:w,orderKeys:E};if(C===void 0||F.length<C)return{documents:w,orderKeys:E};A=mt(O,E),C=Math.max(C,Math.min(C*2,Tr))}},Dr=(n,i,o,s,c,h,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=St(n,i,o,s,h,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),F=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:F?mt(F,P):null}}const{documents:w,orderKeys:x}=St(n,i,o,s,h,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),T=w.length>y,A=T?w.slice(0,y):w,C=A.at(-1);return{continueCursor:T&&C?mt(C,x):null,isDone:!T,page:A}},tt=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(Le(o));return i.set(o,c),c}},Ee=Le(oe),kr=tt(n=>`INSERT INTO ${n} (id, _creationTime, ${Ee}) VALUES (?, ?, ?)`),an=tt(n=>`UPDATE ${n} SET ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),Lr=tt(n=>`UPDATE ${n} SET _creationTime = ?, ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),Fr=tt(n=>`DELETE FROM ${n} WHERE id = ? AND ${Ee} = ?`),Wr="SELECT changes() AS changed",dn=new Map,Br="",qr=n=>{const i=JSON.stringify(n),o=dn.get(i);if(o!==void 0)return o;const s=n.map(h=>u`SELECT ${u.raw(`'${h.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(h)} WHERE id = ${Br}`),{sql:c}=Tn("sqlite",u`${An(s)} LIMIT 1`);return dn.set(i,c),c},Pr=(n,i)=>i.map(()=>n),Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ur=n=>{if(!Or.test(n))throw new v("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new v("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Gr=(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?vt(n,h,s)._id:h._id;typeof g=="string"&&Rt(g)}},ln=50,Ne=Math.floor(bn.boundParams/3),fn=bn.boundParams,jr=128,Ye=n=>new v("BATCH_LIMIT_EXCEEDED",n,{status:400}),Qe=(n,i,o)=>{Mn(n,xn(i,o,Ye),o,Ye)},un=async(n,i,o,s,c)=>{const h=xn(s,c,Ye),{page:g}=await n.findMany(i,Number.isFinite(h)?{limit:h+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>h&&Mn(Math.max(await n.count(i,{where:o}),g.length),h,c,Ye),g},Hr=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},Kr=n=>Math.max(n,X),Fn=(n,i)=>{const o=n.filters.map(s=>u`${ye(s.field)} = ${ke(s.value)}`);return i&&o.push(i),o},Nr=(n,i,o,s,c)=>{const h=It(o.query,At(o.definition.language));if(h.length===0)return[];const g=eo(i,o.indexName),E=`${g}__vocab`,y=h.length-1,w=h.map((P,F)=>{const O=pr(P,F===y),K=O.exact?u`${u.identifier("term")} = ${O.lower}`:u`${u.identifier("term")} >= ${O.lower} AND ${u.identifier("term")} < ${O.upper}`;return u`SELECT ${u.identifier("doc")}, ${u.raw(String(F))} AS ${u.identifier("__term__")}, COUNT(*) AS ${u.identifier("__n__")} FROM ${u.identifier(E)} WHERE ${K} GROUP BY ${u.identifier("doc")}`}),x=h.map((P,F)=>u`SUM(CASE WHEN u.${u.identifier("__term__")} = ${u.raw(String(F))} THEN u.${u.identifier("__n__")} ELSE 0 END)`),T=u`SELECT f.${u.identifier(Ue)} AS ${u.identifier(Ue)}, ${u.join(x,u` + `)} AS ${u.identifier("__score__")} FROM (${An(w)}) u JOIN ${u.identifier(g)} f ON f.rowid = u.${u.identifier("doc")} GROUP BY f.${u.identifier(Ue)} HAVING ${u.join(x.map(P=>u`${P} > 0`),u` AND `)}`,A=Fn(o,c);let C=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)}, s.${u.identifier("__score__")} AS ${u.identifier("__score__")} FROM (${T}) s JOIN ${u.identifier(i)} m ON m.id = s.${u.identifier(Ue)}`;A.length>0&&(C=u`${C} WHERE ${u.join(A,u` AND `)}`),C=u`${C} ORDER BY s.${u.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${u.raw(String(s))}`;const B=[];for(const P of H(n,C)){const F=_n(P);if(F){const O=P.__score__;B.push({document:F,score:typeof O=="number"?O:Number(O??0)})}}return B},Qr=(n,i,o,s,c)=>{const h=At(o.definition.language),g=It(o.query,h);if(g.length===0)return[];const E=Fn(o,c);let y=u`SELECT id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(i)}`;E.length>0&&(y=u`${y} WHERE ${u.join(E,u` AND `)}`),y=u`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${u.raw(String(Kr(s)))}`;const w=H(n,y).toArray(),x=[];for(const T of w){const A=_n(T);if(!A)continue;const C=wr(to(A,o.definition),g);C>0&&x.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:C})}return x.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),x.slice(0,s).map(T=>({document:T.doc,score:T.score}))},gt=(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 v("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},zr=(n,i)=>{const o=n,s={near:(c,h)=>{if(o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(c,".near() point",i,o.indexName),!Number.isFinite(h)||h<=0)throw new v("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 v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(c.sw,".within() sw corner",i,o.indexName),gt(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new v("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 v("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},Vr=(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},Jr=(n,i)=>{const o=Vr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=Io(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return bo(o,i.within)?{creationTime:s,distance:0}:void 0},Yr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?To(o.near.point,o.near.radiusMeters):Ao(o.within),h=So(i,o.indexName),g=c.map(T=>u`(g.${u.identifier("__geohash__")} >= ${T} AND g.${u.identifier("__geohash__")} < ${`${T}{`})`),E=[u`(${u.join(g,u` OR `)})`];s&&E.push(s);const y=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)} FROM ${u.identifier(h)} g JOIN ${u.identifier(i)} m ON m.id = g.${u.identifier("__id__")} WHERE ${u.join(E,u` AND `)}`,w=H(n,y).toArray(),x=[];for(const T of w){const A=Me(T),C=A?Jr(A,o):void 0;A&&C&&x.push({creationTime:C.creationTime,distance:C.distance,doc:A})}return x.sort((T,A)=>T.distance-A.distance||A.creationTime-T.creationTime),x},Wn=(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},Xr=(n,i,o,s,c,h=()=>{})=>{const g=o.within!==void 0,E=Yr(n,i,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return h(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},hn=(n,i,o,s,c,h,g=()=>{})=>{const{geo:E}=o;if(!E)throw new v("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,w=Xr(n,i,E,y?void 0:h,s,g);return y?Wn(w,c,h,x=>x.document):w},wn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&dr(s))throw new v("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)`)},Zr=n=>{let i=0;const o=[],s={...et,relationExists:c=>{const{childWhere:h,negated:g,parentTable:E,relation:y}=c,w=`__rel_${String(i)}`,x=o.at(-1)??E;i+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,C=Je(`${Jt(w,A)} = ${Jt(x,T)}`);o.push(w);const B=Z(h,s,Ze);o.pop();const P=B===void 0?C:De(C," AND ",B),F=De("EXISTS (SELECT 1 FROM ",on(y.table)," AS ",on(w)," WHERE ",P,")");return g?De("NOT ",F):F}};return s};class ei extends v{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ti=/\s/u,ni=String.fromCodePoint(0),pn=(n,i,o)=>{if(!n.tables[i])throw new v("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ti.test(o)||o.includes(ni)?null:o},Bn=(n,i,o,s=()=>{},c=()=>{},h=()=>{},g)=>{const E=i.tables[o];if(!E)throw new v("INTERNAL",`unknown table: ${o}`);const y=Ce(E.softDeleteMode,void 0),w=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},x=()=>{const R=Q(y,w.pushedWhere);return R?Z(R,ge):void 0},T=()=>{const R=Q(y,w.pushedWhere);return R?Z(R,et,Ze):void 0},A=()=>[...w.inMemoryFilters,...w.verifyFilters];let C=0;const B=R=>{const{search:M}=w;if(!M)throw new v("INTERNAL","runSearchFetch called without a staged search");co(mo(n),o,E);const k=w.inMemoryFilters.length>0,L=Rr(k?void 0:R),re=vo(n);if(re&&!ao(n,o,M.definition))throw new v("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 q=x(),ce=re?Nr(n,o,M,L,q):Qr(n,o,M,L,q);!k&&R===void 0&&yr(ce);const ae=A();return C=ce.length,ae.length>0?Wn(ce,ae,R,me=>me.document):ce},P=R=>B(R).map(M=>M.document),F=R=>{const M=vr(R);return Sr(P($r(M)),M)},O=()=>{if(w.search||w.geo||w.indexName===void 0){c(void 0);return}c(Ko(o,w.indexName,w.indexFields,w.sqlConditions,ke))},K=R=>{O();let M=0;const k=(()=>{if(w.search){const L=P(R);return M=C,L}return w.geo?hn(n,o,w,x(),A(),R,L=>{M=L}).map(L=>L.document):St(n,o,E,w,T(),{filters:A(),selective:w.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},L=>{M+=L}).documents})();return h(Math.max(M,k.length)),k},fe=()=>{if(!w.search&&!w.geo)throw new v("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let R=0;const M=(()=>{if(w.search){const k=B(void 0);return R=C,k}return hn(n,o,w,x(),A(),void 0,k=>{R=k})})();return h(Math.max(R,M.length)),M},z={async*[Symbol.asyncIterator](){const R=Bn(n,i,o,s,c,h,{...w,indexFields:[...w.indexFields],inMemoryFilters:[...w.inMemoryFilters],sqlConditions:[...w.sqlConditions],verifyFilters:[...w.verifyFilters]});if(w.search){yield*await R.collect();return}let M;for(;;){const k=await R.paginate({cursor:M??null,numItems:jr});if(yield*k.page,k.isDone||k.continueCursor===null)return;M=k.continueCursor}},async collect(){return K(void 0)},async collectWithScores(){return fe()},filter(R){const M=No(R);return M!==void 0&&Qo(M,E.shape)?(w.pushedWhere=Q(w.pushedWhere,M),w.verifyFilters.push(R)):w.inMemoryFilters.push(R),z},async first(){return K(1)[0]??null},order(R){return w.order=R==="desc"?"desc":"asc",z},async paginate(R){let M=0;if(O(),w.search){const L=F(R);return h(L.page.length),L}if(w.geo)throw new v("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Dr(n,o,E,w,R,T(),{all:A(),selective:w.inMemoryFilters.length>0},L=>{M+=L});return h(Math.max(M,k.page.length)),k},async take(R){return K(R)},async unique(){const R=K(2);if(R.length>1)throw new ei(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,M){const k=(E.geoIndexes??[]).find(re=>re.name===R);if(!k)throw new v("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const L={definition:k,indexName:R};if(w.geo=L,M(zr(L,o)),!L.near&&!L.within)throw new v("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(R,M){const k=E.indexes.find(L=>L.name===R);if(!k)throw new v("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),w.indexName=R,w.indexFields=k.fields,M&&M(Hr(w)),z},withSearchIndex(R,M){const k=(E.searchIndexes??[]).find(re=>re.name===R);if(!k)throw new v("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const L={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:R,query:""};if(w.search=L,M(gr(L,o,At(k.language))),!L.hasQuery)throw new v("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return z}};return z},yt=(n,i,o,s)=>{const c=o;for(const[h,g]of Eo(n)){if(g.serverDefault){h in i&&(c[h]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(h in i)&&(c[h]=g.onUpdateFn())}},gn=5,yn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new v("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},$n=["_commitSeq","_creationTime","_id"],ze=n=>$n.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!$n.includes(i))):n,oi=/unique constraint failed/i,ri=n=>n instanceof Error&&oi.test(n.message),ii=/string or blob too big/iu,si=(n,i)=>{if(!(!(n instanceof Error)||!ii.test(n.message)))throw new v("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.`)},_t=(n,i,o,s)=>{try{$e(n,o,...s)}catch(c){throw ri(c)?new le(`unique constraint violation on "${i}"`,"unique"):(si(c,i),c)}},Ve=(n,i,o,s)=>{if(_t(n,i,o,s),$e(n,Wr).one().changed===0)throw new le(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},En=(n,i,o,s,c,h,g)=>{const E=[];for(let T=0;T<o.length+1;T+=1){const A=o[T],C=s[T],B=C?.direction==="desc"?"desc":"asc",P=A===void 0||C===void 0?u`${u.identifier(Oo)} < ${g}`:Uo(A,h[T],B,!1);if(P===void 0)continue;const F=[];for(let K=0;K<T;K+=1)F.push(u`${u.identifier(o[K])} IS ${h[K]}`);F.push(P);const[O]=F;E.push(F.length===1&&O!==void 0?O:u`(${u.join(F,u` AND `)})`)}const y=E.length>0?u.join(E,u` OR `):u`1 = 0`,w=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c} AND (${y})`).one(),x=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c}`).one();return{before:w.c,total:x.c}},ci=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:E,op:y}of i.get(g)??[]){if(E===s||rn(n,E,y))return!0;c.has(E)||(c.add(E),h.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||rn(n,s,"delete")||o(s)).map(([s])=>s))},ai=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},mn=new WeakMap,di=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const c of n)o.call(s,c,c,i)},has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.values()});return i},li=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const[c,h]of n)o.call(s,h,c,i)},get:o=>n.get(o),has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.entries()});return i},fi=n=>{const i=mn.get(n);if(i!==void 0)return i;const o=Object.freeze(zo(n).map(g=>Object.freeze(g))),s=new Map,c=g=>(n.tables[g]?.shardMode?.kind??"root")==="root";for(const g of o)!g.array&&c(g.sourceTable)&&c(g.targetTable)&&s.set(g.sourceTable,[...s.get(g.sourceTable)??[],g]);for(const g of s.values())Object.freeze(g);const h={checkedForeignKeys:s,deleteRereadTables:di(ci(n)),relationEdges:o,relationWrites:tr(n),softDeleteFields:li(ai(n))};return mn.set(n,h),h},$t=new WeakMap,ui=(n,i)=>{let o=$t.get(i.tables);if(!$t.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"),$t.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},hi=(n,i,o)=>{for(const s of n){const c=s,h=c?.[oe];if(typeof h=="string"){const g=c?.id,E=_o(h);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},wi=(n,i,o)=>{if(i===void 0)return n;const s=(c,...h)=>{const g=n.exec(c,...h),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),w=o===void 0?void 0:ui(c,o);let x=!1;const T=A=>{hi(A,i,w)};return g.toArray=()=>{const A=[];for(const C of{[Symbol.iterator]:y})T([C]),A.push(C);return A},g.one=()=>{x=!0;try{const A=E();return T([A]),A}finally{x=!1}},g[Symbol.iterator]=function*(){for(const C of{[Symbol.iterator]:y})x||T([C]),yield C},g};return new Proxy(n,{get:(c,h)=>h==="exec"?s:h===yo?c:Reflect.get(c,h,c)})},pi=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),gi=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Ro(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},Xe=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{xe(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const h of c.page??[])xe(h,o,s);return}case"rows":{for(const h of Array.isArray(n)?n:[n])xe(h,o,s);return}default:for(const h of Array.isArray(n)?n:[])xe(h.document,o,s)}},qn=(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 y of Reflect.apply(h,s,[]))xe(y,i,o),yield y};const g=gi.get(c);return(...E)=>{const y=Reflect.apply(h,s,E);return g!==void 0?Promise.resolve(y).then(w=>(Xe(w,g,i,o),w)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?qn(y,i,o):y}}}),yi=new Set(["findFirst","findFirstOrThrow","findMany"]),$i=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=>In(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:h(g.page)}:h([g])[0]}},vn=256,Tt=4096,Ei=1024*1024,mi=async(n,i,o,s)=>{const c=i[1]??{},h=[];let{cursor:g}=c,E=vn,y=0;for(;;){const w=await n([i[0],{...c,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(w))return Xe(w,"rows",o,s),[...h,...w];const x=s.headroom().readBytes;if(Xe(w,"page",o,s),h.push(...w.page),w.isDone||typeof w.continueCursor!="string")return{continueCursor:null,isDone:!0,page:h};g=w.continueCursor,y+=s.headroom().readBytes-x,E=y>0?Math.min(Tt,Math.max(vn,Math.floor(Ei*h.length/y))):Tt}},vi=(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)=>qn(Reflect.apply(c,o,g),String(g[0]),i);const h=pi.get(s);return h===void 0?c:async(...g)=>{const E=yi.has(s)?$i(g):void 0;let y=E?.args??g;const w=String(g[0]),x=y[1],T=s==="findMany"&&typeof x?.endCursor=="string",A=s==="findMany"&&typeof x?.limit!="number"&&!T;if(T&&typeof x.limit!="number"&&(y=[y[0],{...x,limit:Tt},...y.slice(2)]),A){const B=await mi(P=>Reflect.apply(c,o,P),y,w,i);return E===void 0?B:E.project(B,h)}const C=await Reflect.apply(c,o,y);return Xe(C,h,w,i),E===void 0?C:E.project(C,h)}}}),Sn=new WeakMap,Rn=new WeakMap,Si=500,Ri=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=Sn.get(n)??{value:void 0},h=Rn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};Sn.set(e,c),Rn.set(e,h),g=Ri(e)}return g},y=wi(n.sql,s,n.schema),{schema:w}=n,x=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(w.tables,e))throw new v("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},{checkedForeignKeys:A,deleteRereadTables:C,relationEdges:B,relationWrites:P,softDeleteFields:F}=fi(w),O=(e,t,r)=>{for(const a of A.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(H(y,u`SELECT 1 FROM ${u.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new v("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},K=er(P,n.inTransaction),fe=()=>n.inTransaction?.()===!0,z=e=>w.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!fe())&&(c.value=uo(y)),{[ho]:c.value}),R=(e,...t)=>{const r=w.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Go(l))),a.push(...jo(r,Ho(r,p,ke))));return a.length>0?a:void 0},M=n.onRead??(()=>{}),k=e=>{zt(w.tables[e])&&M(nn,nn)},L=n.onReadRange??(e=>{M(e.table,G)}),re=e=>{k(e.table),L(e)},q=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),k(e),M(e,t,r)},ce=(e,t)=>{const r=e.row._id;q(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ae=n.onIndexUse??(()=>{}),me=n.onWrite??(()=>{}),ee=e=>{s?.recordWrite(e)},ve=async e=>{ee(e.doc),await me(e)},{cache:ue}=n,Se=n.clock??(()=>Date.now()),bt=n.idGenerator??(()=>crypto.randomUUID()),Ct=n.scheduler??oo,Re=vi(n.globalDb,s),he=n.auth??{identity:null,userId:null},xt=n.cdc??!1,nt=Ct,Pn=lr({scheduler:typeof nt.list=="function"&&typeof nt.get=="function"?nt:void 0,storage:n.storage}),_e=(e,t,r,a)=>{xt&&!zt(w.tables[e])&&lo(y,Se(),e,t,r,a)},Mt=(e,t,r,a)=>{const l=w.tables[e];if(l?.dropStalePatchesMode!==!0||!xt)return!1;const p=i?.();if(p===void 0)return!1;const d=fo(y,e,t,p);if(d===void 0)return!1;const f=Do(l,r);return Object.keys(ze(r)).some(m=>!f.has(m)&&Nt(Yt(d,m))!==Nt(Yt(a,m)))},ie=e=>w.tables[e]?.shardMode?.kind==="global",Dt=(e,t)=>{if(ie(e)){if(!Re)throw new v("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}return U},ot=e=>Dt(e,"cascade"),j=(e,t)=>{if(ie(e)){if(!Re)throw new v("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}},Te=(e,t)=>{q(e,G);for(const r of Yo(Q(t.baseWhere,t.where),w,e,t.relationBaseWhere))q(r,G)},se=(e,t,r)=>{ue?.invalidateTable(t),x({key:r,op:e,table:t})},kt=(e,t,r)=>{x({key:r,op:"insert",row:{...t,_id:r},table:e})},rt=async(e,t,r,a,l)=>{l&&ee(r);const p=await e.insert(t,r,a);return kt(t,r,p),p},Lt=async(e,t,r,a)=>{if(e.insertMany===void 0){const p=[];for(const d of r)p.push(await rt(e,t,d,{allowExplicitId:a},!1));return p}const l=await e.insertMany(t,r,{allowExplicitId:a,limit:Number.POSITIVE_INFINITY,onStored:(p,d)=>{for(const[f,m]of p.entries()){const b=r[d+f];if(b===void 0)throw new v("INTERNAL",`insertMany on global table '${t}' reported row ${String(d+f)} of ${String(r.length)}`);kt(t,b,m)}}});return r.map((p,d)=>{const f=l[d];if(typeof f!="string")throw new v("INTERNAL",`insertMany on global table '${t}' returned no id for row ${String(d)}`);return f})},On=(e,t)=>Dt(e,"relation load").findMany(e,t),Un=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ft=e=>{for(const t of e===void 0?[]:Un(e))ie(t)&&q(t,G)},Wt=(e,t)=>{const r=w.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Ft(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(Ft(p),typeof l=="object"&&Wt(p.table,l.with))}},it=(e,t)=>(ie(e)&&(q(e,G),Wt(e,t.with)),On(e,t)),Gn=e=>!ie(e.table),Bt=n.relationExistsPushDown??"auto",qt=Bt!=="never",{maxRelationKeys:Pt}=n,Fe=(e,t,r)=>Xo(e,{fetcher:it,maxRelationKeys:Pt,relationBaseWhere:r,schema:w,tableName:t}),jn=async(e,t,r,a,l)=>{const p=j(e,"relation grouped count");if(p)return Te(e,{relationBaseWhere:l,where:a}),sr((W,N)=>p.count(W,{relationBaseWhere:l,where:N}),e,t,r,a);const d=w.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);q(e,G);const f=Ce(d.softDeleteMode,void 0),m={[t]:{in:r}},b=Q(Q(m,a),f),_=await Fe(b,e,l),D=Z(_,ge),S=ye(t);let I=u`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${u.identifier(e)}`;D&&(I=u`${I} WHERE ${D}`),I=u`${I} GROUP BY ${S}`;const $=H(y,I).toArray();return new Map($.map(W=>[W.__fk__,W.count]))},Ot=new Set;for(const[e,t]of Object.entries(w.tables))for(const r of Object.values(t.triggerMap??{}))Ot.add(`${e} ${r.timing} ${r.op}`);const te=(e,t,r)=>Ot.has(`${e} ${t} ${r}`),ne=async(e,t,r)=>{if(h.value+=1,h.value>ln)throw h.value-=1,new le(`trigger recursion exceeded ${String(ln)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await fr({ctx:Xn,event:r,op:t,schema:w,tableName:r.table,timing:e})}finally{h.value-=1}},{ensureBackfilledForTable:Ae,ensureBackfilledIndex:st,ensureRankBackfilled:ct,ensureRankBackfilledForTable:Ie,syncAggregates:We,syncCompanionsForInsert:at,syncGeo:Be,syncRanks:we,syncSearch:qe}=wo({broadcast:x,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,R(e,r)),recordCdc:_e,schema:w,sql:y,verified:n.companionMemo?.verified}),Hn=async(e,t)=>{const r=t.filter(({document:a,id:l})=>{try{return at(e,l,a),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:a,id:l}of r)if(Y(l,e)?.docJson===de(a))try{await me({doc:a,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},Ut=(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})},Gt=e=>Object.entries(w.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),be=e=>e===void 0||ie(e)?Re:void 0,Kn=e=>Object.entries(w.tables).flatMap(([t,r])=>ie(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}]):[]),Nn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],Qn=async(e,t,r,a,l)=>{const p=[];let d;do{const f=await e.findMany(t,{cursor:d,includeDeleted:l,limit:Si,where:{[r]:a}});for(const m of f.page)p.push(String(m._id));d=f.isDone?void 0:f.continueCursor??void 0}while(d!==void 0&&p.length<=cr);return p},zn=async(e,t,r,a,l,p)=>{const{action:d,field:f,holderTable:m,references:b}=r,_=await Nn(e,t,b,a);if(_==null)return{effects:[],toExpand:[]};const D=await Qn(e,m,f,_,p),S=D.filter($=>!l.announced.has(`${d}:${m}:${$}`)),I=d==="delete"?D.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of S)l.announced.add(`${d}:${m}:${$}`);for(const $ of I)l.expanded.add(`${m}:${$}`);return{effects:S.map($=>({id:$,op:d,table:m})),toExpand:I}},jt=async(e,t,r,a,l)=>{const p=[];for(const d of Kn(t))for(const f of r){const m=await zn(e,t,d,f,a,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await jt(e,d.holderTable,m.toExpand,a,l))}return p},dt=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)ee(void 0);const p=a?.skipOnDelete===!0?[]:await jt(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)se("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{se("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)se(d.op,d.table,d.id)}},Y=(e,t)=>{const r=Gt(t);for(let a=0;a<r.length;a+=fn){const l=r.slice(a,a+fn),[p]=$e(y,qr(l),...Pr(e,l)).toArray();if(!p)continue;const d=p.__t__,f=Me(p);if(typeof d!="string"||!f)return;const m=p[oe];return{docJson:typeof m=="string"?m:de(m??{}),row:f,tableName:d}}},Ht={assertRankPartitionLocal:Ut,ensureRankBackfilled:ct,onRead:q,rowToDocument:Me,schema:w,sql:y},Vn=(e,t,r)=>{const a=Z(r,ge);return a===void 0||H(y,u`SELECT 1 FROM ${u.identifier(e)} WHERE ${u.identifier("id")} = ${t} AND ${a}`).toArray().length>0},Jn=(e,t,r,a)=>Mt(e,t,r,a)?(o?.({fields:Object.keys(ze(r)),id:t,table:e}),!0):!1,Yn=async(e,t,r,a,l)=>{const p=Y(t,e);if(!p)return{applied:!1,doc:null};if(q(e,t),!Vn(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 le&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:Y(t,e)?.row??null}},Kt=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:f}=await Zo(t,r,{canPushExists:qt?Gn:void 0,existsPushMode:Bt==="always"?"always":"auto",fetcher:it,maxRelationKeys:Pt,schema:w,tableName:e}),m=qt?Zr(a):et,b=Z(f,m,Ze),_=Dn(e,b,kn(d),l);return{limit:p,orderKeys:d,statement:_}},U={system:Pn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return Te(e,t),r.aggregate(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);if(Ge(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 v("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);q(e,G);const l=Ce(a.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await Fe(p,e,t.relationBaseWhere),f=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!f){const $=so(a.aggregateIndexes,t.op,t.field,t.where);if($){st(e,$.index);const W=ft($.index.by??[],$.key),N=lt(e,$.index.name),V=H(y,u`SELECT ${je} AS value, ${wt} AS count FROM ${u.identifier(N)} WHERE ${He} = ${W}`).toArray()[0];return ut(t.op,V)}}wn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(d,ge),b=Ge(t.op),_=ye(t.field);let D=u`SELECT ${u.raw(b)}(${_}) AS value FROM ${u.identifier(e)}`;m&&(D=u`${D} WHERE ${m}`);const I=H(y,D).toArray()[0]?.value;return I??null},asId(e,t){const r=pn(w,e,t);if(r===null)throw new v("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return Te(e,Qt(t)),r.count(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=Qt(t);if(l.restrictsCounts)throw new ht(e);q(e,G);const p=Ce(a.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),f=await Fe(d,e,l.relationBaseWhere),m=f!==d;if(a.aggregateIndexes&&!l.baseWhere&&!m){const S=io(a.aggregateIndexes,l.where);if(S){st(e,S.index);const I=ft(S.index.by??[],S.key),$=lt(e,S.index.name),W=H(y,u`SELECT ${je} AS value FROM ${u.identifier($)} WHERE ${He} = ${I}`).toArray();return W[0]===void 0?0:W[0].value??0}}const b=Z(f,ge);let _=u`SELECT COUNT(*) AS count FROM ${u.identifier(e)}`;return b&&(_=u`${_} WHERE ${b}`),H(y,_).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const a=Y(t,e);if(!a){const S=be(e);S&&await dt(S,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,f=w.tables[d],m=r?.hard===!0,b=!m&&f?.softDeleteMode?f:void 0,_=b?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(te(d,"before","delete")&&await ne("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await ir({deletedId:t,deletedReference:S=>p[S],findHolders:async(S,I,$,W)=>(await ot(S).findMany(S,{...W,includeDeleted:m,where:{[I]:$}})).page,onCascade:(S,I)=>ot(S).delete(S,I,r),onRestrict:S=>{throw new le(S,"restrict")},onSetNull:(S,I,$)=>ot(S).patch(S,I,{[$]:null}),schema:w,tableName:d}),Ae(d),Ie(d),b&&_){const S={[_]:Se()},I={...p,...z(d),...S,_id:t};yt(b,S,I,he),Ve(y,d,an(d),[de(I),t,l]),qe(d,t,I,p),Be(d,t,void 0),We(d,p,I),we(d,t,p,void 0);const $=R(d,p,I);ue?.invalidate(d,t,$),_e(d,t,"update",I),x({indexKeys:$,key:t,op:"update",row:I,table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d});return}Ve(y,d,Fr(d),[t,l]),qe(d,t,void 0),Be(d,t,void 0),We(d,p,void 0),we(d,t,p,void 0);const D=R(d,p);ue?.invalidate(d,t,D),_e(d,t,"delete"),x({indexKeys:D,key:t,op:"delete",table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!w.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Cn),a=t?.hard===void 0?void 0:{hard:t.hard},l=j(e,"deleteAll");let p=0;for(;;){const f=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(f.length===0)break;for(const m of f)await(l===void 0?U.delete(e,m,a):dt(l,e,[m],a)),p+=1;if(f.length<r)break}return{deleted:p}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),Qe(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=j(e,"deleteWhere"),p=(await un(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return dt(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new v("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 Co(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return Te(e,t),t.consistency==="primary"&&M(e,po),r.findMany(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?q(e,G):q(e);const{limit:p,orderKeys:d,statement:f}=await Kt(e,a,t,q),m=$e(y,f.text,...f.params).toArray();l&&s?.recordRead(m.length);const b=[];for(const D of m){const S=Me(D);S&&(b.push(S),!l&&typeof S._id=="string"&&q(e,S._id))}const _=Jo(b,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await or({fetcher:it,groupedCounter:jn,parents:_.page,...rr(t),schema:w,tableName:e,with:t.with}),{..._,page:In(_.page,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Kt(e,a,t,()=>{}),p=$e(y,`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=Y(t,e);if(!r){const a=be(e);return a?(M(e,t,!0),a.get(e,t)):(k(e),M(e,t,!0),null)}return ce(r,t),r.row},async lookupById(e,t){const r=Y(e,t);if(!r){for(const a of Gt(t))k(a),M(a,e,!0);return null}return ce(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=j(e,"groupBy");if(r)return Te(e,t),r.groupBy(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);q(e,G);const l=t.agg??{op:"count"};if(Ge(l.op),l.op!=="count"&&!l.field)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=Ce(a.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),f=await Fe(d,e,t.relationBaseWhere),m=f!==d;if(a.aggregateIndexes&&!t.baseWhere&&!m){const $=ro(a.aggregateIndexes,l.op,l.field,t.by,t.where),W=$===void 0?0:Object.keys($.partial).length,N=$?.index.by?.length??0;if($&&(W===0||W===N)){st(e,$.index);const V=lt(e,$.index.name),J=Object.keys($.partial),pe=[];if(J.length===($.index.by??[]).length&&J.length>0){const Pe=ft($.index.by??[],$.partial),Oe=H(y,u`SELECT ${je} AS value, ${wt} AS count FROM ${u.identifier(V)} WHERE ${He} = ${Pe}`).toArray();return Oe.length>0&&pe.push({key:{...$.partial},value:ut(l.op,Oe[0])}),pe}const Zn=H(y,u`SELECT ${He} AS key, ${je} AS value, ${wt} AS count FROM ${u.identifier(V)}`).toArray();for(const Pe of Zn){const Oe=no(JSON.parse(Pe.key));pe.push({key:Oe,value:ut(l.op,Pe)})}return pe}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const W=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;wn(a,$,W)}const b=Z(f,ge),_=t.by.map($=>u`${ye($)} AS ${u.identifier($)}`);if(l.op==="count")_.push(u`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(u`${u.raw(Ge(l.op))}(${ye($)}) AS value`)}let D=u`SELECT ${u.join(_,u`, `)} FROM ${u.identifier(e)}`;b&&(D=u`${D} WHERE ${b}`),D=u`${D} GROUP BY ${u.join(t.by.map($=>ye($)),u`, `)}`;const S=H(y,D).toArray(),I=[];for(const $ of S){const W={};for(const V of t.by)W[V]=$o(a.shape[V],$[V]??null);const{value:N}=$;I.push({key:W,value:N==null?null:Number(N)})}return I},async insert(e,t,r){const a=j(e,"insert");if(a)return rt(a,e,t,r,!0);const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=Ke(l,vt(l,t,he),{supplied:t,table:e,trusted:p});let f;r?.clientId!==void 0?(Ur(r.clientId),f=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),f=d._id):f=bt();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Se(),b={...d,...z(e),_creationTime:m,_id:f};return te(e,"before","insert")&&await ne("before","insert",{doc:{...b},id:f,op:"insert",table:e}),p||O(e,b),Ae(e),Ie(e),_t(y,e,kr(e),[f,m,de(b)]),at(e,f,b),te(e,"after","insert")&&await ne("after","insert",{doc:b,id:f,op:"insert",table:e}),await ve({doc:b,id:f,op:"insert",table:e}),f},async insertManyUnsafe(e,t,r){if(Qe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=j(e,"insert");if(a){Gr(w.tables[e],t,r?.allowExplicitId,he);for(const _ of t)ee(_);return Lt(a,e,t,r?.allowExplicitId)}const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);Ae(e),Ie(e);const p=[];for(let _=0;_<t.length;_+=Ne)p.push(z(e));const d=r?.allowExplicitId===!0?void 0:nr(l),f=t.map((_,D)=>{const S=vt(l,_,he),I=d===void 0?S:Ke(d,S,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const W=$??bt(),N=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Se(),V={...I,...p[Math.floor(D/Ne)],_creationTime:N,_id:W};return{creationTime:N,document:V,id:W}});for(const _ of f)ee(_.document);const m=async _=>{for(const{document:D,id:S}of _)at(e,S,D);for(const{document:D,id:S}of _)await me({doc:D,id:S,op:"insert",table:e})};let b=0;try{for(let _=0;_<f.length;_+=Ne){const D=f.slice(_,_+Ne),S=u.join(D.map($=>u`(${$.id}, ${$.creationTime}, ${de($.document)})`),u`, `),I=Tn("sqlite",u`INSERT INTO ${u.identifier(e)} (id, _creationTime, ${u.identifier(oe)}) VALUES ${S}`);_t(y,e,I.sql,I.params),b=_+D.length}}catch(_){throw await Hn(e,f.slice(0,b)),_}return await m(f),f.map(_=>_.id)},async insertMany(e,t,r){Qe(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=j(e,"insert");if(p){for(const f of t)ee(f);if(!a)return Lt(p,e,t,void 0)}const d=async f=>p?rt(p,e,f,void 0,!1):U.insert(e,f);for(const f of t)try{l.push(await d(f))}catch(m){if(a&&m instanceof le&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return pn(w,e,t)},async patch(e,t,r,a){T(e,"ctx.db.patch(table, id, values)");const l=Y(t,e);if(!l){const $=be(e);if($){ee(r);try{await $.patch(e,t,r,a)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:f}=l,m=w.tables[f];if(!m)throw new v("INTERNAL",`unknown table: ${f}`);if(q(f,t),yn("patch",r),Mt(f,t,r,d)){o?.({fields:Object.keys(ze(r)),id:t,table:f});return}const b=xo(m,r,d),_={...d,...ze(b),...z(f),_id:t};yt(m,b,_,he);const D=new Set(Object.keys(b)),S=Ke(m,_,{only:D,patched:D,previous:()=>d,table:f,tolerateStoredNull:!0});Mo(a,d,S),te(f,"before","update")&&await ne("before","update",{doc:{...S},id:t,op:"update",previous:d,table:f}),O(f,S,d),Ae(f),Ie(f),Ve(y,f,an(f),[de(S),t,p]),qe(f,t,S,d),Be(f,t,S),We(f,d,S),we(f,t,d,S);const I=R(f,d,S);ue?.invalidate(f,t,I),_e(f,t,"update",S),x({indexKeys:I,key:t,op:"update",row:S,table:f}),te(f,"after","update")&&await ne("after","update",{doc:S,id:t,op:"update",previous:d,table:f}),await ve({doc:S,id:t,op:"update",table:f})},async patchIf(e,t,r){const a=j(e,"patchIf");if(a){if(a.patchIf===void 0)throw new v("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);ee(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw se("update",e,t),p}return l.applied&&se("update",e,t),l}if(!w.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=gn;l+=1){const p=await Yn(e,t,r,l<gn,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new le(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),Qe(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=j(e,"patchWhere")??U,p=(await un(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new v("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 Vo(U,B,e,t)},relationEdges:B,deleteRereadTables:C,inTransaction:fe,softDeleteFields:F,relationWrites:K,query(e){const t=j(e,"query");return t?(q(e,G),t.query(e)):Bn(y,w,e,ae,r=>{r?re(r):q(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=j(e,"rank");if(ae(e,t,"rank"),a)return q(e,G),a.rank(e,t,r);const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(J=>J.name===t);if(!p)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ut(e,l,p),r.restrictsCounts)throw new ht(e);q(e,G),ct(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const f=en(e,p.name),m=p.sortBy.map((J,pe)=>tn(pe)),b=m.map(J=>Le(J)).join(", "),_=H(y,u`SELECT ${u.identifier("__partition__")}, ${u.raw(b)} FROM ${u.identifier(f)} WHERE ${u.identifier("__id__")} = ${d}`).toArray(),[D]=_;if(D===void 0)return null;let S=D.__partition__;const I=Q(r.baseWhere,r.where);pt(I,w,e,"rank");const $=qo(p,I);if($){const J=Po(p.partitionBy??[],$);if(J!==S)return null;S=J}const W=m.map(J=>D[J]),{before:N,total:V}=En(y,f,m,p.sortBy,S,W,d);return{position:N+1,total:V}},async rankBefore(e,t,r){if(ie(e))throw new v("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(m=>m.name===t);if(!l)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ht(e);q(e,G),ct(e,l);const p=en(e,l.name),d=l.sortBy.map((m,b)=>tn(b)),f=l.sortBy.map((m,b)=>ke(r.sortValues[b]??null));return En(y,p,d,l.sortBy,r.partitionKey,f,r.rowId)},async rankPage(e,t,r={}){pt(Q(r.baseWhere,r.where),w,e,"rankPage");const a=j(e,"rankPage");if(ae(e,t,"rank"),a)return q(e,G),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Vt(Ht,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(f=>f.doc)}},async rankPageRows(e,t,r={}){pt(Q(r.baseWhere,r.where),w,e,"rankPage"),ae(e,t,"rank");const{directions:a,hasMore:l,rows:p}=Vt(Ht,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=Y(t,e);if(!r){const d=be(e);if(d?.restore){try{await d.restore(e,t)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const a=w.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new v("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});const p=l?Y(t,e)?.row:void 0;p&&(we(r.tableName,t,p,void 0),we(r.tableName,t,void 0,p))},async replace(e,t,r,a){T(e,"ctx.db.replace(table, id, document)");const l=Y(t,e);if(!l){const W=be(e);if(W){ee(r);try{await W.replace(e,t,r,a)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:f}=l,m=w.tables[f];if(!m)throw new v("INTERNAL",`unknown table: ${f}`);yn("replace",r);const b=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,D=b??_??Se(),S={...r,...z(f),_creationTime:D,_id:t};yt(m,r,S,he);const I=a?.allowExplicitId===!0,$=Ke(m,S,{previous:()=>d,supplied:r,table:f,trusted:I});te(f,"before","update")&&await ne("before","update",{doc:{...$},id:t,op:"update",previous:d,table:f}),I||O(f,$,d),Ae(f),Ie(f),Ve(y,f,Lr(f),[D,de($),t,p]),qe(f,t,$,d),Be(f,t,$),We(f,d,$),we(f,t,d,$),ue?.invalidate(f,t,R(f,d,$)),_e(f,t,"update",$),x({indexKeys:R(f,d,$),key:t,op:"update",row:$,table:f}),te(f,"after","update")&&await ne("after","update",{doc:$,id:t,op:"update",previous:d,table:f}),await ve({doc:$,id:t,op:"update",table:f})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(w.tables).filter(([f,m])=>t.has(f)||r!==void 0&&!r.includes(f)?!1:m.shardMode?.kind!=="global").map(([f])=>f);if(r!==void 0){for(const f of r)if(!w.tables[f])throw new v("INTERNAL",`wipeShard: unknown table: ${f}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new v("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of a){const m=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[f]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Xn={db:U,scheduler:Ct};return n.enforceRls===!0?ar(U,w,(e,t)=>Y(e,t)?.tableName,B):U};export{Es as CDC_LOG_TABLE,Us as IDEMPOTENCY_TABLE,ei as NotUniqueError,Bs as advanceClientWatermark,ms as applyCdcChanges,yn as assertNoExplicitUndefined,Rt as assertStorableRowId,Ur as assertValidClientId,ps as backfillAggregateIndexes,gs as backfillRankIndexes,ys as backfillSearchIndexes,vs as bumpCdcEpoch,Ss as cdcCanVouchFor,Rs as cdcForkedError,_s as cdcSeqLeavingRows,Ts as cdcTouchesTables,As as cdcTrimmedError,Is as compactCdcDocs,Ri as createShardCtxDb,bs as cursorBelowRetainedFloor,wi as meterReadBytes,qs as migrateClientWatermark,Cs as minCdcReplayableSeq,xs as minCdcSeq,pn as normalizeIdStructurally,Ms as readCdcChangeKeys,Ds as readCdcChanges,ks as readCdcCursor,Ls as readCdcEpoch,Ps as readClientWatermark,Gs as readIdempotent,Ns as runShardMigrations,zs as selectShapeMembers,Vs as selectShapeRows,ze as stripReservedPatchFields,Fs as trimCdcChanges,js as trimIdempotent,Hs as writeIdempotent};
|