@lunora/shard-engine 1.0.0-alpha.120 → 1.0.0-alpha.121

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.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BsXerAD-.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-eCIuMGrM.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -586,6 +586,13 @@ interface DatabaseWriterLike {
586
586
  }>;
587
587
  normalizeId: (tableName: string, id: string) => null | string;
588
588
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
589
+ patchIf?: (tableName: string, id: string, args: {
590
+ patch: Record<string, unknown>;
591
+ where: WhereInput;
592
+ }) => Promise<{
593
+ applied: boolean;
594
+ doc: Record<string, unknown> | null;
595
+ }>;
589
596
  patchMany?: (patches: ReadonlyArray<{
590
597
  id: string;
591
598
  patch: Record<string, unknown>;
@@ -916,7 +923,7 @@ declare class NotUniqueError extends LunoraError {
916
923
  constructor(message?: string);
917
924
  }
918
925
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
919
- declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
926
+ declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
920
927
  declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
921
928
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
922
929
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
package/dist/index.d.ts CHANGED
@@ -586,6 +586,13 @@ interface DatabaseWriterLike {
586
586
  }>;
587
587
  normalizeId: (tableName: string, id: string) => null | string;
588
588
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
589
+ patchIf?: (tableName: string, id: string, args: {
590
+ patch: Record<string, unknown>;
591
+ where: WhereInput;
592
+ }) => Promise<{
593
+ applied: boolean;
594
+ doc: Record<string, unknown> | null;
595
+ }>;
589
596
  patchMany?: (patches: ReadonlyArray<{
590
597
  id: string;
591
598
  patch: Record<string, unknown>;
@@ -916,7 +923,7 @@ declare class NotUniqueError extends LunoraError {
916
923
  constructor(message?: string);
917
924
  }
918
925
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
919
- declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
926
+ declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
920
927
  declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
921
928
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
922
929
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CP6A9cx3.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B1yVAkvK.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-GKlDpuM2.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as xe,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Me}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-hGCzG0O1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as we}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BI2lNKPu.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as nr,readDueScheduleOutbox as sr,recordScheduleOutbox as lr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as Er,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Cr,readShapePokeCursor as Rr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CNpeUQ-H.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs";import{SCAN_DEP as Fr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as wr,a as Kr,b as vr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-CyWszGdM.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as lo,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Fo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Csa8ELkU.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as wo}from"./packem_shared/isSoftDeleted-BHlFkAsr.mjs";import{f as vo,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as sa,FLAGS_FUNCTION_PREFIX as la,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as xa,listTables as Ea,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ca,recordShapeProbePass as Ra,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-BGXP6oxh.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Ma}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ka,readBookmark as Ba}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ga,applySelect as qa,buildSeekBeforeWhere as wa,buildSeekWhere as Ka,decodeCursor as va,encodeCursor as Wa,equalityPinnedFields as Xa,normalizeOrderKeys as Ha,softDeleteScope as Va,tiebreakDirectionFor as za,uniqueIndexFields as Qa}from"./packem_shared/CURSOR_PREFIX-C1jsjAPd.mjs";import{QUEUE_TABLE as ja,clearQueueMessages as Ja,isLossyBody as Za,readQueueMessageById as $a,readQueueMessages as et,recordQueueMessages as rt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as at,encodePartitionKey as tt,matchesRankStaticWhere as it,rankKeyFromDoc as nt,rankPivotConditionSql as st,rankTableName as lt,resolveRankPartition as dt,sortColumnName as ct}from"./packem_shared/RANK_TIEBREAK-DrISKVKe.mjs";import{ReactiveCache as pt,reactiveCacheKey as St}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as ft,listReactorStates as xt,migrateReactorState as Et,reactorNeedsRun as ht,readReactorState as Tt,writeReactorState as Ct}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as At,createReadFootprint as gt,markUnvouchableReads as _t}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as bt,indexKeysForRow as Lt,keysTouchRanges as Dt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Ot,whereFilter as Mt,whereOfFilter as Ft}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Nt,RELATED_DEPTH_DECAY as kt,RELATED_MAX_DEPTH as Bt,RELATED_MAX_LIMIT as Ut,deriveRelationEdges as Gt,findRelated as qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{DEFAULT_MAX_RELATION_KEYS as Kt,assertFlatPredicate as vt,assertShapeShardable as Wt,containsRelationPredicate as Xt,isRelationPredicate as Ht,resolveRelationPredicates as Vt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{applyOnDelete as Qt,distinctValues as Yt,fanOutScalarCounts as jt,relationHooks as Jt,resolveWith as Zt,runRowValidators as $t}from"./packem_shared/applyOnDelete-8n5PzcI0.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ri,clampPromotionThresholds as oi,nextPromotionState as ai,relayCountFor as ti,shapeRoutingKey as ii}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as si,OwnerRelay as li,RelayMember as di,createRelayLink as ci}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as pi,gateReplicaDispatch as Si,handleReplicaControl as ui}from"./packem_shared/createReplicaLink-CJn5lH0o.mjs";import{buildReprojectionMigration as xi,countLegacyRows as Ei,reprojectableFields as hi,reprojectionTables as Ti}from"./packem_shared/buildReprojectionMigration-BnUbAUwT.mjs";import{RLS_UNWRAP_SYMBOL as Ri,RlsRequiredError as Ai,guardWriter as gi}from"./packem_shared/RLS_UNWRAP_SYMBOL-DY6k6f6W.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ii,readSchemaHistory as bi,readSchemaVersion as Li,recordSchemaVersion as Di}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Oi}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Fi,isDevEnvironment as yi,readDeployInfo as Ni}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Bi}from"./packem_shared/buildShapeDiff-AxUzi_GL.mjs";import{ShapeDiffCache as Gi,createShapeDiffCache as qi,globalShapeReadKey as wi}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as vi,diffGlobalMembership as Wi,encodeRowsPatch as Xi,projectColumns as Hi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as zi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Yi}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as Ji}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as $i,assertReadonly as en,lintReadonlySql as rn,runReadonlySql as on}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as tn,bigintSqlKey as nn,decodeBigintSqlKey as sn,decodeFloat64SqlKey as ln,float64SqlKey as dn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as mn,subscriptionFrames as pn,subscriptionListDeltas as Sn,trySendFrame as un}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as xn,recordChangedKeys as En,writeTouchesMemo as hn}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Cn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as An}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _n,TransactionHeadroomTracker as In}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ln,runTriggers as Dn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as On}from"./packem_shared/selectExpiredIds-5bAT7X28.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Fn,backfillVectorIndexes as yn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs";import{c as kn,s as Bn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Gn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as wn,reprojectionMigrationId as Kn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Wn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Hn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as zn}from"./packem_shared/runShardMigrations-3BBkjGHs.mjs";import{stableStringify as Yn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Jn}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{ia as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,wr as AGG_COUNT,Kr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,tn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ga as CURSOR_PREFIX,An as ConflictError,R as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,sa as DEFAULT_FANOUT_TOPIC_LIMIT,Kt as DEFAULT_MAX_RELATION_KEYS,si as DEFAULT_MAX_RELAYS,ri as DEFAULT_PROMOTION_THRESHOLDS,_n as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,ho as DurableStreamRunner,la as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,ve as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,$i as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,li as OwnerRelay,ja as QUEUE_TABLE,at as RANK_TIEBREAK,ft as REACTOR_STATE_TABLE,Nt as RELATED_DEFAULT_LIMIT,kt as RELATED_DEPTH_DECAY,Bt as RELATED_MAX_DEPTH,Ut as RELATED_MAX_LIMIT,Gn as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,wn as REPROJECTION_MIGRATION_PREFIX,Ri as RLS_UNWRAP_SYMBOL,pt as ReactiveCache,di as RelayMember,Ai as RlsRequiredError,Fr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ii as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Gi as ShapeDiffCache,zi as ShardRunner,In as TransactionHeadroomTracker,At as UNVOUCHABLE_DEP,Fn as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Re as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,lo as appendStreamChunk,Y as applyCdcChanges,Qt as applyOnDelete,qa as applySelect,ue as archiveCdcSegment,ka as armRestore,vt as assertFlatPredicate,N as assertNoExplicitUndefined,en as assertReadonly,Wt as assertShapeShardable,k as assertValidClientId,mn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,yn as backfillVectorIndexes,nn as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,bt as buildIndexRange,vi as buildPokeFrames,xi as buildReprojectionMigration,wa as buildSeekBeforeWhere,Ka as buildSeekWhere,Fi as buildSettings,Bi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,oi as clampPromotionThresholds,Da as clearCapturedMail,Me as clearCompanionSignatures,Qe as clearMemoryTables,Ja as clearQueueMessages,x as coerceAggregateNumber,oe as compactCdcDocs,kn as compileWhereSql,Ze as computeRankPage,Xt as containsRelationPredicate,Ei as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,gt as createReadFootprint,ci as createRelayLink,pi as createReplicaLink,qi as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Cn as createSystemReader,ae as cursorBelowRetainedFloor,Ro as decideDurableAttach,sn as decodeBigintSqlKey,va as decodeCursor,ln as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,Er as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Gt as deriveRelationEdges,bo as diffExternalSource,Wi as diffGlobalMembership,Yt as distinctValues,E as encodeAggregateKey,Wa as encodeCursor,$o as encodeGeohash,tt as encodePartitionKey,Xi as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,Xa as equalityPinnedFields,o as exportShardRows,ua as facetColumn,jt as fanOutScalarCounts,qt as findRelated,fa as findStorageReferences,po as finishStreamRun,dn as float64SqlKey,h as foldAggregateTally,ar as forgetScheduleOutbox,vo as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Si as gateReplicaDispatch,Vr as geoTableName,wi as globalShapeReadKey,zo as groupUnmappedRows,gi as guardWriter,ui as handleReplicaControl,Ln as hasTrigger,ea as haversineMeters,a as importShardRows,Lt as indexKeysForRow,yi as isDevEnvironment,zr as isFtsAvailable,Wn as isInternalTableName,Za as isLossyBody,Ye as isMemoryTable,Ot as isPushableWhere,Ht as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,xa as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Dt as keysTouchRanges,Do as liftSourceId,rn as lintReadonlySql,xt as listReactorStates,Ea as listTables,_t as markUnvouchableReads,it as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,xn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,Et as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,Cr as minShapePokeCursor,ai as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ha as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,ra as pointInBoundingBox,nr as probeScheduleOutbox,Hi as projectColumns,qo as pullExternalSourceIncrementalTick,wo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,Hn as quoteIdentifier,nt as rankKeyFromDoc,st as rankPivotConditionSql,lt as rankTableName,St as reactiveCacheKey,ht as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Ba as readBookmark,Oa as readCapturedMail,Ee as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ni as readDeployInfo,sr as readDueScheduleOutbox,No as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,$a as readQueueMessageById,et as readQueueMessages,Tt as readReactorState,bi as readSchemaHistory,Li as readSchemaVersion,Sr as readSearchBackfillState,Rr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,ha as readTablePage,Ma as recordCapturedMail,En as recordChangedKeys,Ta as recordFanoutPass,Ca as recordGlobalPollPass,rt as recordQueueMessages,lr as recordScheduleOutbox,Di as recordSchemaVersion,Ra as recordShapeProbePass,Jt as relationHooks,ti as relayCountFor,to as renderSql,hi as reprojectableFields,Kn as reprojectionMigrationId,Ti as reprojectionTables,dt as resolveRankPartition,$e as resolveRankSeekTuple,Vt as resolveRelationPredicates,Zt as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,on as runReadonlySql,$t as runRowValidators,zn as runShardMigrations,Ji as runSocketPool,Gr as runSql,Dn as runTriggers,On as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Oi as serializeSqlValue,Bn as serverInList,ii as shapeRoutingKey,Va as softDeleteScope,ct as sortColumnName,io as sqliteInList,Yn as stableStringify,Jn as stableWireKey,G as stripReservedPatchFields,Yi as stubByName,pn as subscriptionFrames,Sn as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,za as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,xo as trimStreamRuns,eo as tryRowToDocument,un as trySendFrame,no as unionAll,Qa as uniqueIndexFields,s as validateImportRow,Mt as whereFilter,Ft as whereOfFilter,he as writeCdcArchivedThrough,we as writeGlobalShapeSnapshot,Ve as writeIdempotent,Ct as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,hn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-thbeLn0g.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B1yVAkvK.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-GKlDpuM2.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as xe,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Me}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-hGCzG0O1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as we}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BI2lNKPu.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as nr,readDueScheduleOutbox as sr,recordScheduleOutbox as lr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as Er,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Cr,readShapePokeCursor as Rr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CNpeUQ-H.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs";import{SCAN_DEP as Fr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as wr,a as Kr,b as vr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-CyWszGdM.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as lo,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Fo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Csa8ELkU.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as wo}from"./packem_shared/isSoftDeleted-BHlFkAsr.mjs";import{f as vo,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as sa,FLAGS_FUNCTION_PREFIX as la,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as xa,listTables as Ea,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ca,recordShapeProbePass as Ra,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-BGXP6oxh.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Ma}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ka,readBookmark as Ba}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ga,applySelect as qa,buildSeekBeforeWhere as wa,buildSeekWhere as Ka,decodeCursor as va,encodeCursor as Wa,equalityPinnedFields as Xa,normalizeOrderKeys as Ha,softDeleteScope as Va,tiebreakDirectionFor as za,uniqueIndexFields as Qa}from"./packem_shared/CURSOR_PREFIX-C1jsjAPd.mjs";import{QUEUE_TABLE as ja,clearQueueMessages as Ja,isLossyBody as Za,readQueueMessageById as $a,readQueueMessages as et,recordQueueMessages as rt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as at,encodePartitionKey as tt,matchesRankStaticWhere as it,rankKeyFromDoc as nt,rankPivotConditionSql as st,rankTableName as lt,resolveRankPartition as dt,sortColumnName as ct}from"./packem_shared/RANK_TIEBREAK-DrISKVKe.mjs";import{ReactiveCache as pt,reactiveCacheKey as St}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as ft,listReactorStates as xt,migrateReactorState as Et,reactorNeedsRun as ht,readReactorState as Tt,writeReactorState as Ct}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as At,createReadFootprint as gt,markUnvouchableReads as _t}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as bt,indexKeysForRow as Lt,keysTouchRanges as Dt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Ot,whereFilter as Mt,whereOfFilter as Ft}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Nt,RELATED_DEPTH_DECAY as kt,RELATED_MAX_DEPTH as Bt,RELATED_MAX_LIMIT as Ut,deriveRelationEdges as Gt,findRelated as qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{DEFAULT_MAX_RELATION_KEYS as Kt,assertFlatPredicate as vt,assertShapeShardable as Wt,containsRelationPredicate as Xt,isRelationPredicate as Ht,resolveRelationPredicates as Vt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{applyOnDelete as Qt,distinctValues as Yt,fanOutScalarCounts as jt,relationHooks as Jt,resolveWith as Zt,runRowValidators as $t}from"./packem_shared/applyOnDelete-8n5PzcI0.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ri,clampPromotionThresholds as oi,nextPromotionState as ai,relayCountFor as ti,shapeRoutingKey as ii}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as si,OwnerRelay as li,RelayMember as di,createRelayLink as ci}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as pi,gateReplicaDispatch as Si,handleReplicaControl as ui}from"./packem_shared/createReplicaLink-CJn5lH0o.mjs";import{buildReprojectionMigration as xi,countLegacyRows as Ei,reprojectableFields as hi,reprojectionTables as Ti}from"./packem_shared/buildReprojectionMigration-BnUbAUwT.mjs";import{RLS_UNWRAP_SYMBOL as Ri,RlsRequiredError as Ai,guardWriter as gi}from"./packem_shared/RLS_UNWRAP_SYMBOL-Dv9crDfv.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ii,readSchemaHistory as bi,readSchemaVersion as Li,recordSchemaVersion as Di}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Oi}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Fi,isDevEnvironment as yi,readDeployInfo as Ni}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Bi}from"./packem_shared/buildShapeDiff-AxUzi_GL.mjs";import{ShapeDiffCache as Gi,createShapeDiffCache as qi,globalShapeReadKey as wi}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as vi,diffGlobalMembership as Wi,encodeRowsPatch as Xi,projectColumns as Hi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as zi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Yi}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as Ji}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as $i,assertReadonly as en,lintReadonlySql as rn,runReadonlySql as on}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as tn,bigintSqlKey as nn,decodeBigintSqlKey as sn,decodeFloat64SqlKey as ln,float64SqlKey as dn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as mn,subscriptionFrames as pn,subscriptionListDeltas as Sn,trySendFrame as un}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as xn,recordChangedKeys as En,writeTouchesMemo as hn}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Cn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as An}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _n,TransactionHeadroomTracker as In}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ln,runTriggers as Dn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as On}from"./packem_shared/selectExpiredIds-5bAT7X28.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Fn,backfillVectorIndexes as yn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs";import{c as kn,s as Bn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Gn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as wn,reprojectionMigrationId as Kn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Wn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Hn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as zn}from"./packem_shared/runShardMigrations-3BBkjGHs.mjs";import{stableStringify as Yn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Jn}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{ia as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,wr as AGG_COUNT,Kr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,tn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ga as CURSOR_PREFIX,An as ConflictError,R as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,sa as DEFAULT_FANOUT_TOPIC_LIMIT,Kt as DEFAULT_MAX_RELATION_KEYS,si as DEFAULT_MAX_RELAYS,ri as DEFAULT_PROMOTION_THRESHOLDS,_n as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,ho as DurableStreamRunner,la as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,ve as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,$i as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,li as OwnerRelay,ja as QUEUE_TABLE,at as RANK_TIEBREAK,ft as REACTOR_STATE_TABLE,Nt as RELATED_DEFAULT_LIMIT,kt as RELATED_DEPTH_DECAY,Bt as RELATED_MAX_DEPTH,Ut as RELATED_MAX_LIMIT,Gn as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,wn as REPROJECTION_MIGRATION_PREFIX,Ri as RLS_UNWRAP_SYMBOL,pt as ReactiveCache,di as RelayMember,Ai as RlsRequiredError,Fr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ii as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Gi as ShapeDiffCache,zi as ShardRunner,In as TransactionHeadroomTracker,At as UNVOUCHABLE_DEP,Fn as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Re as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,lo as appendStreamChunk,Y as applyCdcChanges,Qt as applyOnDelete,qa as applySelect,ue as archiveCdcSegment,ka as armRestore,vt as assertFlatPredicate,N as assertNoExplicitUndefined,en as assertReadonly,Wt as assertShapeShardable,k as assertValidClientId,mn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,yn as backfillVectorIndexes,nn as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,bt as buildIndexRange,vi as buildPokeFrames,xi as buildReprojectionMigration,wa as buildSeekBeforeWhere,Ka as buildSeekWhere,Fi as buildSettings,Bi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,oi as clampPromotionThresholds,Da as clearCapturedMail,Me as clearCompanionSignatures,Qe as clearMemoryTables,Ja as clearQueueMessages,x as coerceAggregateNumber,oe as compactCdcDocs,kn as compileWhereSql,Ze as computeRankPage,Xt as containsRelationPredicate,Ei as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,gt as createReadFootprint,ci as createRelayLink,pi as createReplicaLink,qi as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Cn as createSystemReader,ae as cursorBelowRetainedFloor,Ro as decideDurableAttach,sn as decodeBigintSqlKey,va as decodeCursor,ln as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,Er as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Gt as deriveRelationEdges,bo as diffExternalSource,Wi as diffGlobalMembership,Yt as distinctValues,E as encodeAggregateKey,Wa as encodeCursor,$o as encodeGeohash,tt as encodePartitionKey,Xi as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,Xa as equalityPinnedFields,o as exportShardRows,ua as facetColumn,jt as fanOutScalarCounts,qt as findRelated,fa as findStorageReferences,po as finishStreamRun,dn as float64SqlKey,h as foldAggregateTally,ar as forgetScheduleOutbox,vo as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Si as gateReplicaDispatch,Vr as geoTableName,wi as globalShapeReadKey,zo as groupUnmappedRows,gi as guardWriter,ui as handleReplicaControl,Ln as hasTrigger,ea as haversineMeters,a as importShardRows,Lt as indexKeysForRow,yi as isDevEnvironment,zr as isFtsAvailable,Wn as isInternalTableName,Za as isLossyBody,Ye as isMemoryTable,Ot as isPushableWhere,Ht as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,xa as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Dt as keysTouchRanges,Do as liftSourceId,rn as lintReadonlySql,xt as listReactorStates,Ea as listTables,_t as markUnvouchableReads,it as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,xn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,Et as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,Cr as minShapePokeCursor,ai as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ha as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,ra as pointInBoundingBox,nr as probeScheduleOutbox,Hi as projectColumns,qo as pullExternalSourceIncrementalTick,wo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,Hn as quoteIdentifier,nt as rankKeyFromDoc,st as rankPivotConditionSql,lt as rankTableName,St as reactiveCacheKey,ht as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Ba as readBookmark,Oa as readCapturedMail,Ee as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ni as readDeployInfo,sr as readDueScheduleOutbox,No as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,$a as readQueueMessageById,et as readQueueMessages,Tt as readReactorState,bi as readSchemaHistory,Li as readSchemaVersion,Sr as readSearchBackfillState,Rr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,ha as readTablePage,Ma as recordCapturedMail,En as recordChangedKeys,Ta as recordFanoutPass,Ca as recordGlobalPollPass,rt as recordQueueMessages,lr as recordScheduleOutbox,Di as recordSchemaVersion,Ra as recordShapeProbePass,Jt as relationHooks,ti as relayCountFor,to as renderSql,hi as reprojectableFields,Kn as reprojectionMigrationId,Ti as reprojectionTables,dt as resolveRankPartition,$e as resolveRankSeekTuple,Vt as resolveRelationPredicates,Zt as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,on as runReadonlySql,$t as runRowValidators,zn as runShardMigrations,Ji as runSocketPool,Gr as runSql,Dn as runTriggers,On as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Oi as serializeSqlValue,Bn as serverInList,ii as shapeRoutingKey,Va as softDeleteScope,ct as sortColumnName,io as sqliteInList,Yn as stableStringify,Jn as stableWireKey,G as stripReservedPatchFields,Yi as stubByName,pn as subscriptionFrames,Sn as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,za as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,xo as trimStreamRuns,eo as tryRowToDocument,un as trySendFrame,no as unionAll,Qa as uniqueIndexFields,s as validateImportRow,Mt as whereFilter,Ft as whereOfFilter,he as writeCdcArchivedThrough,we as writeGlobalShapeSnapshot,Ve as writeIdempotent,Ct as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,hn as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Sn,l as Le,h as _n}from"./fts-companion-pUdD6kF-.mjs";import{sql as a}from"drizzle-orm";import{d as Rn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as It}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as j,CountRlsUnsupportedError as tt,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{backfillAggregateIndexes as jr,backfillRankIndexes as Kr,backfillSearchIndexes as Nr}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{CDC_LOG_TABLE as Vr,applyCdcChanges as zr,bumpCdcEpoch as Jr,cdcCanVouchFor as Yr,cdcForkedError as Xr,cdcSeqLeavingRows as Zr,cdcTouchesTables as ei,cdcTrimmedError as ti,compactCdcDocs as ni,cursorBelowRetainedFloor as oi,minCdcReplayableSeq as ri,minCdcSeq as ii,readCdcChangeKeys as si,readCdcChanges as ci,readCdcCursor as ai,readCdcEpoch as di,trimCdcChanges as li}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Fn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-hGCzG0O1.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as xt}from"./computeRankPage-BI2lNKPu.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as ve,runDrizzle as K}from"./runDrizzle-Du5HLitO.mjs";import{j as He,D as re,r as Re,k as ue,b as We,A as nt,a as Be,e as ce,o as qn,t as Zt,q as bt,i as Wn,h as en,g as Bn}from"./do-sql-CyWszGdM.mjs";import{renderSql as tn,unionAll as ut,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Pn}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as Un,boundingBoxGeohashes as On,haversineMeters as Hn,pointInBoundingBox as Gn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as jn}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Kn,encodeCursor as Ge,normalizeOrderKeys as st,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as ct,buildSeekBeforeWhere as Nn,softDeleteScope as he,equalityPinnedFields as Qn,applySelect as Mt}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Vn,encodePartitionKey as zn,RANK_TIEBREAK as Jn,rankPivotConditionSql as Yn}from"./RANK_TIEBREAK-DrISKVKe.mjs";import{UNVOUCHABLE_DEP as Ft}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Xn,buildIndexRange as Zn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as je,j as Te,c as Y,t as Ke,i as Lt}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as de}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ae}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as eo,isPushableWhere as to}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as no,findRelated as oo}from"./RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{runRowValidators as rt,resolveWith as Wt,relationHooks as Bt,applyOnDelete as ro,fanOutScalarCounts as io}from"./applyOnDelete-8n5PzcI0.mjs";import{guardWriter as so}from"./RLS_UNWRAP_SYMBOL-Dv9crDfv.mjs";import{mayHoldProjectedValue as co}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as ao}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as lo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as gi,readIdempotent as yi,trimIdempotent as $i,writeIdempotent as Ei}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as Si}from"./runShardMigrations-3BBkjGHs.mjs";import{selectShapeMembers as Ri,selectShapeRows as Ti}from"./selectShapeMembers-CNpeUQ-H.mjs";const uo=n=>{const i=atob(n),o=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},fo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ft=(n,i)=>i.query(n),ho=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[d,s]of i.entries()){const w=d===i.length-1;let _=0;for(const m of n)(w?m.startsWith(s):m===s)&&(_+=1);if(_===0)return 0;o+=_}return o},wo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(d)}},po=(n,i,o)=>{const d={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),d},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const m=ft(w,o).length;if(m>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Pt)} search terms are supported (got ${String(m)})`);return _.field=s,_.query=w,_.hasQuery=!0,d}};return d},go=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},yo=n=>Math.min(n.offset+n.numItems+1,z),$o=n=>btoa(`search:${String(n)}`),Eo=n=>{let i;try{i=uo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},mo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Eo(n.cursor):0;if(o===void 0)throw fo();if(o+i>=z)throw new $("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}},So=(n,i)=>{const o=i.offset+i.numItems,d=i.numItems>0&&n.length>o;return{continueCursor:d?$o(o):null,isDone:!d,page:n.slice(i.offset,o)}},_o=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 $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Ro=32,To=1024,sn=(n,i,o,d)=>{const s=`SELECT id, _creationTime, ${Ae(re)} FROM ${Ae(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return i===void 0?je(`${s} ${w}`):Te(`${s} WHERE `,i,` ${w}`)},ht={fieldRef:n=>je(He(n)),serialize:de},cn=n=>{const i=n.map(o=>`${He(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${He("id")} ${Kn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},vo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Ao=n=>{const i=an(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Io=(n,i)=>{const o=n.order,d=Ao(n),{shape:s}=i;return d.length>0?st(d.map(w=>({[w]:o})),s,{pinned:an(n),uniqueBy:on(i.indexes,s)}):st([{_creationTime:o}],s)},Co=(n,i,o,d)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[vo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(rn(i,ct(o))),d&&s.push(Nn(i,ct(d))),s.length!==0)return s.length===1?s[0]:{AND:s}},xo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Ro):n.want},at=(n,i,o,d,s,w,_)=>{const m=Io(d,o),x=cn(m),g=[],{filters:b,want:A}=w;let R=w.cursor??void 0,D=xo(w);if(A===0)return{documents:g,orderKeys:m};for(;;){const W=Y(Co(d,m,R,w.endCursor),ht,Ke),B=sn(i,s&&W?Te(W," AND ",s):s??W,x,D),L=ve(n,B.text,...B.params).toArray();let P={};_(L.length);for(const C of L)if(P=Re(C),b.every(oe=>oe(P))&&g.push(P)===A)return{documents:g,orderKeys:m};if(D===void 0||L.length<D)return{documents:g,orderKeys:m};R=Ge(P,m),D=Math.max(D,Math.min(D*2,To))}},bo=(n,i,o,d,s,w,_,m)=>{const x=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:B}=at(n,i,o,d,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},m),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:L?Ge(L,B):null}}const{documents:g,orderKeys:b}=at(n,i,o,d,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:x+1},m),A=g.length>x,R=A?g.slice(0,x):g,D=R.at(-1);return{continueCursor:A&&D?Ge(D,b):null,isDone:!A,page:R}},Ne=n=>{const i=new Map;return o=>{const d=i.get(o);if(d!==void 0)return d;const s=n(Ae(o));return i.set(o,s),s}},pe=Ae(re),Mo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Ot=Ne(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Do=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),ko=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Fo="SELECT changes() AS changed",Ht=new Map,Lo="",qo=n=>{const i=JSON.stringify(n),o=Ht.get(i);if(o!==void 0)return o;const d=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Lo}`),{sql:s}=tn("sqlite",a`${ut(d)} LIMIT 1`);return Ht.set(i,s),s},Wo=(n,i)=>i.map(()=>n),Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Po=n=>{if(!Bo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Gt=50,dn=500,Pe=Math.floor(nn.boundParams/3),_e=nn.boundParams,Uo=128,fe=(n,i,o)=>{const d=i??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Oo=n=>{const i={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),i),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),i),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),i),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),i),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),i)};return i},Ho=n=>Math.max(n,z),ln=(n,i)=>{const o=n.filters.map(d=>a`${ce(d.field)} = ${de(d.value)}`);return i&&o.push(i),o},Go=(n,i,o,d,s)=>{const w=ft(o.query,lt(o.definition.language));if(w.length===0)return[];const _=Sn(i,o.indexName),m=`${_}__vocab`,x=w.length-1,g=w.map((B,L)=>{const P=wo(B,L===x),C=P.exact?a`${a.identifier("term")} = ${P.lower}`:a`${a.identifier("term")} >= ${P.lower} AND ${a.identifier("term")} < ${P.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${C} GROUP BY ${a.identifier("doc")}`}),b=w.map((B,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),A=a`SELECT f.${a.identifier(Le)} AS ${a.identifier(Le)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${ut(g)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(Le)} HAVING ${a.join(b.map(B=>a`${B} > 0`),a` AND `)}`,R=ln(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${A}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(Le)}`;R.length>0&&(D=a`${D} WHERE ${a.join(R,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(d))}`;const W=[];for(const B of K(n,D)){const L=en(B);if(L){const P=B.__score__;W.push({document:L,score:typeof P=="number"?P:Number(P??0)})}}return W},jo=(n,i,o,d,s)=>{const w=lt(o.definition.language),_=ft(o.query,w);if(_.length===0)return[];const m=ln(o,s);let x=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;m.length>0&&(x=a`${x} WHERE ${a.join(m,a` AND `)}`),x=a`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ho(d)))}`;const g=K(n,x).toArray(),b=[];for(const A of g){const R=en(A);if(!R)continue;const D=ho(_n(R,o.definition),_);D>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:D})}return b.sort((A,R)=>R.score-A.score||R.creationTime-A.creationTime||A.id.localeCompare(R.id)),b.slice(0,d).map(A=>({document:A.doc,score:A.score}))},it=(n,i,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ko=(n,i)=>{const o=n,d={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new $("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:s.lat,lng:s.lng},radiusMeters:w},d},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s.sw,".within() sw corner",i,o.indexName),it(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("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:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},d}};return d},No=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:d,lng:s}=o;return typeof d=="number"&&typeof s=="number"?{lat:d,lng:s}:void 0},Qo=(n,i)=>{const o=No(n,i.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Hn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:d,distance:s}:void 0}return Gn(o,i.within)?{creationTime:d,distance:0}:void 0},Vo=(n,i,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Un(o.near.point,o.near.radiusMeters):On(o.within),w=Bn(i,o.indexName),_=s.map(A=>a`(g.${a.identifier("__geohash__")} >= ${A} AND g.${a.identifier("__geohash__")} < ${`${A}{`})`),m=[a`(${a.join(_,a` OR `)})`];d&&m.push(d);const x=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,g=K(n,x).toArray(),b=[];for(const A of g){const R=Re(A),D=R?Qo(R,o):void 0;R&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:R})}return b.sort((A,R)=>A.distance-R.distance||R.creationTime-A.creationTime),b},un=(n,i,o,d)=>{const s=[];for(const w of n)if(i.every(_=>_(d(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},zo=(n,i,o,d,s,w=()=>{})=>{const _=o.within!==void 0,m=Vo(n,i,o,s).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(m.length),typeof d=="number"?m.slice(0,Math.max(0,Math.floor(d))):m},jt=(n,i,o,d,s,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=s.length>0,g=zo(n,i,m,x?void 0:w,d,_);return x?un(g,s,w,b=>b.document):g},we={fieldRef:ce,serialize:de},Kt=(n,i,o)=>{const d=n.shape[i];if(d!==void 0&&co(d))throw new $("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)`)},Jo=n=>{let i=0;const o=[],d={fieldRef:s=>je(He(s)),relationExists:s=>{const{childWhere:w,negated:_,parentTable:m,relation:x}=s,g=`__rel_${String(i)}`,b=o.at(-1)??m;i+=1,n(x.table,H);const A=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,D=je(`${bt(g,R)} = ${bt(b,A)}`);o.push(g);const W=Y(w,d,Ke);o.pop();const B=W===void 0?D:Te(D," AND ",W),L=Te("EXISTS (SELECT 1 FROM ",Lt(x.table)," AS ",Lt(g)," WHERE ",B,")");return _?Te("NOT ",L):L},serialize:de};return d};class Yo extends ${constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Xo=/\s/u,Zo=String.fromCodePoint(0),Nt=(n,i,o)=>{if(!n.tables[i])throw new $("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Xo.test(o)||o.includes(Zo)?null:o},fn=(n,i,o,d=()=>{},s=()=>{},w=()=>{},_)=>{const m=i.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const x=he(m.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=j(x,g.pushedWhere);return y?Y(y,we):void 0},A=()=>{const y=j(x,g.pushedWhere);return y?Y(y,ht,Ke):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let D=0;const W=y=>{const{search:I}=g;if(!I)throw new $("INTERNAL","runSearchFetch called without a staged search");xn(n,o,m);const k=g.inMemoryFilters.length>0,F=_o(k?void 0:y),Z=Wn(n);if(Z&&!bn(n,o,I.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${I.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 ge=b(),J=Z?Go(n,o,I,F,ge):jo(n,o,I,F,ge);!k&&y===void 0&&go(J);const ie=R();return D=J.length,ie.length>0?un(J,ie,y,Ie=>Ie.document):J},B=y=>W(y).map(I=>I.document),L=y=>{const I=mo(y);return So(B(yo(I)),I)},P=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Zn(o,g.indexName,g.indexFields,g.sqlConditions,de))},C=y=>{P();let I=0;const k=(()=>{if(g.search){const F=B(y);return I=D,F}return g.geo?jt(n,o,g,b(),R(),y,F=>{I=F}).map(F=>F.document):at(n,o,m,g,A(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},F=>{I+=F}).documents})();return w(Math.max(I,k.length)),k},oe=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const I=(()=>{if(g.search){const k=W(void 0);return y=D,k}return jt(n,o,g,b(),R(),void 0,k=>{y=k})})();return w(Math.max(y,I.length)),I},X={async*[Symbol.asyncIterator](){const y=fn(n,i,o,d,s,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let I;for(;;){const k=await y.paginate({cursor:I??null,numItems:Uo});if(yield*k.page,k.isDone||k.continueCursor===null)return;I=k.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return oe()},filter(y){const I=eo(y);return I!==void 0&&to(I,m.shape)?(g.pushedWhere=j(g.pushedWhere,I),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),X},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",X},async paginate(y){let I=0;if(P(),g.search){const F=L(y);return w(F.page.length),F}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=bo(n,o,m,g,y,A(),{all:R(),selective:g.inMemoryFilters.length>0},F=>{I+=F});return w(Math.max(I,k.page.length)),k},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Yo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const k=(m.geoIndexes??[]).find(Z=>Z.name===y);if(!k)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const F={definition:k,indexName:y};if(g.geo=F,I(Ko(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(y,I){const k=m.indexes.find(F=>F.name===y);if(!k)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=k.fields,I&&I(Oo(g)),X},withSearchIndex(y,I){const k=(m.searchIndexes??[]).find(Z=>Z.name===y);if(!k)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=F,I(po(F,o,lt(k.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return X}};return X},Qt=(n,i,o)=>{const d={...i};for(const[s,w]of Zt(n)){if(w.serverDefault){d[s]=w.serverDefault({auth:o});continue}d[s]===void 0&&(w.defaultFn?d[s]=w.defaultFn():"defaultValue"in w&&(d[s]=w.defaultValue))}return d},Vt=(n,i,o,d)=>{const s=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},zt=5,Jt=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],Ue=n=>Yt.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!Yt.includes(i))):n,er=/unique constraint failed/i,tr=n=>n instanceof Error&&er.test(n.message),nr=/string or blob too big/iu,or=(n,i)=>{if(!(!(n instanceof Error)||!nr.test(n.message)))throw new $("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.`)},dt=(n,i,o,d)=>{try{ve(n,o,...d)}catch(s){throw tr(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(or(s,i),s)}},Oe=(n,i,o,d)=>{if(dt(n,i,o,d),ve(n,Fo).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,i,o,d,s,w,_)=>{const m=[];for(let A=0;A<o.length+1;A+=1){const R=o[A],D=d[A],W=D?.direction==="desc"?"desc":"asc",B=R===void 0||D===void 0?a`${a.identifier(Jn)} < ${_}`:Yn(R,w[A],W,!1);if(B===void 0)continue;const L=[];for(let C=0;C<A;C+=1)L.push(a`${a.identifier(o[C])} IS ${w[C]}`);L.push(B);const[P]=L;m.push(L.length===1&&P!==void 0?P:a`(${a.join(L,a` AND `)})`)}const x=m.length>0?a.join(m,a` OR `):a`1 = 0`,g=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${x})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:g.c,total:b.c}},Or=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:d}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=no(s);let m;const x=()=>n.inTransaction?.()===!0,g=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((m===void 0||!x())&&(m=kn(d)),{[Fn]:m}),b=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const h of t)h&&u.push(...Xn(r,h,de));return u.length>0?u:void 0},{headroom:A}=n;let R=!1;const D=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},W=n.onRead??(()=>{}),B=e=>{Ct(s.tables[e])&&W(Ft,Ft)},L=n.onReadRange??(e=>{W(e.table,H)}),P=e=>{B(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==H&&!R&&A?.recordRead(1),B(e),W(e,t)},oe=n.onIndexUse??(()=>{}),X=n.onWrite??(()=>{}),y=e=>{R||A?.recordWrite(e)},I=async e=>{y(e.doc),await X(e)},{cache:k}=n,F=n.clock??(()=>Date.now()),Z=n.idGenerator??(()=>crypto.randomUUID()),ge=n.scheduler??Tn,{globalDb:J}=n,ie=n.auth??{identity:null,userId:null},Ie=n.cdc??!1,Qe=ge,hn=ao({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),ye=(e,t,r,u)=>{Ie&&!Ct(s.tables[e])&&Mn(d,F(),e,t,r,u)},wt=(e,t,r,u)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!Ie)return!1;const h=i?.();if(h===void 0)return!1;const l=Dn(d,e,t,h);return l===void 0?!1:Object.keys(Ue(r)).some(c=>It(l[c])!==It(u[c]))},se=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(se(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return U},Ve=e=>pt(e,"cascade"),N=(e,t)=>{if(se(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,r,u,h)=>{h&&y(r);const l=await e.insert(t,r,u);return w({key:l,op:"insert",row:{...r,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(se(e)&&C(e,H),ze(e,t)),wn=e=>!se(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,r)=>qt(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:r,schema:s,tableName:t}),St=async(e,t,r,u)=>{const h=N(e,"relation grouped count");if(h)return C(e,H),io((S,O)=>h.count(S,O),e,t,r,u);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const c=he(l.softDeleteMode,void 0),f={[t]:{in:r}},p=j(j(f,u),c),v=await Ce(p,e,void 0),E=Y(v,we),M=ce(t);let T=a`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(T=a`${T} WHERE ${E}`),T=a`${T} GROUP BY ${M}`;const q=K(d,T).toArray();return new Map(q.map(S=>[S.__fk__,S.count]))};let xe=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))_t.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>_t.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(xe+=1,xe>Gt)throw xe-=1,new ae(`trigger recursion exceeded ${String(Gt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await lo({ctx:En,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:$e,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:Ee,syncAggregates:be,syncCompanionsForInsert:Rt,syncGeo:Me,syncRanks:me,syncSearch:De}=Ln({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,r)=>k?.invalidate(e,t,b(e,r)),recordCdc:ye,schema:s,sql:d}),Tt=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Se=e=>e===void 0||se(e)?J:void 0,ne=(e,t)=>{const r=vt(t);for(let u=0;u<r.length;u+=_e){const h=r.slice(u,u+_e),[l]=ve(d,qo(h),...Wo(e,h)).toArray();if(!l)continue;const c=l.__t__,f=Re(l);if(typeof c!="string"||!f)return;const p=l[re];return{docJson:typeof p=="string"?p:ue(p??{}),row:f,tableName:c}}},pn=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const h=vt(t);for(let l=0;l<h.length;l+=_e){const c=h.slice(l,l+_e),f=Math.floor(_e/c.length),p=Pn(a`${a.identifier("id")}`,r,!1,f),v=c.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${p}`);for(const E of K(d,ut(v))){const{id:M,__t__:T}=E;typeof T=="string"&&typeof M=="string"&&u.set(M,T)}}return u},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Re,schema:s,sql:d},gn=(e,t,r)=>{const u=Y(r,we);return u===void 0||K(d,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},yn=(e,t,r,u)=>wt(e,t,r,u)?(o?.({fields:Object.keys(Ue(r)),id:t,table:e}),!0):!1,$n=async(e,t,r,u,h)=>{const l=ne(t,e);if(!l)return{applied:!1,doc:null};if(C(e,t),!gn(e,t,r.where)||yn(e,t,r.patch,l.row))return{applied:!1,doc:l.row};try{await h(r.patch)}catch(c){if(c instanceof ae&&c.kind==="occ"&&u)return;throw c}return{applied:!0,doc:ne(t,e)?.row??null}},U={system:hn,async aggregate(e,t){const r=N(e,"aggregate");if(r)return C(e,H),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(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 $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,H);const h=he(u.softDeleteMode,void 0),l=j(j(t.baseWhere,t.where),h),c=await Ce(l,e,t.relationBaseWhere),f=c!==l;if(u.aggregateIndexes&&!t.baseWhere&&!f){const S=Cn(u.aggregateIndexes,t.op,t.field,t.where);if(S){Je(e,S.index);const O=Ze(S.index.by??[],S.key),Q=Xe(e,S.index.name),V=K(d,a`SELECT ${We} AS value, ${nt} AS count FROM ${a.identifier(Q)} WHERE ${Be} = ${O}`).toArray()[0];return et(t.op,V)}}Kt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(c,we),v=qe(t.op),E=ce(t.field);let M=a`SELECT ${a.raw(v)}(${E}) AS value FROM ${a.identifier(e)}`;p&&(M=a`${M} WHERE ${p}`);const q=K(d,M).toArray()[0]?.value;return q??null},asId(e,t){const r=Nt(s,e,t);if(r===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=N(e,"count");if(r)return C(e,H),r.count(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);C(e,H);const l=he(u.softDeleteMode,void 0),c=j(j(h.baseWhere,h.where),l),f=await Ce(c,e,h.relationBaseWhere),p=f!==c;if(u.aggregateIndexes&&!h.baseWhere&&!p){const T=In(u.aggregateIndexes,h.where);if(T){Je(e,T.index);const q=Ze(T.index.by??[],T.key),S=Xe(e,T.index.name),O=K(d,a`SELECT ${We} AS value FROM ${a.identifier(S)} WHERE ${Be} = ${q}`).toArray();return O[0]===void 0?0:O[0].value??0}}const v=Y(f,we);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(E=a`${E} WHERE ${v}`),K(d,E).one().count},async delete(e,t,r){const u=ne(e,t);if(!u){const E=Se(t);E&&(y(void 0),await E.delete(e,t,r));return}const{docJson:h,row:l,tableName:c}=u,f=s.tables[c],p=r?.hard===!0,v=!p&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:l,table:c}),await ro({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,M,T)=>(await Ve(E).findMany(E,{includeDeleted:p,where:{[M]:T}})).page,onCascade:(E,M)=>Ve(E).delete(M,void 0,r),onRestrict:E=>{throw new ae(E,"restrict")},onSetNull:(E,M,T)=>Ve(E).patch(M,{[T]:null}),schema:s,tableName:c}),$e(c),Ee(c),v){const E={...l,...g(c),[v]:F(),_id:e};Oe(d,c,Ot(c),[ue(E),e,h]),De(c,e,E,l),Me(c,e,void 0),be(c,l,E),me(c,e,l,void 0),k?.invalidate(c,e,b(c,l,E)),ye(c,e,"update",E),w({indexKeys:b(c,l,E),key:e,op:"update",row:E,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:c}),await I({id:e,op:"delete",table:c});return}Oe(d,c,ko(c),[e,h]),De(c,e,void 0),Me(c,e,void 0),be(c,l,void 0),me(c,e,l,void 0),k?.invalidate(c,e,b(c,l)),ye(c,e,"delete"),w({indexKeys:b(c,l),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:c}),await I({id:e,op:"delete",table:c})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??dn),u=t?.hard===void 0?void 0:{hard:t.hard},h=se(e)?void 0:e;let l=0;return await D(async()=>{for(;;){const f=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(f.length===0)break;for(const p of f)await U.delete(p,h,u),l+=1;if(f.length<r)break}}),{deleted:l}},async deleteMany(e,t,r){fe(e.length,t?.limit,"deleteMany");for(const u of e)await U.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const l=(await(N(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(c=>String(c._id));if(fe(l.length,r?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,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 jn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=N(e,"findMany");if(r)return C(e,H),r.findMany(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,H):C(e);const l=st(t.orderBy,u.shape,{pinned:Qn(t.where),uniqueBy:on(u.indexes,u.shape)}),c=t.cursor?rn(l,ct(t.cursor)):void 0;let f=j(t.baseWhere,t.where);f=j(f,he(u.softDeleteMode,t.includeDeleted)),f=await qt(f,{canPushExists:Et?wn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),c&&(f=f?{AND:[f,c]}:c);const p=Et?Jo(C):ht,v=Y(f,p,Ke),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,M=sn(e,v,cn(l),E===void 0?void 0:E+1),T=ve(d,M.text,...M.params).toArray();h&&!R&&A?.recordRead(T.length);const q=[];for(const V of T){const G=Re(V);G&&(q.push(G),!h&&typeof G._id=="string"&&C(e,G._id))}if(E===void 0)return t.with&&await Wt({groupedCounter:St,fetcher:ze,parents:q,...Bt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(q,t.select,t.with)};const S=q.length>E,O=S?q.slice(0,E):q,Q=O.at(-1);return t.with&&await Wt({fetcher:ze,groupedCounter:St,parents:O,...Bt(t),schema:s,tableName:e,with:t.with}),{continueCursor:S&&Q&&t.omitContinueCursor!==!0?Ge(Q,l):null,isDone:!S,page:Mt(O,t.select,t.with)}},async get(e,t){const r=ne(e,t);if(!r){const u=Se(t);return u?u.get(e,t):null}return C(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(C(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=N(e,"groupBy");if(r)return C(e,H),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=he(u.softDeleteMode,void 0),c=j(j(t.baseWhere,t.where),l),f=await Ce(c,e,t.relationBaseWhere),p=f!==c;if(u.aggregateIndexes&&!t.baseWhere&&!p){const S=An(u.aggregateIndexes,h.op,h.field,t.by,t.where),O=S===void 0?0:Object.keys(S.partial).length,Q=S?.index.by?.length??0;if(S&&(O===0||O===Q)){Je(e,S.index);const V=Xe(e,S.index.name),G=Object.keys(S.partial),le=[];if(G.length===(S.index.by??[]).length&&G.length>0){const ke=Ze(S.index.by??[],S.partial),Fe=K(d,a`SELECT ${We} AS value, ${nt} AS count FROM ${a.identifier(V)} WHERE ${Be} = ${ke}`).toArray();return Fe.length>0&&le.push({key:{...S.partial},value:et(h.op,Fe[0])}),le}const mn=K(d,a`SELECT ${Be} AS key, ${We} AS value, ${nt} AS count FROM ${a.identifier(V)}`).toArray();for(const ke of mn){const Fe=Rn(JSON.parse(ke.key));le.push({key:Fe,value:et(h.op,ke)})}return le}}for(const S of[...t.by,h.field]){if(S===void 0)continue;const O=S===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${S}" } })`:`groupBy(${e}, { by: [..."${S}"] })`;Kt(u,S,O)}const v=Y(f,we),E=t.by.map(S=>a`${ce(S)} AS ${a.identifier(S)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:S}=h;if(S===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(qe(h.op))}(${ce(S)}) AS value`)}let M=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;v&&(M=a`${M} WHERE ${v}`),M=a`${M} GROUP BY ${a.join(t.by.map(S=>ce(S)),a`, `)}`;const T=K(d,M).toArray(),q=[];for(const S of T){const O={};for(const V of t.by)O[V]=qn(u.shape[V],S[V]??null);const{value:Q}=S;q.push({key:O,value:Q==null?null:Number(Q)})}return q},async insert(e,t,r){const u=N(e,"insert");if(u)return gt(u,e,t,r,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Qt(h,t,ie);rt(h,l);let c;r?.clientId!==void 0?(Po(r.clientId),c=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=Z();const f=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:F(),p={...l,...g(e),_creationTime:f,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),$e(e),Ee(e),dt(d,e,Mo(e),[c,f,ue(p)]),Rt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await I({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,t,r){if(fe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=N(e,"insert");if(u){const f=[];for(const p of t)y(p);for(const p of t){const v=await u.insert(e,p,{allowExplicitId:r?.allowExplicitId});w({key:v,op:"insert",row:{...p,_id:v},table:e}),f.push(v)}return f}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);$e(e),Ee(e);const l=[];for(let f=0;f<t.length;f+=Pe)l.push(g(e));const c=t.map((f,p)=>{const v=Qt(h,f,ie),E=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:Z(),M=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:F(),T={...v,...l[Math.floor(p/Pe)],_creationTime:M,_id:E};return{creationTime:M,document:T,id:E}});for(const f of c)y(f.document);for(let f=0;f<c.length;f+=Pe){const p=a.join(c.slice(f,f+Pe).map(E=>a`(${E.id}, ${E.creationTime}, ${ue(E.document)})`),a`, `),v=tn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${p}`);dt(d,e,v.sql,v.params)}for(const{document:f,id:p}of c)Rt(e,p,f),await X({doc:f,id:p,op:"insert",table:e});return c.map(f=>f.id)},async insertMany(e,t,r){fe(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,h=[],l=N(e,"insert");if(l)for(const f of t)y(f);const c=async f=>l?gt(l,e,f,void 0,!1):U.insert(e,f);for(const f of t)try{h.push(await c(f))}catch(p){if(u&&p instanceof ae&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Nt(s,e,t)},async patch(e,t,r){const u=ne(e,r);if(!u){const v=Se(r);if(v){y(t),await v.patch(e,t,r);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,f=s.tables[c];if(!f)throw new $("INTERNAL",`unknown table: ${c}`);if(C(c,e),Jt("patch",t),wt(c,e,t,l)){o?.({fields:Object.keys(Ue(t)),id:e,table:c});return}const p={...l,...Ue(t),...g(c),_id:e};Vt(f,t,p,ie),rt(f,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:l,table:c}),$e(c),Ee(c),Oe(d,c,Ot(c),[ue(p),e,h]),De(c,e,p,l),Me(c,e,p),be(c,l,p),me(c,e,l,p),k?.invalidate(c,e,b(c,l,p)),ye(c,e,"update",p),w({indexKeys:b(c,l,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:l,table:c}),await I({doc:p,id:e,op:"update",table:c})},async patchIf(e,t,r){const u=N(e,"patchIf");if(u){if(u.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return y(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=zt;h+=1){const l=await $n(e,t,r,h<zt,c=>U.patch(t,c,e));if(l!==void 0)return l}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){fe(e.length,t?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const l=(await(N(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(c=>({id:String(c._id),patch:t.patch}));if(fe(l.length,r?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,r),{patched:l.length}},async related(e,t){return oo(U,_,e,t)},relationEdges:_,query(e){const t=N(e,"query");return t?(C(e,H),t.query(e)):fn(d,s,e,oe,r=>{r?P(r):C(e,H)},r=>{R||A?.recordRead(r)})},async rank(e,t,r){const u=N(e,"rank");if(u)return C(e,H),u.rank(e,t,r);oe(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),r.restrictsCounts)throw new tt(e);C(e,H),Ye(e,l);const c=typeof r.row=="string"?r.row:r.row._id;if(!c)return null;const f=Dt(e,l.name),p=l.sortBy.map((G,le)=>kt(le)),v=p.map(G=>Ae(G)).join(", "),E=K(d,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(f)} WHERE ${a.identifier("__id__")} = ${c}`).toArray(),[M]=E;if(M===void 0)return null;let T=M.__partition__;const q=j(r.baseWhere,r.where);ot(q,s,e,"rank");const S=Vn(l,q);if(S){const G=zn(l.partitionBy??[],S);if(G!==T)return null;T=G}const O=p.map(G=>M[G]),{before:Q,total:V}=Xt(d,f,p,l.sortBy,T,O,c);return{position:Q+1,total:V}},async rankBefore(e,t,r){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new tt(e);C(e,H),Ye(e,h);const l=Dt(e,h.name),c=h.sortBy.map((p,v)=>kt(v)),f=h.sortBy.map((p,v)=>de(r.sortValues[v]??null));return Xt(d,l,c,h.sortBy,r.partitionKey,f,r.rowId)},async rankPage(e,t,r={}){ot(j(r.baseWhere,r.where),s,e,"rankPage");const u=N(e,"rankPage");if(u)return C(e,H),u.rankPage(e,t,r);oe(e,t,"rank");const{continueCursor:h,hasMore:l,rows:c}=xt(At,e,t,r);return{continueCursor:h,isDone:!l,page:c.map(f=>f.doc)}},async rankPageRows(e,t,r={}){ot(j(r.baseWhere,r.where),s,e,"rankPage"),oe(e,t,"rank");const{directions:u,hasMore:h,rows:l}=xt(At,e,t,r);return{directions:u,hasMore:h,rows:l}},async restore(e,t){const r=ne(e,t);if(!r){const l=Se(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new $("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const h=r.row[u]!==null&&r.row[u]!==void 0;await U.patch(e,{[u]:null},t),h&&me(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const h=ne(e,r);if(!h){const q=Se(r);if(q){y(t),await q.replace(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:c,tableName:f}=h,p=s.tables[f];if(!p)throw new $("INTERNAL",`unknown table: ${f}`);Jt("replace",t);const v=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof c._creationTime=="number"?c._creationTime:void 0,M=v??E??F(),T={...t,...g(f),_creationTime:M,_id:e};Vt(p,t,T,ie),rt(p,T),ee(f,"before","update")&&await te("before","update",{doc:{...T},id:e,op:"update",previous:c,table:f}),$e(f),Ee(f),Oe(d,f,Do(f),[M,ue(T),e,l]),De(f,e,T,c),Me(f,e,T),be(f,c,T),me(f,e,c,T),k?.invalidate(f,e,b(f,c,T)),ye(f,e,"update",T),w({indexKeys:b(f,c,T),key:e,op:"update",row:T,table:f}),ee(f,"after","update")&&await te("after","update",{doc:T,id:e,op:"update",previous:c,table:f}),await I({doc:T,id:e,op:"update",table:f})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([f,p])=>t.has(f)||r!==void 0&&!r.includes(f)?!1:p.shardMode?.kind!=="global").map(([f])=>f);if(r!==void 0){for(const f of r)if(!s.tables[f])throw new $("INTERNAL",`wipeShard: unknown table: ${f}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of u){const p=await c(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[f]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},En={db:U,scheduler:ge};return n.enforceRls===!0?so(U,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>pn(e,t),_):U};export{Vr as CDC_LOG_TABLE,gi as IDEMPOTENCY_TABLE,Yo as NotUniqueError,fi as advanceClientWatermark,zr as applyCdcChanges,Jt as assertNoExplicitUndefined,Po as assertValidClientId,jr as backfillAggregateIndexes,Kr as backfillRankIndexes,Nr as backfillSearchIndexes,Jr as bumpCdcEpoch,Yr as cdcCanVouchFor,Xr as cdcForkedError,Zr as cdcSeqLeavingRows,ei as cdcTouchesTables,ti as cdcTrimmedError,ni as compactCdcDocs,Or as createShardCtxDb,oi as cursorBelowRetainedFloor,hi as migrateClientWatermark,ri as minCdcReplayableSeq,ii as minCdcSeq,Nt as normalizeIdStructurally,si as readCdcChangeKeys,ci as readCdcChanges,ai as readCdcCursor,di as readCdcEpoch,wi as readClientWatermark,yi as readIdempotent,Si as runShardMigrations,Ri as selectShapeMembers,Ti as selectShapeRows,Ue as stripReservedPatchFields,li as trimCdcChanges,$i as trimIdempotent,Ei as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},I=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),O={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},W=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),k=(a,n,l)=>{for(const d of W)typeof n[d]=="function"&&(a[d]=O[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of I){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(k(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{I as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
@@ -1 +1 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-CP6A9cx3.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-3BBkjGHs.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=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 r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-thbeLn0g.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-3BBkjGHs.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=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 r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.120",
3
+ "version": "1.0.0-alpha.121",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
52
- "@lunora/platform": "1.0.0-alpha.59",
52
+ "@lunora/platform": "1.0.0-alpha.60",
53
53
  "drizzle-orm": "^0.45.3"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as yn,l as Le,h as $n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as mn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as At}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as En,aggregateSqlFunction as qe,normalizeCountArgument as Sn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ye,encodeAggregateKey as Xe,readAggregateValue as Ze}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as et,selectIndexForGroupBy as _n,selectIndexForCount as Rn,selectIndexForAggregate as Tn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as vn,searchIndexCoversTable as An}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{backfillAggregateIndexes as Uo,backfillRankIndexes as Oo,backfillSearchIndexes as Ho}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{appendCdcChange as In,readCdcDocAtOrBefore as Cn}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{CDC_LOG_TABLE as No,applyCdcChanges as jo,bumpCdcEpoch as Ko,cdcCanVouchFor as Qo,cdcForkedError as Vo,cdcSeqLeavingRows as zo,cdcTouchesTables as Jo,cdcTrimmedError as Yo,compactCdcDocs as Xo,cursorBelowRetainedFloor as Zo,minCdcReplayableSeq as ei,minCdcSeq as ti,readCdcChangeKeys as ni,readCdcChanges as ri,readCdcCursor as oi,readCdcEpoch as ii,trimCdcChanges as si}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{allocateCommitSeq as xn,COMMIT_SEQ_FIELD as bn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Mn}from"./createCompanionSync-hGCzG0O1.mjs";import{isMemoryTable as It}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ct}from"./computeRankPage-BI2lNKPu.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as ve,runDrizzle as j}from"./runDrizzle-Du5HLitO.mjs";import{j as Oe,D as re,r as _e,k as le,b as We,A as tt,a as Be,e as ce,o as Dn,t as Yt,q as xt,i as kn,h as Xt,g as Fn}from"./do-sql-CyWszGdM.mjs";import{renderSql as Zt,unionAll as ut,WORKERD_SQLITE_LIMITS as en,sqliteInList as Ln}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as qn,boundingBoxGeohashes as Wn,haversineMeters as Bn,pointInBoundingBox as Pn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Un}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as On,encodeCursor as He,normalizeOrderKeys as st,uniqueIndexFields as tn,buildSeekWhere as nn,decodeCursor as ct,buildSeekBeforeWhere as Hn,softDeleteScope as fe,equalityPinnedFields as Gn,applySelect as bt}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Nn,encodePartitionKey as jn,RANK_TIEBREAK as Kn,rankPivotConditionSql as Qn}from"./RANK_TIEBREAK-DrISKVKe.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Vn,buildIndexRange as zn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as Re,c as te,t as Ne,i as Ft}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ae}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Jn,isPushableWhere as Yn}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{assertFlatPredicate as nt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{runRowValidators as rt,resolveWith as qt,relationHooks as Wt,applyOnDelete as er,fanOutScalarCounts as tr}from"./applyOnDelete-8n5PzcI0.mjs";import{guardWriter as nr}from"./RLS_UNWRAP_SYMBOL-DY6k6f6W.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as or}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Te}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ir}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ai,migrateClientWatermark as di,readClientWatermark as li}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as fi,readIdempotent as hi,trimIdempotent as wi,writeIdempotent as gi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as yi}from"./runShardMigrations-3BBkjGHs.mjs";import{selectShapeMembers as mi,selectShapeRows as Ei}from"./selectShapeMembers-CNpeUQ-H.mjs";const sr=n=>{const o=atob(n),r=Uint8Array.from(o,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},cr=()=>new $("BAD_REQUEST","invalid cursor"),Bt=16,Pt=8,z=1024,ft=(n,o)=>o.query(n),ar=(n,o)=>{if(n.length===0)return 0;let r=0;for(const[a,i]of o.entries()){const w=a===o.length-1;let _=0;for(const E of n)(w?E.startsWith(i):E===i)&&(_+=1);if(_===0)return 0;r+=_}return r},dr=(n,o)=>{if(!o)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(a)}},lr=(n,o,r)=>{const a={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${o}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${o}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),a},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${o}" indexes "${_.definition.field}", not "${i}"`);const E=ft(w,r).length;if(E>Bt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${o}": at most ${String(Bt)} search terms are supported (got ${String(E)})`);return _.field=i,_.query=w,_.hasQuery=!0,a}};return a},ur=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},fr=n=>Math.min(n.offset+n.numItems+1,z),hr=n=>btoa(`search:${String(n)}`),wr=n=>{let o;try{o=sr(n)}catch{return}if(!o.startsWith("search:"))return;const r=Number(o.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},gr=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const o=Math.max(0,Math.floor(n.numItems)),r=n.cursor?wr(n.cursor):0;if(r===void 0)throw cr();if(r+o>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(o)} 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-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:o,offset:r}},pr=(n,o)=>{const r=o.offset+o.numItems,a=o.numItems>0&&n.length>r;return{continueCursor:a?hr(r):null,isDone:!a,page:n.slice(o.offset,r)}},yr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const o=Math.max(0,Math.floor(n));if(o>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},$r=32,mr=1024,rn=(n,o,r,a)=>{const i=`SELECT id, _creationTime, ${Ae(re)} FROM ${Ae(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return o===void 0?Ge(`${i} ${w}`):Re(`${i} WHERE `,o,` ${w}`)},ht={fieldRef:n=>Ge(Oe(n)),serialize:ae},on=n=>{const o=n.map(r=>`${Oe(r.field)} ${r.direction==="desc"?"DESC":"ASC"}`);return n.some(r=>r.field==="_id"||r.field==="id")||o.push(`${Oe("id")} ${On(n)==="desc"?"DESC":"ASC"}`),o.join(", ")},Er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=n=>new Set(n.sqlConditions.filter(o=>o.comparator==="=").map(o=>o.field)),Sr=n=>{const o=sn(n);let r=0;for(;r<n.indexFields.length&&o.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},_r=(n,o)=>{const r=n.order,a=Sr(n),{shape:i}=o;return a.length>0?st(a.map(w=>({[w]:r})),i,{pinned:sn(n),uniqueBy:tn(o.indexes,i)}):st([{_creationTime:r}],i)},Rr=(n,o,r,a)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[Er[w.comparator]??"eq"]:w.value}}));if(r&&i.push(nn(o,ct(r))),a&&i.push(Hn(o,ct(a))),i.length!==0)return i.length===1?i[0]:{AND:i}},Tr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,$r):n.want},at=(n,o,r,a,i,w,_)=>{const E=_r(a,r),x=on(E),p=[],{filters:b,want:A}=w;let R=w.cursor??void 0,D=Tr(w);if(A===0)return{documents:p,orderKeys:E};for(;;){const W=te(Rr(a,E,R,w.endCursor),ht,Ne),B=rn(o,i&&W?Re(W," AND ",i):i??W,x,D),L=ve(n,B.text,...B.params).toArray();let P={};_(L.length);for(const C of L)if(P=_e(C),b.every(ne=>ne(P))&&p.push(P)===A)return{documents:p,orderKeys:E};if(D===void 0||L.length<D)return{documents:p,orderKeys:E};R=He(P,E),D=Math.max(D,Math.min(D*2,mr))}},vr=(n,o,r,a,i,w,_,E)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:W,orderKeys:B}=at(n,o,r,a,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},E),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:W,splitCursor:L?He(L,B):null}}const{documents:p,orderKeys:b}=at(n,o,r,a,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},E),A=p.length>x,R=A?p.slice(0,x):p,D=R.at(-1);return{continueCursor:A&&D?He(D,b):null,isDone:!A,page:R}},je=n=>{const o=new Map;return r=>{const a=o.get(r);if(a!==void 0)return a;const i=n(Ae(r));return o.set(r,i),i}},he=Ae(re),Ar=je(n=>`INSERT INTO ${n} (id, _creationTime, ${he}) VALUES (?, ?, ?)`),Ut=je(n=>`UPDATE ${n} SET ${he} = ? WHERE id = ? AND ${he} = ?`),Ir=je(n=>`UPDATE ${n} SET _creationTime = ?, ${he} = ? WHERE id = ? AND ${he} = ?`),Cr=je(n=>`DELETE FROM ${n} WHERE id = ? AND ${he} = ?`),xr="SELECT changes() AS changed",Ot=new Map,br="",Mr=n=>{const o=JSON.stringify(n),r=Ot.get(o);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(re)} FROM ${c.identifier(w)} WHERE id = ${br}`),{sql:i}=Zt("sqlite",c`${ut(a)} LIMIT 1`);return Ot.set(o,i),i},Dr=(n,o)=>o.map(()=>n),kr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Fr=n=>{if(!kr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ht=50,cn=500,Pe=Math.floor(en.boundParams/3),Ee=en.boundParams,Lr=128,ue=(n,o,r)=>{const a=o??cn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},qr=n=>{const o={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),o),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),o),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),o),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),o),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),o)};return o},Wr=n=>Math.max(n,z),an=(n,o)=>{const r=n.filters.map(a=>c`${ce(a.field)} = ${ae(a.value)}`);return o&&r.push(o),r},Br=(n,o,r,a,i)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const _=yn(o,r.indexName),E=`${_}__vocab`,x=w.length-1,p=w.map((B,L)=>{const P=dr(B,L===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(E)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),A=c`SELECT f.${c.identifier(Le)} AS ${c.identifier(Le)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(p)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Le)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=an(r,i);let D=c`SELECT m.id, m._creationTime, m.${c.identifier(re)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${A}) s JOIN ${c.identifier(o)} m ON m.id = s.${c.identifier(Le)}`;R.length>0&&(D=c`${D} WHERE ${c.join(R,c` AND `)}`),D=c`${D} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const W=[];for(const B of j(n,D)){const L=Xt(B);if(L){const P=B.__score__;W.push({document:L,score:typeof P=="number"?P:Number(P??0)})}}return W},Pr=(n,o,r,a,i)=>{const w=lt(r.definition.language),_=ft(r.query,w);if(_.length===0)return[];const E=an(r,i);let x=c`SELECT id, _creationTime, ${c.identifier(re)} FROM ${c.identifier(o)}`;E.length>0&&(x=c`${x} WHERE ${c.join(E,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Wr(a)))}`;const p=j(n,x).toArray(),b=[];for(const A of p){const R=Xt(A);if(!R)continue;const D=ar($n(R,r.definition),_);D>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:D})}return b.sort((A,R)=>R.score-A.score||R.creationTime-A.creationTime||A.id.localeCompare(R.id)),b.slice(0,a).map(A=>({document:A.doc,score:A.score}))},ot=(n,o,r,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${r}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ur=(n,o)=>{const r=n,a={near:(i,w)=>{if(r.within)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near() or .within(), not both`);if(ot(i,".near() point",o,r.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},a},within:i=>{if(r.near)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near() or .within(), not both`);if(ot(i.sw,".within() sw corner",o,r.indexName),ot(i.ne,".within() ne corner",o,r.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .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 r.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},a}};return a},Or=(n,o)=>{const r=n[o];if(r===null||typeof r!="object")return;const{lat:a,lng:i}=r;return typeof a=="number"&&typeof i=="number"?{lat:a,lng:i}:void 0},Hr=(n,o)=>{const r=Or(n,o.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(o.near){const i=Bn(o.near.point,r);return i<=o.near.radiusMeters?{creationTime:a,distance:i}:void 0}return Pn(r,o.within)?{creationTime:a,distance:0}:void 0},Gr=(n,o,r,a)=>{if(!r.near&&!r.within)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const i=r.near?qn(r.near.point,r.near.radiusMeters):Wn(r.within),w=Fn(o,r.indexName),_=i.map(A=>c`(g.${c.identifier("__geohash__")} >= ${A} AND g.${c.identifier("__geohash__")} < ${`${A}{`})`),E=[c`(${c.join(_,c` OR `)})`];a&&E.push(a);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(re)} FROM ${c.identifier(w)} g JOIN ${c.identifier(o)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(E,c` AND `)}`,p=j(n,x).toArray(),b=[];for(const A of p){const R=_e(A),D=R?Hr(R,r):void 0;R&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:R})}return b.sort((A,R)=>A.distance-R.distance||R.creationTime-A.creationTime),b},dn=(n,o,r,a)=>{const i=[];for(const w of n)if(o.every(_=>_(a(w)))&&(i.push(w),typeof r=="number"&&i.length>=r))break;return i},Nr=(n,o,r,a,i,w=()=>{})=>{const _=r.within!==void 0,E=Gr(n,o,r,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(E.length),typeof a=="number"?E.slice(0,Math.max(0,Math.floor(a))):E},Gt=(n,o,r,a,i,w,_=()=>{})=>{const{geo:E}=r;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,p=Nr(n,o,E,x?void 0:w,a,_);return x?dn(p,i,w,b=>b.document):p},Se={fieldRef:ce,serialize:ae},Nt=(n,o,r)=>{const a=n.shape[o];if(a!==void 0&&rr(a))throw new $("BAD_REQUEST",`${r}: "${o}" 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)`)},jr=n=>{let o=0;const r=[],a={fieldRef:i=>Ge(Oe(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:E,relation:x}=i,p=`__rel_${String(o)}`,b=r.at(-1)??E;o+=1,n(x.table,H);const A=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,D=Ge(`${xt(p,R)} = ${xt(b,A)}`);r.push(p);const W=te(w,a,Ne);r.pop();const B=W===void 0?D:Re(D," AND ",W),L=Re("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(p)," WHERE ",B,")");return _?Re("NOT ",L):L},serialize:ae};return a};class Kr extends ${constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Qr=/\s/u,Vr=String.fromCodePoint(0),jt=(n,o,r)=>{if(!n.tables[o])throw new $("INTERNAL",`unknown table: ${o}`);return typeof r!="string"||r.length===0||Qr.test(r)||r.includes(Vr)?null:r},ln=(n,o,r,a=()=>{},i=()=>{},w=()=>{},_)=>{const E=o.tables[r];if(!E)throw new $("INTERNAL",`unknown table: ${r}`);const x=fe(E.softDeleteMode,void 0),p=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,p.pushedWhere);return y?te(y,Se):void 0},A=()=>{const y=N(x,p.pushedWhere);return y?te(y,ht,Ne):void 0},R=()=>[...p.inMemoryFilters,...p.verifyFilters];let D=0;const W=y=>{const{search:I}=p;if(!I)throw new $("INTERNAL","runSearchFetch called without a staged search");vn(n,r,E);const k=p.inMemoryFilters.length>0,F=yr(k?void 0:y),X=kn(n);if(X&&!An(n,r,I.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" 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 we=b(),J=X?Br(n,r,I,F,we):Pr(n,r,I,F,we);!k&&y===void 0&&ur(J);const oe=R();return D=J.length,oe.length>0?dn(J,oe,y,Ie=>Ie.document):J},B=y=>W(y).map(I=>I.document),L=y=>{const I=gr(y);return pr(B(fr(I)),I)},P=()=>{if(p.search||p.geo||p.indexName===void 0){i(void 0);return}i(zn(r,p.indexName,p.indexFields,p.sqlConditions,ae))},C=y=>{P();let I=0;const k=(()=>{if(p.search){const F=B(y);return I=D,F}return p.geo?Gt(n,r,p,b(),R(),y,F=>{I=F}).map(F=>F.document):at(n,r,E,p,A(),{filters:R(),selective:p.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},F=>{I+=F}).documents})();return w(Math.max(I,k.length)),k},ne=()=>{if(!p.search&&!p.geo)throw new $("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const I=(()=>{if(p.search){const k=W(void 0);return y=D,k}return Gt(n,r,p,b(),R(),void 0,k=>{y=k})})();return w(Math.max(y,I.length)),I},Y={async*[Symbol.asyncIterator](){const y=ln(n,o,r,a,i,w,{...p,indexFields:[...p.indexFields],inMemoryFilters:[...p.inMemoryFilters],sqlConditions:[...p.sqlConditions],verifyFilters:[...p.verifyFilters]});if(p.search){yield*await y.collect();return}let I;for(;;){const k=await y.paginate({cursor:I??null,numItems:Lr});if(yield*k.page,k.isDone||k.continueCursor===null)return;I=k.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const I=Jn(y);return I!==void 0&&Yn(I,E.shape)?(p.pushedWhere=N(p.pushedWhere,I),p.verifyFilters.push(y)):p.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return p.order=y==="desc"?"desc":"asc",Y},async paginate(y){let I=0;if(P(),p.search){const F=L(y);return w(F.page.length),F}if(p.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=vr(n,r,E,p,y,A(),{all:R(),selective:p.inMemoryFilters.length>0},F=>{I+=F});return w(Math.max(I,k.page.length)),k},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Kr(`unique() on table "${r}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const k=(E.geoIndexes??[]).find(X=>X.name===y);if(!k)throw new $("INTERNAL",`unknown geo index "${y}" on table "${r}"`);a(r,y,"geo");const F={definition:k,indexName:y};if(p.geo=F,I(Ur(F,r)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${y}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,I){const k=E.indexes.find(F=>F.name===y);if(!k)throw new $("INTERNAL",`unknown index "${y}" on table "${r}"`);return a(r,y,"index"),p.indexName=y,p.indexFields=k.fields,I&&I(qr(p)),Y},withSearchIndex(y,I){const k=(E.searchIndexes??[]).find(X=>X.name===y);if(!k)throw new $("INTERNAL",`unknown search index "${y}" on table "${r}"`);a(r,y,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:y,query:""};if(p.search=F,I(lr(F,r,lt(k.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${r}" requires a .search(field, query) call`);return Y}};return Y},Kt=(n,o,r)=>{const a={...o};for(const[i,w]of Yt(n)){if(w.serverDefault){a[i]=w.serverDefault({auth:r});continue}a[i]===void 0&&(w.defaultFn?a[i]=w.defaultFn():"defaultValue"in w&&(a[i]=w.defaultValue))}return a},Qt=(n,o,r,a)=>{const i=r;for(const[w,_]of Yt(n)){if(_.serverDefault){w in o&&(i[w]=_.serverDefault({auth:a}));continue}_.onUpdateFn&&!(w in o)&&(i[w]=_.onUpdateFn())}},Vt=(n,o)=>{for(const r of Object.keys(o))if(o[r]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},zt=["_commitSeq","_creationTime","_id"],it=n=>zt.some(o=>o in n)?Object.fromEntries(Object.entries(n).filter(([o])=>!zt.includes(o))):n,zr=/unique constraint failed/i,Jr=n=>n instanceof Error&&zr.test(n.message),Yr=/string or blob too big/iu,Xr=(n,o)=>{if(!(!(n instanceof Error)||!Yr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${o}": 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.`)},dt=(n,o,r,a)=>{try{ve(n,r,...a)}catch(i){throw Jr(i)?new Te(`unique constraint violation on "${o}"`,"unique"):(Xr(i,o),i)}},Ue=(n,o,r,a)=>{if(dt(n,o,r,a),ve(n,xr).one().changed===0)throw new Te(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,o,r,a,i,w,_)=>{const E=[];for(let A=0;A<r.length+1;A+=1){const R=r[A],D=a[A],W=D?.direction==="desc"?"desc":"asc",B=R===void 0||D===void 0?c`${c.identifier(Kn)} < ${_}`:Qn(R,w[A],W,!1);if(B===void 0)continue;const L=[];for(let C=0;C<A;C+=1)L.push(c`${c.identifier(r[C])} IS ${w[C]}`);L.push(B);const[P]=L;E.push(L.length===1&&P!==void 0?P:c`(${c.join(L,c` AND `)})`)}const x=E.length>0?c.join(E,c` OR `):c`1 = 0`,p=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(o)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(o)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:p.c,total:b.c}},Wo=n=>{const{baselineSeq:o,onStalePatchDropped:r}=n,{sql:a}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=Xn(i);let E;const x=()=>n.inTransaction?.()===!0,p=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((E===void 0||!x())&&(E=xn(a)),{[bn]:E}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Vn(s,h,ae));return f.length>0?f:void 0},{headroom:A}=n;let R=!1;const D=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},W=n.onRead??(()=>{}),B=e=>{It(i.tables[e])&&W(kt,kt)},L=n.onReadRange??(e=>{W(e.table,H)}),P=e=>{B(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==H&&!R&&A?.recordRead(1),B(e),W(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||A?.recordWrite(e)},I=async e=>{y(e.doc),await Y(e)},{cache:k}=n,F=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),we=n.scheduler??En,{globalDb:J}=n,oe=n.auth??{identity:null,userId:null},Ie=n.cdc??!1,Ke=we,un=or({scheduler:typeof Ke.list=="function"&&typeof Ke.get=="function"?Ke:void 0,storage:n.storage}),ge=(e,t,s,f)=>{Ie&&!It(i.tables[e])&&In(a,F(),e,t,s,f)},fn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ie)return!1;const h=o?.();if(h===void 0)return!1;const l=Cn(a,e,t,h);return l===void 0?!1:Object.keys(it(s)).some(d=>At(l[d])!==At(f[d]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return U},Qe=e=>wt(e,"cascade"),K=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},Ve=(e,t)=>wt(e,"relation load").findMany(e,t),pt=(e,t)=>(ie(e)&&C(e,H),Ve(e,t)),hn=e=>!ie(e.table),yt=n.relationExistsPushDown??"auto",$t=yt!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,s)=>Lt(e,{fetcher:pt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),Et=async(e,t,s,f)=>{const h=K(e,"relation grouped count");if(h)return C(e,H),tr((S,O)=>h.count(S,O),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const d=fe(l.softDeleteMode,void 0),u={[t]:{in:s}},g=N(N(u,f),d),v=await Ce(g,e,void 0),m=te(v,Se),M=ce(t);let T=c`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(T=c`${T} WHERE ${m}`),T=c`${T} GROUP BY ${M}`;const q=j(a,T).toArray();return new Map(q.map(S=>[S.__fk__,S.count]))};let xe=0;const St=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))St.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>St.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(xe+=1,xe>Ht)throw xe-=1,new Te(`trigger recursion exceeded ${String(Ht)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ir({ctx:gn,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:ze,ensureRankBackfilled:Je,ensureRankBackfilledForTable:ye,syncAggregates:be,syncCompanionsForInsert:_t,syncGeo:Me,syncRanks:$e,syncSearch:De}=Mn({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>k?.invalidate(e,t,b(e,s)),recordCdc:ge,schema:i,sql:a}),Rt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),me=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=Tt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=ve(a,Mr(h),...Dr(e,h)).toArray();if(!l)continue;const d=l.__t__,u=_e(l);if(typeof d!="string"||!u)return;const g=l[re];return{docJson:typeof g=="string"?g:le(g??{}),row:u,tableName:d}}},wn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=Ee){const d=h.slice(l,l+Ee),u=Math.floor(Ee/d.length),g=Ln(c`${c.identifier("id")}`,s,!1,u),v=d.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${g}`);for(const m of j(a,ut(v))){const{id:M,__t__:T}=m;typeof T=="string"&&typeof M=="string"&&f.set(M,T)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:Je,onRead:C,rowToDocument:_e,schema:i,sql:a},U={system:un,async aggregate(e,t){const s=K(e,"aggregate");if(s)return C(e,H),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(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 $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,H);const h=fe(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),d=await Ce(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u){const S=Tn(f.aggregateIndexes,t.op,t.field,t.where);if(S){ze(e,S.index);const O=Xe(S.index.by??[],S.key),Q=Ye(e,S.index.name),V=j(a,c`SELECT ${We} AS value, ${tt} AS count FROM ${c.identifier(Q)} WHERE ${Be} = ${O}`).toArray()[0];return Ze(t.op,V)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const g=te(d,Se),v=qe(t.op),m=ce(t.field);let M=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;g&&(M=c`${M} WHERE ${g}`);const q=j(a,M).toArray()[0]?.value;return q??null},asId(e,t){const s=jt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=K(e,"count");if(s)return C(e,H),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Sn(t);if(h.restrictsCounts)throw new et(e);C(e,H);const l=fe(f.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),l),u=await Ce(d,e,h.relationBaseWhere),g=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!g){const T=Rn(f.aggregateIndexes,h.where);if(T){ze(e,T.index);const q=Xe(T.index.by??[],T.key),S=Ye(e,T.index.name),O=j(a,c`SELECT ${We} AS value FROM ${c.identifier(S)} WHERE ${Be} = ${q}`).toArray();return O[0]===void 0?0:O[0].value??0}}const v=te(u,Se);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(a,m).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const m=me(t);m&&(y(void 0),await m.delete(e,t,s));return}const{docJson:h,row:l,tableName:d}=f,u=i.tables[d],g=s?.hard===!0,v=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await er({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,M,T)=>(await Qe(m).findMany(m,{includeDeleted:g,where:{[M]:T}})).page,onCascade:(m,M)=>Qe(m).delete(M,void 0,s),onRestrict:m=>{throw new Te(m,"restrict")},onSetNull:(m,M,T)=>Qe(m).patch(M,{[T]:null}),schema:i,tableName:d}),pe(d),ye(d),v){const m={...l,...p(d),[v]:F(),_id:e};Ue(a,d,Ut(d),[le(m),e,h]),De(d,e,m,l),Me(d,e,void 0),be(d,l,m),$e(d,e,l,void 0),k?.invalidate(d,e,b(d,l,m)),ge(d,e,"update",m),w({indexKeys:b(d,l,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await I({id:e,op:"delete",table:d});return}Ue(a,d,Cr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,l,void 0),$e(d,e,l,void 0),k?.invalidate(d,e,b(d,l)),ge(d,e,"delete"),w({indexKeys:b(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await I({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??cn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await D(async()=>{for(;;){const u=(await U.findMany(e,{limit:s})).page.map(g=>String(g._id));if(u.length===0)break;for(const g of u)await U.delete(g,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){ue(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(K(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await U.findFirst(e,t);if(s===null)throw new Un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=K(e,"findMany");if(s)return C(e,H),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,H):C(e);const l=st(t.orderBy,f.shape,{pinned:Gn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,ct(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,fe(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:$t?hn:void 0,existsPushMode:yt==="always"?"always":"auto",fetcher:pt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const g=$t?jr(C):ht,v=te(u,g,Ne),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,M=rn(e,v,on(l),m===void 0?void 0:m+1),T=ve(a,M.text,...M.params).toArray();h&&!R&&A?.recordRead(T.length);const q=[];for(const V of T){const G=_e(V);G&&(q.push(G),!h&&typeof G._id=="string"&&C(e,G._id))}if(m===void 0)return t.with&&await qt({groupedCounter:Et,fetcher:Ve,parents:q,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(q,t.select,t.with)};const S=q.length>m,O=S?q.slice(0,m):q,Q=O.at(-1);return t.with&&await qt({fetcher:Ve,groupedCounter:Et,parents:O,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:S&&Q&&t.omitContinueCursor!==!0?He(Q,l):null,isDone:!S,page:bt(O,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=me(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=K(e,"groupBy");if(s)return C(e,H),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=fe(f.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),l),u=await Ce(d,e,t.relationBaseWhere),g=u!==d;if(f.aggregateIndexes&&!t.baseWhere&&!g){const S=_n(f.aggregateIndexes,h.op,h.field,t.by,t.where),O=S===void 0?0:Object.keys(S.partial).length,Q=S?.index.by?.length??0;if(S&&(O===0||O===Q)){ze(e,S.index);const V=Ye(e,S.index.name),G=Object.keys(S.partial),de=[];if(G.length===(S.index.by??[]).length&&G.length>0){const ke=Xe(S.index.by??[],S.partial),Fe=j(a,c`SELECT ${We} AS value, ${tt} AS count FROM ${c.identifier(V)} WHERE ${Be} = ${ke}`).toArray();return Fe.length>0&&de.push({key:{...S.partial},value:Ze(h.op,Fe[0])}),de}const pn=j(a,c`SELECT ${Be} AS key, ${We} AS value, ${tt} AS count FROM ${c.identifier(V)}`).toArray();for(const ke of pn){const Fe=mn(JSON.parse(ke.key));de.push({key:Fe,value:Ze(h.op,ke)})}return de}}for(const S of[...t.by,h.field]){if(S===void 0)continue;const O=S===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${S}" } })`:`groupBy(${e}, { by: [..."${S}"] })`;Nt(f,S,O)}const v=te(u,Se),m=t.by.map(S=>c`${ce(S)} AS ${c.identifier(S)}`);if(h.op==="count")m.push(c`COUNT(*) AS value`);else{const{field:S}=h;if(S===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);m.push(c`${c.raw(qe(h.op))}(${ce(S)}) AS value`)}let M=c`SELECT ${c.join(m,c`, `)} FROM ${c.identifier(e)}`;v&&(M=c`${M} WHERE ${v}`),M=c`${M} GROUP BY ${c.join(t.by.map(S=>ce(S)),c`, `)}`;const T=j(a,M).toArray(),q=[];for(const S of T){const O={};for(const V of t.by)O[V]=Dn(f.shape[V],S[V]??null);const{value:Q}=S;q.push({key:O,value:Q==null?null:Number(Q)})}return q},async insert(e,t,s){const f=K(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,oe);rt(h,l);let d;s?.clientId!==void 0?(Fr(s.clientId),d=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:F(),g={...l,...p(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...g},id:d,op:"insert",table:e}),pe(e),ye(e),dt(a,e,Ar(e),[d,u,le(g)]),_t(e,d,g),Z(e,"after","insert")&&await ee("after","insert",{doc:g,id:d,op:"insert",table:e}),await I({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,s){if(ue(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=K(e,"insert");if(f){const u=[];for(const g of t)y(g);for(const g of t){const v=await f.insert(e,g,{allowExplicitId:s?.allowExplicitId});w({key:v,op:"insert",row:{...g,_id:v},table:e}),u.push(v)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ye(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(p(e));const d=t.map((u,g)=>{const v=Kt(h,u,oe),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:X(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:F(),T={...v,...l[Math.floor(g/Pe)],_creationTime:M,_id:m};return{creationTime:M,document:T,id:m}});for(const u of d)y(u.document);for(let u=0;u<d.length;u+=Pe){const g=c.join(d.slice(u,u+Pe).map(m=>c`(${m.id}, ${m.creationTime}, ${le(m.document)})`),c`, `),v=Zt("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(re)}) VALUES ${g}`);dt(a,e,v.sql,v.params)}for(const{document:u,id:g}of d)_t(e,g,u),await Y({doc:u,id:g,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,s){ue(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=K(e,"insert");if(l)for(const u of t)y(u);const d=async u=>l?gt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(g){if(f&&g instanceof Te&&g.kind==="unique")h.push(null);else throw g}return h},normalizeId(e,t){return jt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const v=me(s);if(v){y(t),await v.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=i.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(C(d,e),Vt("patch",t),fn(d,e,t,l)){r?.({fields:Object.keys(it(t)),id:e,table:d});return}const g={...l,...it(t),...p(d),_id:e};Qt(u,t,g,oe),rt(u,g,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:l,table:d}),pe(d),ye(d),Ue(a,d,Ut(d),[le(g),e,h]),De(d,e,g,l),Me(d,e,g),be(d,l,g),$e(d,e,l,g),k?.invalidate(d,e,b(d,l,g)),ge(d,e,"update",g),w({indexKeys:b(d,l,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:l,table:d}),await I({doc:g,id:e,op:"update",table:d})},async patchMany(e,t,s){ue(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(K(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},async related(e,t){return Zn(U,_,e,t)},relationEdges:_,query(e){const t=K(e,"query");return t?(C(e,H),t.query(e)):ln(a,i,e,ne,s=>{s?P(s):C(e,H)},s=>{R||A?.recordRead(s)})},async rank(e,t,s){const f=K(e,"rank");if(f)return C(e,H),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),s.restrictsCounts)throw new et(e);C(e,H),Je(e,l);const d=typeof s.row=="string"?s.row:s.row._id;if(!d)return null;const u=Mt(e,l.name),g=l.sortBy.map((G,de)=>Dt(de)),v=g.map(G=>Ae(G)).join(", "),m=j(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[M]=m;if(M===void 0)return null;let T=M.__partition__;const q=N(s.baseWhere,s.where);nt(q,i,e,"rank");const S=Nn(l,q);if(S){const G=jn(l.partitionBy??[],S);if(G!==T)return null;T=G}const O=g.map(G=>M[G]),{before:Q,total:V}=Jt(a,u,g,l.sortBy,T,O,d);return{position:Q+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(g=>g.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new et(e);C(e,H),Je(e,h);const l=Mt(e,h.name),d=h.sortBy.map((g,v)=>Dt(v)),u=h.sortBy.map((g,v)=>ae(s.sortValues[v]??null));return Jt(a,l,d,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){nt(N(s.baseWhere,s.where),i,e,"rankPage");const f=K(e,"rankPage");if(f)return C(e,H),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,s);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,s={}){nt(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=me(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&$e(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const q=me(s);if(q){y(t),await q.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,g=i.tables[u];if(!g)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof d._creationTime=="number"?d._creationTime:void 0,M=v??m??F(),T={...t,...p(u),_creationTime:M,_id:e};Qt(g,t,T,oe),rt(g,T),Z(u,"before","update")&&await ee("before","update",{doc:{...T},id:e,op:"update",previous:d,table:u}),pe(u),ye(u),Ue(a,u,Ir(u),[M,le(T),e,l]),De(u,e,T,d),Me(u,e,T),be(u,d,T),$e(u,e,d,T),k?.invalidate(u,e,b(u,d,T)),ge(u,e,"update",T),w({indexKeys:b(u,d,T),key:e,op:"update",row:T,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:T,id:e,op:"update",previous:d,table:u}),await I({doc:T,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,g])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const g=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=g.deleted,l+=g.deleted}return{deleted:l,tables:h}}},gn={db:U,scheduler:we};return n.enforceRls===!0?nr(U,i,(e,t)=>se(e,t)?.tableName,(e,t)=>wn(e,t),_):U};export{No as CDC_LOG_TABLE,fi as IDEMPOTENCY_TABLE,Kr as NotUniqueError,ai as advanceClientWatermark,jo as applyCdcChanges,Vt as assertNoExplicitUndefined,Fr as assertValidClientId,Uo as backfillAggregateIndexes,Oo as backfillRankIndexes,Ho as backfillSearchIndexes,Ko as bumpCdcEpoch,Qo as cdcCanVouchFor,Vo as cdcForkedError,zo as cdcSeqLeavingRows,Jo as cdcTouchesTables,Yo as cdcTrimmedError,Xo as compactCdcDocs,Wo as createShardCtxDb,Zo as cursorBelowRetainedFloor,di as migrateClientWatermark,ei as minCdcReplayableSeq,ti as minCdcSeq,jt as normalizeIdStructurally,ni as readCdcChangeKeys,ri as readCdcChanges,oi as readCdcCursor,ii as readCdcEpoch,li as readClientWatermark,hi as readIdempotent,yi as runShardMigrations,mi as selectShapeMembers,Ei as selectShapeRows,it as stripReservedPatchFields,si as trimCdcChanges,wi as trimIdempotent,gi as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};