@lunora/shard-engine 1.0.0-alpha.171 → 1.0.0-alpha.173

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.
Files changed (24) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/dist/packem_shared/{ADMIN_FUNCTIONS-Dsiw5qoT.mjs → ADMIN_FUNCTIONS-BVfaxaPu.mjs} +1 -1
  4. package/dist/packem_shared/{AGG_COUNT-Ctb5Pnyl.mjs → AGG_COUNT-BkqKHbcG.mjs} +1 -1
  5. package/dist/packem_shared/{CDC_LOG_TABLE-oPp25hdi.mjs → CDC_LOG_TABLE-CTkXVeJx.mjs} +1 -1
  6. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs → DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs} +1 -1
  7. package/dist/packem_shared/{NotUniqueError-Cgu71D66.mjs → NotUniqueError-BprK42pn.mjs} +1 -1
  8. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-DntvQ2eS.mjs → VECTOR_BACKFILL_MAX_PAGES-UY0toTIR.mjs} +1 -1
  9. package/dist/packem_shared/{applyInsertDefaults-B0NXPs2x.mjs → applyInsertDefaults-BJo578fn.mjs} +1 -1
  10. package/dist/packem_shared/{backfillAggregateIndexes-CSROhPJq.mjs → backfillAggregateIndexes-CRNxxM19.mjs} +1 -1
  11. package/dist/packem_shared/{buildReprojectionMigration-Ds2JaFo7.mjs → buildReprojectionMigration-DAh1inpL.mjs} +1 -1
  12. package/dist/packem_shared/{buildShapeDiff-BfTX-roE.mjs → buildShapeDiff-CCpH5fNc.mjs} +1 -1
  13. package/dist/packem_shared/{createCompanionSync-_zfDTDoO.mjs → createCompanionSync-qhvw6wyL.mjs} +1 -1
  14. package/dist/packem_shared/{createReplicaLink-CbXW6X7p.mjs → createReplicaLink-D0YNQDzD.mjs} +1 -1
  15. package/dist/packem_shared/{defineEngineContractSuite-DB_czsoy.mjs → defineEngineContractSuite-DTJ60C7D.mjs} +1 -1
  16. package/dist/packem_shared/do-sql-RROYQPCM.mjs +1 -0
  17. package/dist/packem_shared/{isSoftDeleted-BYZ0sPyu.mjs → isSoftDeleted-QCy5JKnY.mjs} +1 -1
  18. package/dist/packem_shared/{isTtlExpired-CozZXOL3.mjs → isTtlExpired-BmiUp7MF.mjs} +1 -1
  19. package/dist/packem_shared/{materializeExternalRows-DzUChRJ-.mjs → materializeExternalRows-BakYlgvb.mjs} +1 -1
  20. package/dist/packem_shared/runShardMigrations-_KucUTa2.mjs +5 -0
  21. package/dist/packem_shared/{selectShapeMembers-BCfKypfN.mjs → selectShapeMembers-BhK79123.mjs} +1 -1
  22. package/package.json +3 -3
  23. package/dist/packem_shared/do-sql-BWrJQAOh.mjs +0 -1
  24. package/dist/packem_shared/runShardMigrations-DMDT1blz.mjs +0 -5
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DB_czsoy.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DTJ60C7D.mjs";export{t as defineEngineContractSuite};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-2xl7lIcj.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-Cgu71D66.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-CSROhPJq.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-oPp25hdi.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-_zfDTDoO.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as xr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as xo,readStreamRun as Eo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DzUChRJ-.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-BYZ0sPyu.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as xa,findStorageReferences as Ea,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-Dsiw5qoT.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as xt,rankPivotConditionSql as Et,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-Cy7oH_7w.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as xi,nextPromotionState as Ei,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CbXW6X7p.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-BfTX-roE.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ds}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as ms}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ss,assertReadonly as us,lintReadonlySql as fs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as hs,bigintSqlKey as Ts,decodeBigintSqlKey as Rs,decodeFloat64SqlKey as As,float64SqlKey as Cs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as _s,subscriptionFrames as Is,subscriptionListDeltas as bs,trySendFrame as Ls}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ps,recordChangedKeys as Os,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Fs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ks}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Us,TransactionHeadroomTracker as Gs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as qs,runTriggers as vs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as Ws,nextTtlExpiry as Xs,selectExpiredIds as Hs}from"./packem_shared/isTtlExpired-CozZXOL3.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DntvQ2eS.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as rl,siblingSecretOf as ol,signSiblingBody as al,verifySiblingBody as tl}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as sl,reprojectionMigrationId as ll}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as dl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as ml}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Sl}from"./packem_shared/runShardMigrations-DMDT1blz.mjs";import{stableStringify as fl,stableWireKey as xl}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,hs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ks as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,Us as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,Ss as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,$s as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,rl as RELAY_SIGNATURE_HEADER,sl as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Gs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,us as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,_s as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,Ts as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,xi as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,js as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Fs as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,Rs as decodeBigintSqlKey,ja as decodeCursor,As as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,E as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,xa as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,Ea as findStorageReferences,uo as finishStreamRun,Cs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,qs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,dl as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,Ws as isTtlExpired,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,fs as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Ps as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,Ei as nextPromotionState,Xs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,ml as quoteIdentifier,xt as rankKeyFromDoc,Et as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,xo as readStreamChunks,Eo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Os as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,ll as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,xs as runReadonlySql,Si as runRowValidators,Sl as runShardMigrations,ms as runSocketPool,qr as runSql,vs as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,Js as serverInList,Ti as shapeRoutingKey,ol as siblingSecretOf,al as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,fl as stableStringify,xl as stableWireKey,w as stripReservedPatchFields,ds as stubByName,Is as subscriptionFrames,bs as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ls as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,tl as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,xr as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,Ms as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-2xl7lIcj.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-BprK42pn.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-CRNxxM19.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-CTkXVeJx.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-qhvw6wyL.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as xr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BhK79123.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-RROYQPCM.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as xo,readStreamRun as Eo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-BakYlgvb.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-QCy5JKnY.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as xa,findStorageReferences as Ea,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-BVfaxaPu.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as xt,rankPivotConditionSql as Et,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-Cy7oH_7w.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-BJo578fn.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as xi,nextPromotionState as Ei,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-D0YNQDzD.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-DAh1inpL.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-CCpH5fNc.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ds}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as ms}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ss,assertReadonly as us,lintReadonlySql as fs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as hs,bigintSqlKey as Ts,decodeBigintSqlKey as Rs,decodeFloat64SqlKey as As,float64SqlKey as Cs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as _s,subscriptionFrames as Is,subscriptionListDeltas as bs,trySendFrame as Ls}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ps,recordChangedKeys as Os,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Fs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ks}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Us,TransactionHeadroomTracker as Gs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as qs,runTriggers as vs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as Ws,nextTtlExpiry as Xs,selectExpiredIds as Hs}from"./packem_shared/isTtlExpired-BmiUp7MF.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-UY0toTIR.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as rl,siblingSecretOf as ol,signSiblingBody as al,verifySiblingBody as tl}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as sl,reprojectionMigrationId as ll}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as dl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as ml}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Sl}from"./packem_shared/runShardMigrations-_KucUTa2.mjs";import{stableStringify as fl,stableWireKey as xl}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,hs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ks as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,Us as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,Ss as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,$s as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,rl as RELAY_SIGNATURE_HEADER,sl as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Gs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,us as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,_s as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,Ts as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,xi as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,js as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Fs as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,Rs as decodeBigintSqlKey,ja as decodeCursor,As as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,E as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,xa as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,Ea as findStorageReferences,uo as finishStreamRun,Cs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,qs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,dl as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,Ws as isTtlExpired,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,fs as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Ps as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,Ei as nextPromotionState,Xs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,ml as quoteIdentifier,xt as rankKeyFromDoc,Et as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,xo as readStreamChunks,Eo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Os as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,ll as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,xs as runReadonlySql,Si as runRowValidators,Sl as runShardMigrations,ms as runSocketPool,qr as runSql,vs as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,Js as serverInList,Ti as shapeRoutingKey,ol as siblingSecretOf,al as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,fl as stableStringify,xl as stableWireKey,w as stripReservedPatchFields,ds as stubByName,Is as subscriptionFrames,bs as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ls as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,tl as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,xr as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,Ms as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as d}from"@lunora/errors";import{decodeWire as Q,WIRE_TAG as R,needsWireEncoding as X,encodeWire as G}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as w}from"./isInternalTableName-BoljO2tP.mjs";import{n as T,o as V}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as J,sqliteInList as Y}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const je="__lunora_admin__:",Le="__lunora_relation__:",Fe="__lunora_flags__:",xe={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},Z=50,y=500,ee=30,te=200,l="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},ne=e=>{const{[T]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[T]:t,...n}:{...n,...Q(t)}},re=(e,t)=>{if(!e.includes(l))return{columns:e,rows:t};const n=[];for(const a of t){const i=a[l],_=typeof i=="string"?x(i):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(a).filter(([m])=>m!==l));n.push({...c,...ne(_)})}const r=e.filter(a=>a!==l),o=[],s=new Set(r);for(const a of n)for(const i of Object.keys(a))s.has(i)||(s.add(i),o.push(i));return{columns:[...r,...o],rows:n}},S=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),U=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},Ue=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)w(r)||n.push({name:r,rowCount:U(e,u(r))});return n},q=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,M=(e,t)=>{if(w(t)||!q(e,t))throw new d("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},A=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},F=100,D=(e,t)=>{if(t>F)throw new d("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(F)} — remove some filters or narrow the search`)},P=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",oe=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?P(e.value)==="":oe.has(e.operator)&&e.value==="",W=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new d("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},b=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(l);if(!(!r&&!o)){if(r){if(n.length>0)throw new d("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:u(e),params:[]}}return{expression:`json_extract(${u(l)}, ?)`,params:[W(e,n)]}}},ae=/^-?\d+$/u,v=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ae.test(r))throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},ie=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,_e=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new d("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},ce=(e,t,n)=>{if(t.includes(e.column))throw new d("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(l))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new d("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=_e(e.value),s=W(e.column,r),a=u(l),i=`SELECT 1 FROM json_each(${a}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${s}[0]`,s,...o.params,`${s}[1]`,`${s}[2]`,...o.params],sql:`CASE WHEN json_extract(${a}, ?) IS NOT '${R}' THEN EXISTS (${i}) WHEN json_extract(${a}, ?) IS 'arr' THEN EXISTS (${i}) ELSE 0 END`}},le=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return X(e)?JSON.stringify(G(e)):void 0}catch(t){throw new d("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",de=(e,t,n)=>{const r=le(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new d("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let s="'integer', 'real'";return typeof e.value=="string"?s="'text'":typeof e.value=="boolean"&&(s="'true', 'false'"),{params:[...n,...n,v(e,void 0)],sql:`(json_type(${u(l)}, ?) IN (${s}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const s=`json_type(${u(l)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,a=v(e,void 0);return o==="eq"?{params:[...n,...n,a],sql:`(${s})`}:{params:[...n,...n,...n,a],sql:`(${t} IS NOT NULL AND NOT (${s}))`}}},H=e=>{const t=`json_tree(${e})`;return`NOT (typeof(j.key) = 'integer' AND j.key IN (0, 1) AND EXISTS (SELECT 1 FROM ${t} AS f WHERE f.parent = j.parent AND f.key = 0 AND f.type = 'text' AND f.atom = '${R}') AND (WITH RECURSIVE links(node, k) AS (SELECT j.parent, 0 UNION ALL SELECT c.parent, links.k + 1 FROM links JOIN ${t} AS c ON c.id = links.node WHERE typeof(c.key) = 'integer' AND c.key = 2 AND ${((r,o)=>`(SELECT count(*) FROM ${t} AS ${r} WHERE ${r}.parent = ${o} AND typeof(${r}.key) = 'integer' AND ((${r}.key = 0 AND ${r}.atom = '${R}') OR (${r}.key = 1 AND ${r}.atom = 'arr'))) = 2`)("h","c.parent")}) SELECT max(k) FROM links) % 2 = 0)`},me=(e,t,n)=>({params:[t,t,n,t,t,n,t,t,n,t,t,t],sql:`CASE WHEN json_type(${e}, ?) IN ('text', 'integer', 'real') THEN ${S(`json_extract(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('true', 'false') THEN ${S(`json_type(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('array', 'object') THEN EXISTS (SELECT 1 FROM json_tree(${e}, ?) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${H(`${e}, ?`)}) ELSE 0 END`}),fe=(e,{expression:t,kind:n,pathParameters:r,physical:o})=>{const s=e.path??[];if(n==="bigint")throw new d("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const a=P(e.value);return s.length===0&&o?{params:[a],sql:S(t)}:s.length===0?me(u(l),r[0],a):{params:[...r,...r,a],sql:`(json_type(${u(l)}, ?) IN ('text', 'integer', 'real') AND ${S(t)})`}},pe=(e,t,n)=>{if(e.operator==="has")return ce(e,t,n);const r=e.path??[],o=b(e.column,t,r);if(o===void 0||se(e))return;const{expression:s,params:a}=o,i=t.includes(e.column)||r.length>0?void 0:n?.[e.column];if(e.operator==="contains")return fe(e,{expression:s,kind:i,pathParameters:a,physical:t.includes(e.column)});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(r.length>0){const _=de(e,s,a);if(_!==void 0)return _}return{params:[...a,v(e,i)],sql:`${s} ${I[e.operator]} ?`}},ge=new Set(["date","timestamp"]),Ee=[`$.${T}`,`$."${T}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Se=e=>`(${S(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${Ee} AND ${H(e)}))`,he=/["\\\u0000-\u001F]/u,ye=e=>he.test(e)?"":e,be=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,Ne=e=>{const t=be.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const s=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(s).getUTCDate()!==o)return;let a;return o!==void 0?a=Date.UTC(n,(r??1)-1,o+1):r===void 0?a=Date.UTC(n+1,0,1):a=Date.UTC(n,r,1),{from:s,to:a}},O=(e,t,n,r)=>{const o=[],s=[];if(t!==""&&e.length>0){const a=e.map(_=>_===l?Se(u(_)):S(u(_)));s.push(...e.flatMap(_=>_===l?[ye(t),t]:[t]));const i=Ne(t);if(i!==void 0){for(const c of e)a.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),s.push(i.from,i.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ge.has(r?.[c]??""));_.length>0&&e.includes(l)&&(a.push(`EXISTS (SELECT 1 FROM json_each(${u(l)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),s.push(JSON.stringify(_),i.from,i.to))}o.push(`(${a.join(" OR ")})`)}for(const a of n??[]){const i=pe(a,e,r);i!==void 0&&(o.push(`(${i.sql})`),s.push(...i.params))}return o.length===0?void 0:{parameters:s,where:o.join(" AND ")}},Te=(e,t)=>{if(e===void 0)return;const n=b(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},qe=(e,t)=>{const{table:n}=t;M(e,n);const r=C(Math.trunc(t.limit??Z),1,y),o=Math.max(0,Math.trunc(t.offset??0)),s=u(n),a=A(e,s),i=t.search?.trim()??"",_=N=>{if(t.refs===void 0)return N;const $={};for(const k of N.columns){const j=t.refs[k];j!==void 0&&($[k]=j)}return Object.keys($).length>0?{...N,refs:$}:N},c=O(a,i,t.filters,t.columnKinds),m=Te(t.orderBy,a),p=c===void 0?"":` WHERE ${c.where}`,E=m===void 0?"":` ORDER BY ${m.sql}`,g=c?.parameters??[],h=m?.params??[];D(n,g.length+h.length+2);let f;t.skipCount||(f=c===void 0?U(e,s):Number(e.exec(`SELECT COUNT(*) AS c FROM ${s}${p}`,...g).one().c));const B=e.exec(`SELECT * FROM ${s}${p}${E} LIMIT ? OFFSET ?`,...g,...h,r,o).toArray();return _({...re(a,B),sqlColumns:a,total:f})},Pe=(e,t)=>{const{table:n}=t;M(e,n);const r=C(Math.trunc(t.limit??y),1,y),o=u(n),s=A(e,o),a=t.search?.trim()??"";for(const f of t.filters??[])if(b(f.column,s,f.path??[])===void 0)throw new d("BAD_REQUEST",`unknown column: ${f.column}`);const i=O(s,a,t.filters,t.columnKinds);if(i===void 0&&(t.filters?.length??0)>0)throw new d("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];i!==void 0&&(_.push(i.where),c.push(...i.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const m=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";D(n,c.length+1);const E=e.exec(`SELECT id FROM ${o}${m}${p} LIMIT ?`,...c,r+1).toArray(),g=E.length>r,h=E.slice(0,r).map(f=>f.id);return{hasMore:g,ids:h}},Ae=(e,t,n,r)=>{const o=new Set(n.filter(a=>a!==l));if(!n.includes(l))return o;for(const a of Object.keys(r??{}))o.add(a);const s=e.exec(`SELECT ${u(l)} AS doc FROM ${t} LIMIT ?`,y).toArray();for(const{doc:a}of s){const i=typeof a=="string"?x(a):void 0;if(i!==void 0)for(const _ of Object.keys(i))o.add(_)}return o},We=(e,t)=>{const{column:n,table:r}=t;M(e,r);const o=u(r),s=A(e,o);if(!Ae(e,o,s,t.columnKinds).has(n))throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=b(n,s);if(a===void 0)throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=C(Math.trunc(t.limit??ee),1,te),_=t.search?.trim()??"",c=O(s,_,t.filters,t.columnKinds),m=c===void 0?"":` WHERE ${c.where}`,p=c?.parameters??[];D(r,a.params.length*2+p.length+1);const E=e.exec(`SELECT ${a.expression} AS value, COUNT(*) AS count FROM ${o}${m} GROUP BY ${a.expression} ORDER BY count DESC LIMIT ?`,...a.params,...p,...a.params,i+1).toArray(),g=E.length>i,h=s.includes(n)?void 0:t.columnKinds?.[n];return{truncated:g,values:E.slice(0,i).map(f=>({count:Number(f.count),value:ie(f.value,h)}))}},He=(e,t,n)=>{const r={},o=n.slice(0,y);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[s,a]of Object.entries(t)){if(w(s)||!q(e,s))continue;const i=u(s),_=A(e,i);for(const c of a){const m=b(c,_);if(m===void 0)continue;const p=J("sqlite",Y(K.raw(m.expression),o,!1)),E=e.exec(`SELECT id, ${m.expression} AS ref FROM ${i} WHERE ${p.sql}`,...m.params,...m.params,...p.params).toArray();for(const g of E)r[g.ref]?.push({column:c,id:g.id,table:s})}}return{references:r,storageColumns:t}},Be=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,s)=>{const a=Object.values(o.subs??{}).map(i=>({args:i.args,functionPath:i.functionPath,table:i.table}));return{admin:o.admin===!0,id:s,subscriptions:a}}),r=n.reduce((o,s)=>o+s.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},$e=20,Qe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ge=()=>({drains:0,pairsSkipped:0}),Ke=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ve=(e,t,n)=>({run:e.run+t,served:e.served+n}),Je=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Ye=(e,t=$e)=>{const n=new Map,r=new Map,o=e.filter(i=>i.authenticated!==!1);for(const i of o){for(const _ of Object.values(i.shapes??{})){const c=_.name??"(unknown shape)";n.set(c,(n.get(c)??0)+1)}for(const _ of i.whispers??[])r.set(_,(r.get(_)??0)+1)}const s=[...[...n].map(([i,_])=>({kind:"shape",subscribers:_,topic:i})),...[...r].map(([i,_])=>({kind:"whisper",subscribers:_,topic:i}))];return s.sort((i,_)=>_.subscribers-i.subscribers||i.topic.localeCompare(_.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:o.length}};export{xe as ADMIN_FUNCTIONS,je as ADMIN_FUNCTION_PREFIX,$e as DEFAULT_FANOUT_TOPIC_LIMIT,Fe as FLAGS_FUNCTION_PREFIX,y as MAX_PAGE_SIZE,Le as RELATION_FUNCTION_PREFIX,Qe as createFanoutCounters,Ge as createGlobalPollCounters,Xe as createShapeProbeCounters,Ne as datePrefixRange,We as facetColumn,He as findStorageReferences,w as isInternalTableName,se as isVacuousFilterClause,Ue as listTables,qe as readTablePage,Je as recordFanoutPass,Ke as recordGlobalPollPass,Ve as recordShapeProbePass,Pe as selectMatchingIds,Ye as summarizeFanoutTopics,Be as summarizeSubscriptions};
1
+ import{LunoraError as d}from"@lunora/errors";import{decodeWire as Q,WIRE_TAG as R,needsWireEncoding as X,encodeWire as G}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as w}from"./isInternalTableName-BoljO2tP.mjs";import{n as T,o as V}from"./do-sql-RROYQPCM.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as J,sqliteInList as Y}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const je="__lunora_admin__:",Le="__lunora_relation__:",Fe="__lunora_flags__:",xe={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},Z=50,y=500,ee=30,te=200,l="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},ne=e=>{const{[T]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[T]:t,...n}:{...n,...Q(t)}},re=(e,t)=>{if(!e.includes(l))return{columns:e,rows:t};const n=[];for(const a of t){const i=a[l],_=typeof i=="string"?x(i):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(a).filter(([m])=>m!==l));n.push({...c,...ne(_)})}const r=e.filter(a=>a!==l),o=[],s=new Set(r);for(const a of n)for(const i of Object.keys(a))s.has(i)||(s.add(i),o.push(i));return{columns:[...r,...o],rows:n}},S=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),U=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},Ue=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)w(r)||n.push({name:r,rowCount:U(e,u(r))});return n},q=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,M=(e,t)=>{if(w(t)||!q(e,t))throw new d("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},A=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},F=100,D=(e,t)=>{if(t>F)throw new d("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(F)} — remove some filters or narrow the search`)},P=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",oe=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?P(e.value)==="":oe.has(e.operator)&&e.value==="",W=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new d("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},b=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(l);if(!(!r&&!o)){if(r){if(n.length>0)throw new d("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:u(e),params:[]}}return{expression:`json_extract(${u(l)}, ?)`,params:[W(e,n)]}}},ae=/^-?\d+$/u,v=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ae.test(r))throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},ie=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,_e=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new d("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},ce=(e,t,n)=>{if(t.includes(e.column))throw new d("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(l))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new d("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=_e(e.value),s=W(e.column,r),a=u(l),i=`SELECT 1 FROM json_each(${a}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${s}[0]`,s,...o.params,`${s}[1]`,`${s}[2]`,...o.params],sql:`CASE WHEN json_extract(${a}, ?) IS NOT '${R}' THEN EXISTS (${i}) WHEN json_extract(${a}, ?) IS 'arr' THEN EXISTS (${i}) ELSE 0 END`}},le=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return X(e)?JSON.stringify(G(e)):void 0}catch(t){throw new d("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",de=(e,t,n)=>{const r=le(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new d("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let s="'integer', 'real'";return typeof e.value=="string"?s="'text'":typeof e.value=="boolean"&&(s="'true', 'false'"),{params:[...n,...n,v(e,void 0)],sql:`(json_type(${u(l)}, ?) IN (${s}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const s=`json_type(${u(l)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,a=v(e,void 0);return o==="eq"?{params:[...n,...n,a],sql:`(${s})`}:{params:[...n,...n,...n,a],sql:`(${t} IS NOT NULL AND NOT (${s}))`}}},H=e=>{const t=`json_tree(${e})`;return`NOT (typeof(j.key) = 'integer' AND j.key IN (0, 1) AND EXISTS (SELECT 1 FROM ${t} AS f WHERE f.parent = j.parent AND f.key = 0 AND f.type = 'text' AND f.atom = '${R}') AND (WITH RECURSIVE links(node, k) AS (SELECT j.parent, 0 UNION ALL SELECT c.parent, links.k + 1 FROM links JOIN ${t} AS c ON c.id = links.node WHERE typeof(c.key) = 'integer' AND c.key = 2 AND ${((r,o)=>`(SELECT count(*) FROM ${t} AS ${r} WHERE ${r}.parent = ${o} AND typeof(${r}.key) = 'integer' AND ((${r}.key = 0 AND ${r}.atom = '${R}') OR (${r}.key = 1 AND ${r}.atom = 'arr'))) = 2`)("h","c.parent")}) SELECT max(k) FROM links) % 2 = 0)`},me=(e,t,n)=>({params:[t,t,n,t,t,n,t,t,n,t,t,t],sql:`CASE WHEN json_type(${e}, ?) IN ('text', 'integer', 'real') THEN ${S(`json_extract(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('true', 'false') THEN ${S(`json_type(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('array', 'object') THEN EXISTS (SELECT 1 FROM json_tree(${e}, ?) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${H(`${e}, ?`)}) ELSE 0 END`}),fe=(e,{expression:t,kind:n,pathParameters:r,physical:o})=>{const s=e.path??[];if(n==="bigint")throw new d("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const a=P(e.value);return s.length===0&&o?{params:[a],sql:S(t)}:s.length===0?me(u(l),r[0],a):{params:[...r,...r,a],sql:`(json_type(${u(l)}, ?) IN ('text', 'integer', 'real') AND ${S(t)})`}},pe=(e,t,n)=>{if(e.operator==="has")return ce(e,t,n);const r=e.path??[],o=b(e.column,t,r);if(o===void 0||se(e))return;const{expression:s,params:a}=o,i=t.includes(e.column)||r.length>0?void 0:n?.[e.column];if(e.operator==="contains")return fe(e,{expression:s,kind:i,pathParameters:a,physical:t.includes(e.column)});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(r.length>0){const _=de(e,s,a);if(_!==void 0)return _}return{params:[...a,v(e,i)],sql:`${s} ${I[e.operator]} ?`}},ge=new Set(["date","timestamp"]),Ee=[`$.${T}`,`$."${T}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Se=e=>`(${S(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${Ee} AND ${H(e)}))`,he=/["\\\u0000-\u001F]/u,ye=e=>he.test(e)?"":e,be=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,Ne=e=>{const t=be.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const s=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(s).getUTCDate()!==o)return;let a;return o!==void 0?a=Date.UTC(n,(r??1)-1,o+1):r===void 0?a=Date.UTC(n+1,0,1):a=Date.UTC(n,r,1),{from:s,to:a}},O=(e,t,n,r)=>{const o=[],s=[];if(t!==""&&e.length>0){const a=e.map(_=>_===l?Se(u(_)):S(u(_)));s.push(...e.flatMap(_=>_===l?[ye(t),t]:[t]));const i=Ne(t);if(i!==void 0){for(const c of e)a.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),s.push(i.from,i.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ge.has(r?.[c]??""));_.length>0&&e.includes(l)&&(a.push(`EXISTS (SELECT 1 FROM json_each(${u(l)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),s.push(JSON.stringify(_),i.from,i.to))}o.push(`(${a.join(" OR ")})`)}for(const a of n??[]){const i=pe(a,e,r);i!==void 0&&(o.push(`(${i.sql})`),s.push(...i.params))}return o.length===0?void 0:{parameters:s,where:o.join(" AND ")}},Te=(e,t)=>{if(e===void 0)return;const n=b(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},qe=(e,t)=>{const{table:n}=t;M(e,n);const r=C(Math.trunc(t.limit??Z),1,y),o=Math.max(0,Math.trunc(t.offset??0)),s=u(n),a=A(e,s),i=t.search?.trim()??"",_=N=>{if(t.refs===void 0)return N;const $={};for(const k of N.columns){const j=t.refs[k];j!==void 0&&($[k]=j)}return Object.keys($).length>0?{...N,refs:$}:N},c=O(a,i,t.filters,t.columnKinds),m=Te(t.orderBy,a),p=c===void 0?"":` WHERE ${c.where}`,E=m===void 0?"":` ORDER BY ${m.sql}`,g=c?.parameters??[],h=m?.params??[];D(n,g.length+h.length+2);let f;t.skipCount||(f=c===void 0?U(e,s):Number(e.exec(`SELECT COUNT(*) AS c FROM ${s}${p}`,...g).one().c));const B=e.exec(`SELECT * FROM ${s}${p}${E} LIMIT ? OFFSET ?`,...g,...h,r,o).toArray();return _({...re(a,B),sqlColumns:a,total:f})},Pe=(e,t)=>{const{table:n}=t;M(e,n);const r=C(Math.trunc(t.limit??y),1,y),o=u(n),s=A(e,o),a=t.search?.trim()??"";for(const f of t.filters??[])if(b(f.column,s,f.path??[])===void 0)throw new d("BAD_REQUEST",`unknown column: ${f.column}`);const i=O(s,a,t.filters,t.columnKinds);if(i===void 0&&(t.filters?.length??0)>0)throw new d("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];i!==void 0&&(_.push(i.where),c.push(...i.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const m=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";D(n,c.length+1);const E=e.exec(`SELECT id FROM ${o}${m}${p} LIMIT ?`,...c,r+1).toArray(),g=E.length>r,h=E.slice(0,r).map(f=>f.id);return{hasMore:g,ids:h}},Ae=(e,t,n,r)=>{const o=new Set(n.filter(a=>a!==l));if(!n.includes(l))return o;for(const a of Object.keys(r??{}))o.add(a);const s=e.exec(`SELECT ${u(l)} AS doc FROM ${t} LIMIT ?`,y).toArray();for(const{doc:a}of s){const i=typeof a=="string"?x(a):void 0;if(i!==void 0)for(const _ of Object.keys(i))o.add(_)}return o},We=(e,t)=>{const{column:n,table:r}=t;M(e,r);const o=u(r),s=A(e,o);if(!Ae(e,o,s,t.columnKinds).has(n))throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=b(n,s);if(a===void 0)throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=C(Math.trunc(t.limit??ee),1,te),_=t.search?.trim()??"",c=O(s,_,t.filters,t.columnKinds),m=c===void 0?"":` WHERE ${c.where}`,p=c?.parameters??[];D(r,a.params.length*2+p.length+1);const E=e.exec(`SELECT ${a.expression} AS value, COUNT(*) AS count FROM ${o}${m} GROUP BY ${a.expression} ORDER BY count DESC LIMIT ?`,...a.params,...p,...a.params,i+1).toArray(),g=E.length>i,h=s.includes(n)?void 0:t.columnKinds?.[n];return{truncated:g,values:E.slice(0,i).map(f=>({count:Number(f.count),value:ie(f.value,h)}))}},He=(e,t,n)=>{const r={},o=n.slice(0,y);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[s,a]of Object.entries(t)){if(w(s)||!q(e,s))continue;const i=u(s),_=A(e,i);for(const c of a){const m=b(c,_);if(m===void 0)continue;const p=J("sqlite",Y(K.raw(m.expression),o,!1)),E=e.exec(`SELECT id, ${m.expression} AS ref FROM ${i} WHERE ${p.sql}`,...m.params,...m.params,...p.params).toArray();for(const g of E)r[g.ref]?.push({column:c,id:g.id,table:s})}}return{references:r,storageColumns:t}},Be=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,s)=>{const a=Object.values(o.subs??{}).map(i=>({args:i.args,functionPath:i.functionPath,table:i.table}));return{admin:o.admin===!0,id:s,subscriptions:a}}),r=n.reduce((o,s)=>o+s.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},$e=20,Qe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ge=()=>({drains:0,pairsSkipped:0}),Ke=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ve=(e,t,n)=>({run:e.run+t,served:e.served+n}),Je=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Ye=(e,t=$e)=>{const n=new Map,r=new Map,o=e.filter(i=>i.authenticated!==!1);for(const i of o){for(const _ of Object.values(i.shapes??{})){const c=_.name??"(unknown shape)";n.set(c,(n.get(c)??0)+1)}for(const _ of i.whispers??[])r.set(_,(r.get(_)??0)+1)}const s=[...[...n].map(([i,_])=>({kind:"shape",subscribers:_,topic:i})),...[...r].map(([i,_])=>({kind:"whisper",subscribers:_,topic:i}))];return s.sort((i,_)=>_.subscribers-i.subscribers||i.topic.localeCompare(_.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:o.length}};export{xe as ADMIN_FUNCTIONS,je as ADMIN_FUNCTION_PREFIX,$e as DEFAULT_FANOUT_TOPIC_LIMIT,Fe as FLAGS_FUNCTION_PREFIX,y as MAX_PAGE_SIZE,Le as RELATION_FUNCTION_PREFIX,Qe as createFanoutCounters,Ge as createGlobalPollCounters,Xe as createShapeProbeCounters,Ne as datePrefixRange,We as facetColumn,He as findStorageReferences,w as isInternalTableName,se as isVacuousFilterClause,Ue as listTables,qe as readTablePage,Je as recordFanoutPass,Ke as recordGlobalPollPass,Ve as recordShapeProbePass,Pe as selectMatchingIds,Ye as summarizeFanoutTopics,Be as summarizeSubscriptions};
@@ -1 +1 @@
1
- import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-DeJW4U9z.mjs";import{A as l,a as i,b as n,D as d,n as m,c as p,d as u,l as q,s as G,m as c,k as S,g as f,i as A,j as D,e as h,p as T,u as _,q as g,f as j,r as y,t as C,h as O}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-DeoBMpZ2.mjs";import"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";export{l as AGG_COUNT,i as AGG_KEY,n as AGG_VALUE,d as DOC_COLUMN,m as DOC_ORIGINALS_KEY,p as aggUpsertSql,u as createIndexSql,q as decodeDocJson,G as decodeGroupKeyValue,c as doWhereSqlStrategy,S as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,h as jsonPathSql,T as jsonTypeGuard,_ as jsonTypeGuardSql,g as qualifiedJsonPath,j as qualifiedJsonPathSql,x as quoteIdentifier,y as rowToDocument,J as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
1
+ import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-DeJW4U9z.mjs";import{A as l,a as i,b as n,D as d,n as m,c as p,d as u,l as q,s as G,m as c,k as S,g as f,i as A,j as D,e as h,p as T,u as _,q as g,f as j,r as y,t as C,h as O}from"./do-sql-RROYQPCM.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-DeoBMpZ2.mjs";import"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";export{l as AGG_COUNT,i as AGG_KEY,n as AGG_VALUE,d as DOC_COLUMN,m as DOC_ORIGINALS_KEY,p as aggUpsertSql,u as createIndexSql,q as decodeDocJson,G as decodeGroupKeyValue,c as doWhereSqlStrategy,S as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,h as jsonPathSql,T as jsonTypeGuard,_ as jsonTypeGuardSql,g as qualifiedJsonPath,j as qualifiedJsonPathSql,x as quoteIdentifier,y as rowToDocument,J as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
@@ -1,4 +1,4 @@
1
- import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-BWrJQAOh.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${C(c)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",O="__cdc_log_table_id_seq",u=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
1
+ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-RROYQPCM.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${C(c)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",O="__cdc_log_table_id_seq",u=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-B0NXPs2x.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
1
+ import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-BJo578fn.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
@@ -1 +1 @@
1
- import{LunoraError as y}from"@lunora/errors";import{q as yt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Dn,l as We,s as kn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Ln,stableWireKey as qt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Fn,aggregateSqlFunction as Be,normalizeCountArgument as qn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ct,selectIndexForGroupBy as Wn,selectIndexForCount as Bn,selectIndexForAggregate as Pn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Un,searchIndexCoversTable as On}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{backfillAggregateIndexes as $i,backfillRankIndexes as Ei,backfillSearchIndexes as mi}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{appendCdcChange as Hn,readCdcDocAtOrBefore as Gn}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{CDC_LOG_TABLE as Ti,applyCdcChanges as Ri,bumpCdcEpoch as _i,cdcCanVouchFor as vi,cdcForkedError as Ii,cdcSeqLeavingRows as Ai,cdcTouchesTables as xi,cdcTrimmedError as Ci,compactCdcDocs as bi,cursorBelowRetainedFloor as Mi,minCdcReplayableSeq as Di,minCdcSeq as ki,readCdcChangeKeys as Li,readCdcChanges as Fi,readCdcCursor as qi,readCdcEpoch as Wi,trimCdcChanges as Bi}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{allocateCommitSeq as jn,COMMIT_SEQ_FIELD as Kn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Nn}from"./createCompanionSync-_zfDTDoO.mjs";import{isMemoryTable as Wt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Bt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Qn,j as ft,D as oe,r as Ie,k as ue,b as Pe,A as at,a as Ue,m as fe,e as he,s as Vn,t as Jn,i as zn,q as Pt,h as fn,g as Yn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as hn,unionAll as wn,WORKERD_SQLITE_LIMITS as pn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Xn,boundingBoxGeohashes as Zn,haversineMeters as eo,pointInBoundingBox as to}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as no}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as oo,assertPatchAllowed as ro,operatorFields as io,readPatchField as Ut}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as so,encodeCursor as Ne,nullsOrderSuffix as co,normalizeOrderKeys as Ot,uniqueIndexFields as ao,buildSeekWhere as lo,decodeCursor as Ht,buildSeekBeforeWhere as uo,softDeleteScope as ve,applySelect as Gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as jt,sortColumnName as Kt,resolveRankPartition as fo,encodePartitionKey as ho,RANK_TIEBREAK as wo,rankPivotConditionSql as po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Nt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as go,withUnknownIndexKeys as yo,indexKeysForRow as $o,buildIndexRange as Eo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as Ae,c as X,t as Je,i as Qt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as xe}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as mo,isPushableWhere as So}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as To,findRelated as Ro}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as dt,resolveRelationPredicates as _o,composeReadPredicate as vo}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as Io}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Ao,applyInsertDefaults as ht,resolveWith as Vt,relationHooks as Jt,applyOnDelete as xo,fanOutScalarCounts as Co}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as bo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Do}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ui,migrateClientWatermark as Oi,readClientWatermark as Hi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ji,readIdempotent as Ki,trimIdempotent as Ni,writeIdempotent as Qi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ji}from"./runShardMigrations-DMDT1blz.mjs";import{selectShapeMembers as Yi,selectShapeRows as Xi}from"./selectShapeMembers-BCfKypfN.mjs";const Lo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Fo=()=>new y("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,J=1024,$t=(n,i)=>i.query(n),qo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let m=0;for(const S of n)(w?S.startsWith(s):S===s)&&(m+=1);if(m===0)return 0;o+=m}return o},Wo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>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(c)}},Bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Xt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const m=n;if(s!==m.definition.field)throw new y("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${s}"`);const S=$t(w,o).length;if(S>Yt)throw new y("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(Yt)} search terms are supported (got ${String(S)})`);return m.field=s,m.query=w,m.hasQuery=!0,c}};return c},Po=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Uo=n=>Math.min(n.offset+n.numItems+1,J),Oo=n=>btoa(`search:${String(n)}`),Ho=n=>{let i;try{i=Lo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Go=n=>{if(typeof n.endCursor=="string")throw new y("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 y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Ho(n.cursor):0;if(o===void 0)throw Fo();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-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,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},jo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Oo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ko=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},gn=500,yn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??gn},$n=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},No=32,Qo=1024,En=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(oe)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Qe(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},ze={fieldRef:n=>Qe(ft(n)),rangeTypeGuard:(n,i)=>Qe(Qn(n,i)),serialize:xe},Vo=n=>n===void 0?"":co(n==="first"),mn=n=>{const i=n.map(o=>`${ft(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Vo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ft("id")} ${so(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Jo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Sn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),zo=n=>{const i=Sn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Yo=(n,i)=>{const o=n.order,c=zo(n),{shape:s}=i;return c.length>0?Ot(c.map(w=>({[w]:o})),s,{pinned:Sn(n),uniqueBy:ao(i.indexes,s)}):Ot([{_creationTime:o}],s)},Xo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Jo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(lo(i,Ht(o))),c&&s.push(uo(i,Ht(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,No):n.want},wt=(n,i,o,c,s,w,m)=>{const S=Yo(c,o),I=mn(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=Zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=X(Xo(c,S,A,w.endCursor),ze,Je),q=En(i,s&&P?Ae(P," AND ",s):s??P,I,D),k=we(n,q.text,...q.params).toArray();let W={};m(k.length);for(const O of k)if(W=Ie(O),F.every(ge=>ge(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ne(W,S),D=Math.max(D,Math.min(D*2,Qo))}},er=(n,i,o,c,s,w,m,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=wt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:m.all,selective:m.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ne(k,q):null}}const{documents:$,orderKeys:F}=wt(n,i,o,c,w,{cursor:s.cursor,filters:m.all,selective:m.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ne(D,F):null,isDone:!C,page:A}},Ye=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},pe=Ce(oe),tr=Ye(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Zt=Ye(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),nr=Ye(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),or=Ye(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),rr="SELECT changes() AS changed",en=new Map,ir="",sr=n=>{const i=JSON.stringify(n),o=en.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(w)} WHERE id = ${ir}`),{sql:s}=hn("sqlite",a`${wn(c)} LIMIT 1`);return en.set(i,s),s},cr=(n,i)=>i.map(()=>n),ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,dr=n=>{if(!ar.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},pt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},lr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const m=s?ht(n,w,c)._id:w._id;typeof m=="string"&&pt(m)}},tn=50,He=Math.floor(pn.boundParams/3),nn=pn.boundParams,ur=128,Ve=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ge=(n,i,o)=>{$n(n,yn(i,o,Ve),o,Ve)},on=async(n,i,o,c,s)=>{const w=yn(c,s,Ve),{page:m}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return m.length>w&&$n(Math.max(await n.count(i,{where:o}),m.length),w,s,Ve),m},fr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},hr=n=>Math.max(n,J),Tn=(n,i)=>{const o=n.filters.map(c=>a`${he(c.field)} = ${xe(c.value)}`);return i&&o.push(i),o},wr=(n,i,o,c,s)=>{const w=$t(o.query,yt(o.definition.language));if(w.length===0)return[];const m=Dn(i,o.indexName),S=`${m}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Wo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${wn($)}) u JOIN ${a.identifier(m)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=Tn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=fn(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},pr=(n,i,o,c,s)=>{const w=yt(o.definition.language),m=$t(o.query,w);if(m.length===0)return[];const S=Tn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(hr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=fn(C);if(!A)continue;const D=qo(kn(A,o.definition),m);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},lt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},gr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("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},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s.sw,".within() sw corner",i,o.indexName),lt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("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 y("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}},c}};return c},yr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},$r=(n,i)=>{const o=yr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=eo(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return to(o,i.within)?{creationTime:c,distance:0}:void 0},Er=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Xn(o.near.point,o.near.radiusMeters):Zn(o.within),w=Yn(i,o.indexName),m=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(m,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=Ie(C),D=A?$r(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Rn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(m=>m(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},mr=(n,i,o,c,s,w=()=>{})=>{const m=o.within!==void 0,S=Er(n,i,o,s).map(I=>({distanceMeters:m?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},rn=(n,i,o,c,s,w,m=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=mr(n,i,S,I?void 0:w,c,m);return I?Rn($,s,w,F=>F.document):$},sn=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&Mo(c))throw new y("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)`)},Sr=n=>{let i=0;const o=[],c={...ze,relationExists:s=>{const{childWhere:w,negated:m,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Qe(`${Pt($,A)} = ${Pt(F,C)}`);o.push($);const P=X(w,c,Je);o.pop();const q=P===void 0?D:Ae(D," AND ",P),k=Ae("EXISTS (SELECT 1 FROM ",Qt(I.table)," AS ",Qt($)," WHERE ",q,")");return m?Ae("NOT ",k):k}};return c};class Tr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Rr=/\s/u,_r=String.fromCodePoint(0),cn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Rr.test(o)||o.includes(_r)?null:o},_n=(n,i,o,c=()=>{},s=()=>{},w=()=>{},m)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=m??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const E=K(I,$.pushedWhere);return E?X(E,fe):void 0},C=()=>{const E=K(I,$.pushedWhere);return E?X(E,ze,Je):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=E=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Un(n,o,S);const L=$.inMemoryFilters.length>0,R=Ko(L?void 0:E),Z=zn(n);if(Z&&!On(n,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const re=F(),ie=Z?wr(n,o,M,R,re):pr(n,o,M,R,re);!L&&E===void 0&&Po(ie);const Q=A();return D=ie.length,Q.length>0?Rn(ie,Q,E,se=>se.document):ie},q=E=>P(E).map(M=>M.document),k=E=>{const M=Go(E);return jo(q(Uo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(Eo(o,$.indexName,$.indexFields,$.sqlConditions,xe))},O=E=>{W();let M=0;const L=(()=>{if($.search){const R=q(E);return M=D,R}return $.geo?rn(n,o,$,F(),A(),E,R=>{M=R}).map(R=>R.document):wt(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:E===void 0?void 0:Math.max(0,Math.floor(E))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},ge=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let E=0;const M=(()=>{if($.search){const L=P(void 0);return E=D,L}return rn(n,o,$,F(),A(),void 0,L=>{E=L})})();return w(Math.max(E,M.length)),M},N={async*[Symbol.asyncIterator](){const E=_n(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await E.collect();return}let M;for(;;){const L=await E.paginate({cursor:M??null,numItems:ur});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return ge()},filter(E){const M=mo(E);return M!==void 0&&So(M,S.shape)?($.pushedWhere=K($.pushedWhere,M),$.verifyFilters.push(E)):$.inMemoryFilters.push(E),N},async first(){return O(1)[0]??null},order(E){return $.order=E==="desc"?"desc":"asc",N},async paginate(E){let M=0;if(W(),$.search){const R=k(E);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=er(n,o,S,$,E,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(E){return O(E)},async unique(){const E=O(2);if(E.length>1)throw new Tr(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,M){const L=(S.geoIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown geo index "${E}" on table "${o}"`);c(o,E,"geo");const R={definition:L,indexName:E};if($.geo=R,M(gr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(E,M){const L=S.indexes.find(R=>R.name===E);if(!L)throw new y("INTERNAL",`unknown index "${E}" on table "${o}"`);return c(o,E,"index"),$.indexName=E,$.indexFields=L.fields,M&&M(fr($)),N},withSearchIndex(E,M){const L=(S.searchIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown search index "${E}" on table "${o}"`);c(o,E,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:E,query:""};if($.search=R,M(Bo(R,o,yt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,i,o,c)=>{const s=o;for(const[w,m]of Jn(n)){if(m.serverDefault){w in i&&(s[w]=m.serverDefault({auth:c}));continue}m.onUpdateFn&&!(w in i)&&(s[w]=m.onUpdateFn())}},an=5,dn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],je=n=>ln.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!ln.includes(i))):n,vr=/unique constraint failed/i,Ir=n=>n instanceof Error&&vr.test(n.message),Ar=/string or blob too big/iu,xr=(n,i)=>{if(!(!(n instanceof Error)||!Ar.test(n.message)))throw new y("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.`)},gt=(n,i,o,c)=>{try{we(n,o,...c)}catch(s){throw Ir(s)?new ce(`unique constraint violation on "${i}"`,"unique"):(xr(s,i),s)}},Ke=(n,i,o,c)=>{if(gt(n,i,o,c),we(n,rr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,i,o,c,s,w,m)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(wo)} < ${m}`:po(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Cr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let m=w.pop();m!==void 0;m=w.pop())for(const{holder:S,op:I}of i.get(m)??[]){if(S===c||zt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||zt(n,c,"delete")||o(c)).map(([c])=>c))},br=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),m=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=To(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Io(s,n.inTransaction),C=Cr(s),A=br(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=jn(c)),{[Kn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes??[],d=[];let f;for(const h of t)h&&(typeof h._id=="string"&&h._id!==f&&(f=h._id,d.push(go(f))),d.push(...yo(r,$o(r,h,xe))));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const ge=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},N=n.onRead??(()=>{}),E=e=>{Wt(s.tables[e])&&N(Nt,Nt)},M=n.onReadRange??(e=>{N(e.table,H)}),L=e=>{E(e.table),M(e)},R=(e,t,r)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),E(e),N(e,t,r)},Z=(e,t)=>{const r=e.row._id;R(e.tableName,typeof r=="string"?r:t,typeof r=="string")},re=n.onIndexUse??(()=>{}),ie=n.onWrite??(()=>{}),Q=e=>{O||W?.recordWrite(e)},se=async e=>{Q(e.doc),await ie(e)},{cache:ye}=n,$e=n.clock??(()=>Date.now()),Et=n.idGenerator??(()=>crypto.randomUUID()),mt=n.scheduler??Fn,{globalDb:Ee}=n,ae=n.auth??{identity:null,userId:null},St=n.cdc??!1,Xe=mt,vn=Do({scheduler:typeof Xe.list=="function"&&typeof Xe.get=="function"?Xe:void 0,storage:n.storage}),me=(e,t,r,d)=>{St&&!Wt(s.tables[e])&&Hn(c,$e(),e,t,r,d)},Tt=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!St)return!1;const h=i?.();if(h===void 0)return!1;const l=Gn(c,e,t,h);if(l===void 0)return!1;const u=io(f,r);return Object.keys(je(r)).some(p=>!u.has(p)&&qt(Ut(l,p))!==qt(Ut(d,p)))},de=e=>s.tables[e]?.shardMode?.kind==="global",Rt=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}return U},Ze=e=>Rt(e,"cascade"),G=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}},_t=async(e,t,r,d,f)=>{f&&Q(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},et=(e,t)=>Rt(e,"relation load").findMany(e,t),vt=(e,t)=>(de(e)&&R(e,H),et(e,t)),In=e=>!de(e.table),It=n.relationExistsPushDown??"auto",At=It!=="never",{maxRelationKeys:xt}=n,be=(e,t,r)=>_o(e,{fetcher:vt,maxRelationKeys:xt,relationBaseWhere:r,schema:s,tableName:t}),Ct=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Co((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,d),l),T=await be(p,e,void 0),x=X(T,fe),_=he(t);let v=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(v=a`${v} WHERE ${x}`),v=a`${v} GROUP BY ${_}`;const b=j(c,v).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let Me=0;const bt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))bt.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>bt.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>tn)throw Me-=1,new ce(`trigger recursion exceeded ${String(tn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await ko({ctx:bn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:Te,syncAggregates:De,syncCompanionsForInsert:Mt,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Nn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ye?.invalidate(e,t,k(e,r)),recordCdc:me,schema:s,sql:c,verified:n.companionMemo?.verified}),Dt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},kt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||de(e)?Ee:void 0,ot=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)Q(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=kt(t);for(let d=0;d<r.length;d+=nn){const f=r.slice(d,d+nn),[h]=we(c,sr(f),...cr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=Ie(h);if(typeof l!="string"||!u)return;const p=h[oe];return{docJson:typeof p=="string"?p:ue(p??{}),row:u,tableName:l}}},Lt={assertRankPartitionLocal:Dt,ensureRankBackfilled:nt,onRead:R,rowToDocument:Ie,schema:s,sql:c},An=(e,t,r)=>{const d=X(r,fe);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},xn=(e,t,r,d)=>Tt(e,t,r,d)?(o?.({fields:Object.keys(je(r)),id:t,table:e}),!0):!1,Cn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!An(e,t,r.where)||xn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof ce&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},Ft=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await vo(t,r,{canPushExists:At?In:void 0,existsPushMode:It==="always"?"always":"auto",fetcher:vt,maxRelationKeys:xt,schema:s,tableName:e}),p=At?Sr(d):ze,T=X(u,p,Je),x=En(e,T,mn(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:vn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(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 y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),l=await be(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Pn(d.aggregateIndexes,t.op,t.field,t.where);if(g){tt(e,g.index);const B=it(g.index.by??[],g.key),z=rt(e,g.index.name),Y=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${B}`).toArray()[0];return st(t.op,Y)}}sn(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(l,fe),T=Be(t.op),x=he(t.field);let _=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(_=a`${_} WHERE ${p}`);const b=j(c,_).toArray()[0]?.value;return b??null},asId(e,t){const r=cn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=qn(t);if(f.restrictsCounts)throw new ct(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=K(K(f.baseWhere,f.where),h),u=await be(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const v=Bn(d.aggregateIndexes,f.where);if(v){tt(e,v.index);const b=it(v.index.by??[],v.key),g=rt(e,v.index.name),B=j(c,a`SELECT ${Pe} AS value FROM ${a.identifier(g)} WHERE ${Ue} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=X(u,fe);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){m(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const v=_e(e);v&&await ot(v,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),await xo({deletedId:t,deletedReference:v=>h[v],findHolders:async(v,b,g,B)=>(await Ze(v).findMany(v,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(v,b)=>Ze(v).delete(v,b,r),onRestrict:v=>{throw new ce(v,"restrict")},onSetNull:(v,b,g)=>Ze(v).patch(v,b,{[g]:null}),schema:s,tableName:l}),Se(l),Te(l),T&&x){const v={[x]:$e()},b={...h,...q(l),...v,_id:t};ut(T,v,b,ae),Ke(c,l,Zt(l),[ue(b),t,f]),Le(l,t,b,h),ke(l,t,void 0),De(l,h,b),Re(l,t,h,void 0);const g=k(l,h,b);ye?.invalidate(l,t,g),me(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l});return}Ke(c,l,or(l),[t,f]),Le(l,t,void 0),ke(l,t,void 0),De(l,h,void 0),Re(l,t,h,void 0);const _=k(l,h);ye?.invalidate(l,t,_),me(l,t,"delete"),w({indexKeys:_,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??gn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await ge(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):ot(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){m(e,"ctx.db.deleteMany(table, ids)"),Ge(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await on(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return ot(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,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 no(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await Ft(e,d,t,R),p=we(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=Ie(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Vt({groupedCounter:Ct,fetcher:et,parents:T,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Gt(T,t.select,t.with)};const x=T.length>h,_=x?T.slice(0,h):T,v=_.at(-1);return t.with&&await Vt({fetcher:et,groupedCounter:Ct,parents:_,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&v&&t.omitContinueCursor!==!0?Ne(v,l):null,isDone:!x,page:Gt(_,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Ft(e,d,t,()=>{}),h=we(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){m(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=_e(e);return d?d.get(e,t):(E(e),N(e,t,!0),null)}return Z(r,t),r.row},async lookupById(e,t){const r=ne(e,t);if(!r){for(const d of kt(t))E(d),N(d,e,!0);return null}return Z(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=K(K(t.baseWhere,t.where),h),u=await be(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=Wn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,z=g?.index.by?.length??0;if(g&&(B===0||B===z)){tt(e,g.index);const Y=rt(e,g.index.name),V=Object.keys(g.partial),le=[];if(V.length===(g.index.by??[]).length&&V.length>0){const Fe=it(g.index.by??[],g.partial),qe=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...g.partial},value:st(f.op,qe[0])}),le}const Mn=j(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)}`).toArray();for(const Fe of Mn){const qe=Ln(JSON.parse(Fe.key));le.push({key:qe,value:st(f.op,Fe)})}return le}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;sn(d,g,B)}const T=X(u,fe),x=t.by.map(g=>a`${he(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(Be(f.op))}(${he(g)}) AS value`)}let _=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(_=a`${_} WHERE ${T}`),_=a`${_} GROUP BY ${a.join(t.by.map(g=>he(g)),a`, `)}`;const v=j(c,_).toArray(),b=[];for(const g of v){const B={};for(const Y of t.by)B[Y]=Vn(d.shape[Y],g[Y]??null);const{value:z}=g;b.push({key:B,value:z==null?null:Number(z)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return _t(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Oe(f,ht(f,t,ae),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(dr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(pt(l._id),u=l._id):u=Et();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:$e(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),Se(e),Te(e),gt(c,e,tr(e),[u,p,ue(T)]),Mt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await se({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(Ge(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];lr(s.tables[e],t,r?.allowExplicitId,ae);for(const T of t)Q(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Se(e),Te(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:Ao(f),u=t.map((p,T)=>{const x=ht(f,p,ae),_=l===void 0?x:Oe(l,x,{supplied:p}),v=r?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;v!==void 0&&pt(v);const b=v??Et(),g=r?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:$e(),B={..._,...h[Math.floor(T/He)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)Q(p.document);for(let p=0;p<u.length;p+=He){const T=a.join(u.slice(p,p+He).map(_=>a`(${_.id}, ${_.creationTime}, ${ue(_.document)})`),a`, `),x=hn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(oe)}) VALUES ${T}`);gt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)Mt(e,T,p),await ie({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){Ge(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)Q(u);const l=async u=>h?_t(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof ce&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return cn(s,e,t)},async patch(e,t,r,d){m(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=_e(e);if(b){Q(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),dn("patch",r),Tt(u,t,r,l)){o?.({fields:Object.keys(je(r)),id:t,table:u});return}const T=oo(p,r,l),x={...l,...je(T),...q(u),_id:t};ut(p,T,x,ae);const _=Oe(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});ro(d,l,_),ee(u,"before","update")&&await te("before","update",{doc:{..._},id:t,op:"update",previous:l,table:u}),$(u,_,l),Se(u),Te(u),Ke(c,u,Zt(u),[ue(_),t,h]),Le(u,t,_,l),ke(u,t,_),De(u,l,_),Re(u,t,l,_);const v=k(u,l,_);ye?.invalidate(u,t,v),me(u,t,"update",_),w({indexKeys:v,key:t,op:"update",row:_,table:u}),ee(u,"after","update")&&await te("after","update",{doc:_,id:t,op:"update",previous:l,table:u}),await se({doc:_,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return Q(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=an;f+=1){const h=await Cn(e,t,r,f<an,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){m(e,"ctx.db.patchMany(table, patches)"),Ge(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await on(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return Ro(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):_n(c,s,e,re,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);re(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(V=>V.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Dt(e,f,h),r.restrictsCounts)throw new ct(e);R(e,H),nt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=jt(e,h.name),p=h.sortBy.map((V,le)=>Kt(le)),T=p.map(V=>Ce(V)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[_]=x;if(_===void 0)return null;let v=_.__partition__;const b=K(r.baseWhere,r.where);dt(b,s,e,"rank");const g=fo(h,b);if(g){const V=ho(h.partitionBy??[],g);if(V!==v)return null;v=V}const B=p.map(V=>_[V]),{before:z,total:Y}=un(c,u,p,h.sortBy,v,B,l);return{position:z+1,total:Y}},async rankBefore(e,t,r){if(de(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ct(e);R(e,H),nt(e,f);const h=jt(e,f.name),l=f.sortBy.map((p,T)=>Kt(T)),u=f.sortBy.map((p,T)=>xe(r.sortValues[T]??null));return un(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);re(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=Bt(Lt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage"),re(e,t,"rank");const{directions:d,hasMore:f,rows:h}=Bt(Lt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){m(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=_e(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Re(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){m(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=_e(e);if(B){Q(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);dn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,_=T??x??$e(),v={...r,...q(u),_creationTime:_,_id:t};ut(p,r,v,ae);const b=d?.allowExplicitId===!0,g=Oe(p,v,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),Se(u),Te(u),Ke(c,u,nr(u),[_,ue(g),t,h]),Le(u,t,g,l),ke(u,t,g),De(u,l,g),Re(u,t,l,g),ye?.invalidate(u,t,k(u,l,g)),me(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await se({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},bn={db:U,scheduler:mt};return n.enforceRls===!0?bo(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ti as CDC_LOG_TABLE,ji as IDEMPOTENCY_TABLE,Tr as NotUniqueError,Ui as advanceClientWatermark,Ri as applyCdcChanges,dn as assertNoExplicitUndefined,pt as assertStorableRowId,dr as assertValidClientId,$i as backfillAggregateIndexes,Ei as backfillRankIndexes,mi as backfillSearchIndexes,_i as bumpCdcEpoch,vi as cdcCanVouchFor,Ii as cdcForkedError,Ai as cdcSeqLeavingRows,xi as cdcTouchesTables,Ci as cdcTrimmedError,bi as compactCdcDocs,pi as createShardCtxDb,Mi as cursorBelowRetainedFloor,Oi as migrateClientWatermark,Di as minCdcReplayableSeq,ki as minCdcSeq,cn as normalizeIdStructurally,Li as readCdcChangeKeys,Fi as readCdcChanges,qi as readCdcCursor,Wi as readCdcEpoch,Hi as readClientWatermark,Ki as readIdempotent,Ji as runShardMigrations,Yi as selectShapeMembers,Xi as selectShapeRows,je as stripReservedPatchFields,Bi as trimCdcChanges,Ni as trimIdempotent,Qi as writeIdempotent};
1
+ import{LunoraError as y}from"@lunora/errors";import{q as yt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Dn,l as We,s as kn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Ln,stableWireKey as qt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Fn,aggregateSqlFunction as Be,normalizeCountArgument as qn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ct,selectIndexForGroupBy as Wn,selectIndexForCount as Bn,selectIndexForAggregate as Pn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Un,searchIndexCoversTable as On}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{backfillAggregateIndexes as $i,backfillRankIndexes as Ei,backfillSearchIndexes as mi}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{appendCdcChange as Hn,readCdcDocAtOrBefore as Gn}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{CDC_LOG_TABLE as Ti,applyCdcChanges as Ri,bumpCdcEpoch as _i,cdcCanVouchFor as vi,cdcForkedError as Ii,cdcSeqLeavingRows as Ai,cdcTouchesTables as xi,cdcTrimmedError as Ci,compactCdcDocs as bi,cursorBelowRetainedFloor as Mi,minCdcReplayableSeq as Di,minCdcSeq as ki,readCdcChangeKeys as Li,readCdcChanges as Fi,readCdcCursor as qi,readCdcEpoch as Wi,trimCdcChanges as Bi}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{allocateCommitSeq as jn,COMMIT_SEQ_FIELD as Kn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Nn}from"./createCompanionSync-qhvw6wyL.mjs";import{isMemoryTable as Wt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Bt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Qn,j as ft,D as oe,r as Ie,k as ue,b as Pe,A as at,a as Ue,m as fe,e as he,s as Vn,t as Jn,i as zn,q as Pt,h as fn,g as Yn}from"./do-sql-RROYQPCM.mjs";import{renderSql as hn,unionAll as wn,WORKERD_SQLITE_LIMITS as pn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Xn,boundingBoxGeohashes as Zn,haversineMeters as eo,pointInBoundingBox as to}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as no}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as oo,assertPatchAllowed as ro,operatorFields as io,readPatchField as Ut}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as so,encodeCursor as Ne,nullsOrderSuffix as co,normalizeOrderKeys as Ot,uniqueIndexFields as ao,buildSeekWhere as lo,decodeCursor as Ht,buildSeekBeforeWhere as uo,softDeleteScope as ve,applySelect as Gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as jt,sortColumnName as Kt,resolveRankPartition as fo,encodePartitionKey as ho,RANK_TIEBREAK as wo,rankPivotConditionSql as po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Nt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as go,withUnknownIndexKeys as yo,indexKeysForRow as $o,buildIndexRange as Eo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as Ae,c as X,t as Je,i as Qt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as xe}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as mo,isPushableWhere as So}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as To,findRelated as Ro}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as dt,resolveRelationPredicates as _o,composeReadPredicate as vo}from"./DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs";import{describeRelationWrites as Io}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Ao,applyInsertDefaults as ht,resolveWith as Vt,relationHooks as Jt,applyOnDelete as xo,fanOutScalarCounts as Co}from"./applyInsertDefaults-BJo578fn.mjs";import{guardWriter as bo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Do}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ui,migrateClientWatermark as Oi,readClientWatermark as Hi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ji,readIdempotent as Ki,trimIdempotent as Ni,writeIdempotent as Qi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ji}from"./runShardMigrations-_KucUTa2.mjs";import{selectShapeMembers as Yi,selectShapeRows as Xi}from"./selectShapeMembers-BhK79123.mjs";const Lo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Fo=()=>new y("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,J=1024,$t=(n,i)=>i.query(n),qo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let m=0;for(const S of n)(w?S.startsWith(s):S===s)&&(m+=1);if(m===0)return 0;o+=m}return o},Wo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>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(c)}},Bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Xt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const m=n;if(s!==m.definition.field)throw new y("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${s}"`);const S=$t(w,o).length;if(S>Yt)throw new y("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(Yt)} search terms are supported (got ${String(S)})`);return m.field=s,m.query=w,m.hasQuery=!0,c}};return c},Po=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Uo=n=>Math.min(n.offset+n.numItems+1,J),Oo=n=>btoa(`search:${String(n)}`),Ho=n=>{let i;try{i=Lo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Go=n=>{if(typeof n.endCursor=="string")throw new y("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 y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Ho(n.cursor):0;if(o===void 0)throw Fo();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-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,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},jo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Oo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ko=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},gn=500,yn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??gn},$n=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},No=32,Qo=1024,En=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(oe)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Qe(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},ze={fieldRef:n=>Qe(ft(n)),rangeTypeGuard:(n,i)=>Qe(Qn(n,i)),serialize:xe},Vo=n=>n===void 0?"":co(n==="first"),mn=n=>{const i=n.map(o=>`${ft(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Vo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ft("id")} ${so(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Jo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Sn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),zo=n=>{const i=Sn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Yo=(n,i)=>{const o=n.order,c=zo(n),{shape:s}=i;return c.length>0?Ot(c.map(w=>({[w]:o})),s,{pinned:Sn(n),uniqueBy:ao(i.indexes,s)}):Ot([{_creationTime:o}],s)},Xo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Jo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(lo(i,Ht(o))),c&&s.push(uo(i,Ht(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,No):n.want},wt=(n,i,o,c,s,w,m)=>{const S=Yo(c,o),I=mn(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=Zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=X(Xo(c,S,A,w.endCursor),ze,Je),q=En(i,s&&P?Ae(P," AND ",s):s??P,I,D),k=we(n,q.text,...q.params).toArray();let W={};m(k.length);for(const O of k)if(W=Ie(O),F.every(ge=>ge(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ne(W,S),D=Math.max(D,Math.min(D*2,Qo))}},er=(n,i,o,c,s,w,m,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=wt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:m.all,selective:m.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ne(k,q):null}}const{documents:$,orderKeys:F}=wt(n,i,o,c,w,{cursor:s.cursor,filters:m.all,selective:m.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ne(D,F):null,isDone:!C,page:A}},Ye=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},pe=Ce(oe),tr=Ye(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Zt=Ye(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),nr=Ye(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),or=Ye(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),rr="SELECT changes() AS changed",en=new Map,ir="",sr=n=>{const i=JSON.stringify(n),o=en.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(w)} WHERE id = ${ir}`),{sql:s}=hn("sqlite",a`${wn(c)} LIMIT 1`);return en.set(i,s),s},cr=(n,i)=>i.map(()=>n),ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,dr=n=>{if(!ar.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},pt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},lr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const m=s?ht(n,w,c)._id:w._id;typeof m=="string"&&pt(m)}},tn=50,He=Math.floor(pn.boundParams/3),nn=pn.boundParams,ur=128,Ve=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ge=(n,i,o)=>{$n(n,yn(i,o,Ve),o,Ve)},on=async(n,i,o,c,s)=>{const w=yn(c,s,Ve),{page:m}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return m.length>w&&$n(Math.max(await n.count(i,{where:o}),m.length),w,s,Ve),m},fr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},hr=n=>Math.max(n,J),Tn=(n,i)=>{const o=n.filters.map(c=>a`${he(c.field)} = ${xe(c.value)}`);return i&&o.push(i),o},wr=(n,i,o,c,s)=>{const w=$t(o.query,yt(o.definition.language));if(w.length===0)return[];const m=Dn(i,o.indexName),S=`${m}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Wo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${wn($)}) u JOIN ${a.identifier(m)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=Tn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=fn(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},pr=(n,i,o,c,s)=>{const w=yt(o.definition.language),m=$t(o.query,w);if(m.length===0)return[];const S=Tn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(hr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=fn(C);if(!A)continue;const D=qo(kn(A,o.definition),m);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},lt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},gr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("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},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s.sw,".within() sw corner",i,o.indexName),lt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("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 y("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}},c}};return c},yr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},$r=(n,i)=>{const o=yr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=eo(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return to(o,i.within)?{creationTime:c,distance:0}:void 0},Er=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Xn(o.near.point,o.near.radiusMeters):Zn(o.within),w=Yn(i,o.indexName),m=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(m,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=Ie(C),D=A?$r(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Rn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(m=>m(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},mr=(n,i,o,c,s,w=()=>{})=>{const m=o.within!==void 0,S=Er(n,i,o,s).map(I=>({distanceMeters:m?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},rn=(n,i,o,c,s,w,m=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=mr(n,i,S,I?void 0:w,c,m);return I?Rn($,s,w,F=>F.document):$},sn=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&Mo(c))throw new y("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)`)},Sr=n=>{let i=0;const o=[],c={...ze,relationExists:s=>{const{childWhere:w,negated:m,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Qe(`${Pt($,A)} = ${Pt(F,C)}`);o.push($);const P=X(w,c,Je);o.pop();const q=P===void 0?D:Ae(D," AND ",P),k=Ae("EXISTS (SELECT 1 FROM ",Qt(I.table)," AS ",Qt($)," WHERE ",q,")");return m?Ae("NOT ",k):k}};return c};class Tr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Rr=/\s/u,_r=String.fromCodePoint(0),cn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Rr.test(o)||o.includes(_r)?null:o},_n=(n,i,o,c=()=>{},s=()=>{},w=()=>{},m)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=m??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const E=K(I,$.pushedWhere);return E?X(E,fe):void 0},C=()=>{const E=K(I,$.pushedWhere);return E?X(E,ze,Je):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=E=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Un(n,o,S);const L=$.inMemoryFilters.length>0,R=Ko(L?void 0:E),Z=zn(n);if(Z&&!On(n,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const re=F(),ie=Z?wr(n,o,M,R,re):pr(n,o,M,R,re);!L&&E===void 0&&Po(ie);const Q=A();return D=ie.length,Q.length>0?Rn(ie,Q,E,se=>se.document):ie},q=E=>P(E).map(M=>M.document),k=E=>{const M=Go(E);return jo(q(Uo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(Eo(o,$.indexName,$.indexFields,$.sqlConditions,xe))},O=E=>{W();let M=0;const L=(()=>{if($.search){const R=q(E);return M=D,R}return $.geo?rn(n,o,$,F(),A(),E,R=>{M=R}).map(R=>R.document):wt(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:E===void 0?void 0:Math.max(0,Math.floor(E))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},ge=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let E=0;const M=(()=>{if($.search){const L=P(void 0);return E=D,L}return rn(n,o,$,F(),A(),void 0,L=>{E=L})})();return w(Math.max(E,M.length)),M},N={async*[Symbol.asyncIterator](){const E=_n(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await E.collect();return}let M;for(;;){const L=await E.paginate({cursor:M??null,numItems:ur});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return ge()},filter(E){const M=mo(E);return M!==void 0&&So(M,S.shape)?($.pushedWhere=K($.pushedWhere,M),$.verifyFilters.push(E)):$.inMemoryFilters.push(E),N},async first(){return O(1)[0]??null},order(E){return $.order=E==="desc"?"desc":"asc",N},async paginate(E){let M=0;if(W(),$.search){const R=k(E);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=er(n,o,S,$,E,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(E){return O(E)},async unique(){const E=O(2);if(E.length>1)throw new Tr(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,M){const L=(S.geoIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown geo index "${E}" on table "${o}"`);c(o,E,"geo");const R={definition:L,indexName:E};if($.geo=R,M(gr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(E,M){const L=S.indexes.find(R=>R.name===E);if(!L)throw new y("INTERNAL",`unknown index "${E}" on table "${o}"`);return c(o,E,"index"),$.indexName=E,$.indexFields=L.fields,M&&M(fr($)),N},withSearchIndex(E,M){const L=(S.searchIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown search index "${E}" on table "${o}"`);c(o,E,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:E,query:""};if($.search=R,M(Bo(R,o,yt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,i,o,c)=>{const s=o;for(const[w,m]of Jn(n)){if(m.serverDefault){w in i&&(s[w]=m.serverDefault({auth:c}));continue}m.onUpdateFn&&!(w in i)&&(s[w]=m.onUpdateFn())}},an=5,dn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],je=n=>ln.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!ln.includes(i))):n,vr=/unique constraint failed/i,Ir=n=>n instanceof Error&&vr.test(n.message),Ar=/string or blob too big/iu,xr=(n,i)=>{if(!(!(n instanceof Error)||!Ar.test(n.message)))throw new y("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.`)},gt=(n,i,o,c)=>{try{we(n,o,...c)}catch(s){throw Ir(s)?new ce(`unique constraint violation on "${i}"`,"unique"):(xr(s,i),s)}},Ke=(n,i,o,c)=>{if(gt(n,i,o,c),we(n,rr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,i,o,c,s,w,m)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(wo)} < ${m}`:po(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Cr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let m=w.pop();m!==void 0;m=w.pop())for(const{holder:S,op:I}of i.get(m)??[]){if(S===c||zt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||zt(n,c,"delete")||o(c)).map(([c])=>c))},br=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),m=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=To(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Io(s,n.inTransaction),C=Cr(s),A=br(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=jn(c)),{[Kn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes??[],d=[];let f;for(const h of t)h&&(typeof h._id=="string"&&h._id!==f&&(f=h._id,d.push(go(f))),d.push(...yo(r,$o(r,h,xe))));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const ge=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},N=n.onRead??(()=>{}),E=e=>{Wt(s.tables[e])&&N(Nt,Nt)},M=n.onReadRange??(e=>{N(e.table,H)}),L=e=>{E(e.table),M(e)},R=(e,t,r)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),E(e),N(e,t,r)},Z=(e,t)=>{const r=e.row._id;R(e.tableName,typeof r=="string"?r:t,typeof r=="string")},re=n.onIndexUse??(()=>{}),ie=n.onWrite??(()=>{}),Q=e=>{O||W?.recordWrite(e)},se=async e=>{Q(e.doc),await ie(e)},{cache:ye}=n,$e=n.clock??(()=>Date.now()),Et=n.idGenerator??(()=>crypto.randomUUID()),mt=n.scheduler??Fn,{globalDb:Ee}=n,ae=n.auth??{identity:null,userId:null},St=n.cdc??!1,Xe=mt,vn=Do({scheduler:typeof Xe.list=="function"&&typeof Xe.get=="function"?Xe:void 0,storage:n.storage}),me=(e,t,r,d)=>{St&&!Wt(s.tables[e])&&Hn(c,$e(),e,t,r,d)},Tt=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!St)return!1;const h=i?.();if(h===void 0)return!1;const l=Gn(c,e,t,h);if(l===void 0)return!1;const u=io(f,r);return Object.keys(je(r)).some(p=>!u.has(p)&&qt(Ut(l,p))!==qt(Ut(d,p)))},de=e=>s.tables[e]?.shardMode?.kind==="global",Rt=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}return U},Ze=e=>Rt(e,"cascade"),G=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}},_t=async(e,t,r,d,f)=>{f&&Q(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},et=(e,t)=>Rt(e,"relation load").findMany(e,t),vt=(e,t)=>(de(e)&&R(e,H),et(e,t)),In=e=>!de(e.table),It=n.relationExistsPushDown??"auto",At=It!=="never",{maxRelationKeys:xt}=n,be=(e,t,r)=>_o(e,{fetcher:vt,maxRelationKeys:xt,relationBaseWhere:r,schema:s,tableName:t}),Ct=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Co((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,d),l),T=await be(p,e,void 0),x=X(T,fe),_=he(t);let v=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(v=a`${v} WHERE ${x}`),v=a`${v} GROUP BY ${_}`;const b=j(c,v).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let Me=0;const bt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))bt.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>bt.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>tn)throw Me-=1,new ce(`trigger recursion exceeded ${String(tn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await ko({ctx:bn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:Te,syncAggregates:De,syncCompanionsForInsert:Mt,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Nn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ye?.invalidate(e,t,k(e,r)),recordCdc:me,schema:s,sql:c,verified:n.companionMemo?.verified}),Dt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},kt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||de(e)?Ee:void 0,ot=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)Q(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=kt(t);for(let d=0;d<r.length;d+=nn){const f=r.slice(d,d+nn),[h]=we(c,sr(f),...cr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=Ie(h);if(typeof l!="string"||!u)return;const p=h[oe];return{docJson:typeof p=="string"?p:ue(p??{}),row:u,tableName:l}}},Lt={assertRankPartitionLocal:Dt,ensureRankBackfilled:nt,onRead:R,rowToDocument:Ie,schema:s,sql:c},An=(e,t,r)=>{const d=X(r,fe);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},xn=(e,t,r,d)=>Tt(e,t,r,d)?(o?.({fields:Object.keys(je(r)),id:t,table:e}),!0):!1,Cn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!An(e,t,r.where)||xn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof ce&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},Ft=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await vo(t,r,{canPushExists:At?In:void 0,existsPushMode:It==="always"?"always":"auto",fetcher:vt,maxRelationKeys:xt,schema:s,tableName:e}),p=At?Sr(d):ze,T=X(u,p,Je),x=En(e,T,mn(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:vn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(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 y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),l=await be(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Pn(d.aggregateIndexes,t.op,t.field,t.where);if(g){tt(e,g.index);const B=it(g.index.by??[],g.key),z=rt(e,g.index.name),Y=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${B}`).toArray()[0];return st(t.op,Y)}}sn(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(l,fe),T=Be(t.op),x=he(t.field);let _=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(_=a`${_} WHERE ${p}`);const b=j(c,_).toArray()[0]?.value;return b??null},asId(e,t){const r=cn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=qn(t);if(f.restrictsCounts)throw new ct(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=K(K(f.baseWhere,f.where),h),u=await be(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const v=Bn(d.aggregateIndexes,f.where);if(v){tt(e,v.index);const b=it(v.index.by??[],v.key),g=rt(e,v.index.name),B=j(c,a`SELECT ${Pe} AS value FROM ${a.identifier(g)} WHERE ${Ue} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=X(u,fe);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){m(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const v=_e(e);v&&await ot(v,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),await xo({deletedId:t,deletedReference:v=>h[v],findHolders:async(v,b,g,B)=>(await Ze(v).findMany(v,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(v,b)=>Ze(v).delete(v,b,r),onRestrict:v=>{throw new ce(v,"restrict")},onSetNull:(v,b,g)=>Ze(v).patch(v,b,{[g]:null}),schema:s,tableName:l}),Se(l),Te(l),T&&x){const v={[x]:$e()},b={...h,...q(l),...v,_id:t};ut(T,v,b,ae),Ke(c,l,Zt(l),[ue(b),t,f]),Le(l,t,b,h),ke(l,t,void 0),De(l,h,b),Re(l,t,h,void 0);const g=k(l,h,b);ye?.invalidate(l,t,g),me(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l});return}Ke(c,l,or(l),[t,f]),Le(l,t,void 0),ke(l,t,void 0),De(l,h,void 0),Re(l,t,h,void 0);const _=k(l,h);ye?.invalidate(l,t,_),me(l,t,"delete"),w({indexKeys:_,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??gn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await ge(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):ot(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){m(e,"ctx.db.deleteMany(table, ids)"),Ge(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await on(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return ot(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,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 no(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await Ft(e,d,t,R),p=we(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=Ie(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Vt({groupedCounter:Ct,fetcher:et,parents:T,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Gt(T,t.select,t.with)};const x=T.length>h,_=x?T.slice(0,h):T,v=_.at(-1);return t.with&&await Vt({fetcher:et,groupedCounter:Ct,parents:_,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&v&&t.omitContinueCursor!==!0?Ne(v,l):null,isDone:!x,page:Gt(_,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Ft(e,d,t,()=>{}),h=we(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){m(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=_e(e);return d?d.get(e,t):(E(e),N(e,t,!0),null)}return Z(r,t),r.row},async lookupById(e,t){const r=ne(e,t);if(!r){for(const d of kt(t))E(d),N(d,e,!0);return null}return Z(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=K(K(t.baseWhere,t.where),h),u=await be(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=Wn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,z=g?.index.by?.length??0;if(g&&(B===0||B===z)){tt(e,g.index);const Y=rt(e,g.index.name),V=Object.keys(g.partial),le=[];if(V.length===(g.index.by??[]).length&&V.length>0){const Fe=it(g.index.by??[],g.partial),qe=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...g.partial},value:st(f.op,qe[0])}),le}const Mn=j(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)}`).toArray();for(const Fe of Mn){const qe=Ln(JSON.parse(Fe.key));le.push({key:qe,value:st(f.op,Fe)})}return le}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;sn(d,g,B)}const T=X(u,fe),x=t.by.map(g=>a`${he(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(Be(f.op))}(${he(g)}) AS value`)}let _=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(_=a`${_} WHERE ${T}`),_=a`${_} GROUP BY ${a.join(t.by.map(g=>he(g)),a`, `)}`;const v=j(c,_).toArray(),b=[];for(const g of v){const B={};for(const Y of t.by)B[Y]=Vn(d.shape[Y],g[Y]??null);const{value:z}=g;b.push({key:B,value:z==null?null:Number(z)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return _t(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Oe(f,ht(f,t,ae),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(dr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(pt(l._id),u=l._id):u=Et();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:$e(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),Se(e),Te(e),gt(c,e,tr(e),[u,p,ue(T)]),Mt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await se({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(Ge(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];lr(s.tables[e],t,r?.allowExplicitId,ae);for(const T of t)Q(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Se(e),Te(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:Ao(f),u=t.map((p,T)=>{const x=ht(f,p,ae),_=l===void 0?x:Oe(l,x,{supplied:p}),v=r?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;v!==void 0&&pt(v);const b=v??Et(),g=r?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:$e(),B={..._,...h[Math.floor(T/He)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)Q(p.document);for(let p=0;p<u.length;p+=He){const T=a.join(u.slice(p,p+He).map(_=>a`(${_.id}, ${_.creationTime}, ${ue(_.document)})`),a`, `),x=hn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(oe)}) VALUES ${T}`);gt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)Mt(e,T,p),await ie({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){Ge(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)Q(u);const l=async u=>h?_t(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof ce&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return cn(s,e,t)},async patch(e,t,r,d){m(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=_e(e);if(b){Q(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),dn("patch",r),Tt(u,t,r,l)){o?.({fields:Object.keys(je(r)),id:t,table:u});return}const T=oo(p,r,l),x={...l,...je(T),...q(u),_id:t};ut(p,T,x,ae);const _=Oe(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});ro(d,l,_),ee(u,"before","update")&&await te("before","update",{doc:{..._},id:t,op:"update",previous:l,table:u}),$(u,_,l),Se(u),Te(u),Ke(c,u,Zt(u),[ue(_),t,h]),Le(u,t,_,l),ke(u,t,_),De(u,l,_),Re(u,t,l,_);const v=k(u,l,_);ye?.invalidate(u,t,v),me(u,t,"update",_),w({indexKeys:v,key:t,op:"update",row:_,table:u}),ee(u,"after","update")&&await te("after","update",{doc:_,id:t,op:"update",previous:l,table:u}),await se({doc:_,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return Q(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=an;f+=1){const h=await Cn(e,t,r,f<an,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){m(e,"ctx.db.patchMany(table, patches)"),Ge(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await on(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return Ro(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):_n(c,s,e,re,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);re(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(V=>V.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Dt(e,f,h),r.restrictsCounts)throw new ct(e);R(e,H),nt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=jt(e,h.name),p=h.sortBy.map((V,le)=>Kt(le)),T=p.map(V=>Ce(V)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[_]=x;if(_===void 0)return null;let v=_.__partition__;const b=K(r.baseWhere,r.where);dt(b,s,e,"rank");const g=fo(h,b);if(g){const V=ho(h.partitionBy??[],g);if(V!==v)return null;v=V}const B=p.map(V=>_[V]),{before:z,total:Y}=un(c,u,p,h.sortBy,v,B,l);return{position:z+1,total:Y}},async rankBefore(e,t,r){if(de(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ct(e);R(e,H),nt(e,f);const h=jt(e,f.name),l=f.sortBy.map((p,T)=>Kt(T)),u=f.sortBy.map((p,T)=>xe(r.sortValues[T]??null));return un(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);re(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=Bt(Lt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage"),re(e,t,"rank");const{directions:d,hasMore:f,rows:h}=Bt(Lt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){m(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=_e(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Re(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){m(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=_e(e);if(B){Q(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);dn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,_=T??x??$e(),v={...r,...q(u),_creationTime:_,_id:t};ut(p,r,v,ae);const b=d?.allowExplicitId===!0,g=Oe(p,v,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),Se(u),Te(u),Ke(c,u,nr(u),[_,ue(g),t,h]),Le(u,t,g,l),ke(u,t,g),De(u,l,g),Re(u,t,l,g),ye?.invalidate(u,t,k(u,l,g)),me(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await se({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},bn={db:U,scheduler:mt};return n.enforceRls===!0?bo(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ti as CDC_LOG_TABLE,ji as IDEMPOTENCY_TABLE,Tr as NotUniqueError,Ui as advanceClientWatermark,Ri as applyCdcChanges,dn as assertNoExplicitUndefined,pt as assertStorableRowId,dr as assertValidClientId,$i as backfillAggregateIndexes,Ei as backfillRankIndexes,mi as backfillSearchIndexes,_i as bumpCdcEpoch,vi as cdcCanVouchFor,Ii as cdcForkedError,Ai as cdcSeqLeavingRows,xi as cdcTouchesTables,Ci as cdcTrimmedError,bi as compactCdcDocs,pi as createShardCtxDb,Mi as cursorBelowRetainedFloor,Oi as migrateClientWatermark,Di as minCdcReplayableSeq,ki as minCdcSeq,cn as normalizeIdStructurally,Li as readCdcChangeKeys,Fi as readCdcChanges,qi as readCdcCursor,Wi as readCdcEpoch,Hi as readClientWatermark,Ki as readIdempotent,Ji as runShardMigrations,Yi as selectShapeMembers,Xi as selectShapeRows,je as stripReservedPatchFields,Bi as trimCdcChanges,Ni as trimIdempotent,Qi as writeIdempotent};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-BWrJQAOh.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-RROYQPCM.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-BWrJQAOh.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
1
+ import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-RROYQPCM.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
@@ -1 +1 @@
1
- import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-_zfDTDoO.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-qhvw6wyL.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-RROYQPCM.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-BWrJQAOh.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-RROYQPCM.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BhK79123.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
1
+ import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-RROYQPCM.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-Cgu71D66.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-DMDT1blz.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch("items",o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
1
+ import{createShardCtxDb as _}from"./NotUniqueError-BprK42pn.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-_KucUTa2.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch("items",o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{WIRE_TAG as T,decodeWire as h,needsWireEncoding as A,encodeWire as $}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{e as O}from"./effective-kind-BmG_zCAy.mjs";import{S as g,i as y,s as N,F as b}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as I}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as j}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as L}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const w=/^[A-Za-z_$][\w$]*$/u,f=e=>w.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",Y=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=L(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const o=t??e;try{return A(o)?JSON.stringify($(o)):JSON.stringify(o)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},D=e=>{const t=JSON.parse(e),r=e.includes(T)||e.includes(String.raw`\u`)?h(t):t,o=r[i];if(o===null||typeof o!="object"||Array.isArray(o))return r;const s={...r};return delete s[i],{...s,...o}},x=(e,t)=>`${e}__geo_${t}`,P=e=>{try{return N(e)}catch(t){throw t instanceof b?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(y(e)?P(e).map(r=>f(r)).join("."):f(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,R=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${g[t]})`,U=e=>n.raw(R(e)),G=(e,t)=>n.raw(C(e,t)),q=(e,t)=>E(`${I(e)}.`,t),H=(e,t)=>n.raw(q(e,t)),Z=(e,t,r,o)=>n`CREATE ${o?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${r})`,u=n.identifier("__key__"),v=n.identifier("__value__"),F=n.identifier("__count__"),ee=(e,t,r,o,s)=>n`INSERT INTO ${n.identifier(e)} (${u}, ${v}, ${F}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,te=(e,t)=>e===void 0||t!==0&&t!==1||O(e)!=="boolean"?t:t===1,m=new WeakMap,re=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[o,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([o,a]))}return Object.freeze(r),m.set(e,r),r},J=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=D(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},oe=e=>{try{return J(e)}catch{return}},p=new WeakMap,ne=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{d(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{d(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},se={fieldRef:U,rangeTypeGuard:G,serialize:j};export{F as A,l as D,u as a,v as b,ee as c,Z as d,U as e,H as f,x as g,oe as h,ne as i,R as j,Y as k,D as l,se as m,i as n,f as o,C as p,q,J as r,te as s,re as t,G as u};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DzUChRJ-.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-BakYlgvb.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{e as i}from"./do-sql-BWrJQAOh.mjs";const f=(r,o)=>{const n=o-(r.after??0),e=[t`${i(r.field)} IS NOT NULL`,t`${i(r.field)} < ${n}`];return r.softDeleteField!==void 0&&e.push(t`${i(r.softDeleteField)} IS NULL`),e},L=(r,o,n,e)=>{const d=t`SELECT id FROM ${t.identifier(o.table)} WHERE ${t.join(f(o,n),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(e))+1))}`,s=l(r,d).toArray(),a=s.length>e,$=s.slice(0,e).map(E=>E.id);return{hasMore:a,ids:$}},S=(r,o,n,e)=>{const d=t`SELECT 1 AS hit FROM ${t.identifier(o.table)} WHERE id = ${n} AND ${t.join(f(o,e),t` AND `)}`;return l(r,d).toArray().length>0},c=(r,o)=>o===void 0?i(r):t`${i(o)}, ${i(r)}`,h=(r,o)=>{const n=o.softDeleteField===void 0?t``:t` WHERE ${i(o.softDeleteField)} IS NULL`,e=t`SELECT MIN(${i(o.field)}) AS expiry FROM ${t.identifier(o.table)}${n}`,d=l(r,e).toArray()[0]?.expiry;return typeof d=="number"?d+(o.after??0):void 0};export{S as isTtlExpired,h as nextTtlExpiry,L as selectExpiredIds,c as ttlIndexColumns};
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{e as i}from"./do-sql-RROYQPCM.mjs";const f=(r,o)=>{const n=o-(r.after??0),e=[t`${i(r.field)} IS NOT NULL`,t`${i(r.field)} < ${n}`];return r.softDeleteField!==void 0&&e.push(t`${i(r.softDeleteField)} IS NULL`),e},L=(r,o,n,e)=>{const d=t`SELECT id FROM ${t.identifier(o.table)} WHERE ${t.join(f(o,n),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(e))+1))}`,s=l(r,d).toArray(),a=s.length>e,$=s.slice(0,e).map(E=>E.id);return{hasMore:a,ids:$}},S=(r,o,n,e)=>{const d=t`SELECT 1 AS hit FROM ${t.identifier(o.table)} WHERE id = ${n} AND ${t.join(f(o,e),t` AND `)}`;return l(r,d).toArray().length>0},c=(r,o)=>o===void 0?i(r):t`${i(o)}, ${i(r)}`,h=(r,o)=>{const n=o.softDeleteField===void 0?t``:t` WHERE ${i(o.softDeleteField)} IS NULL`,e=t`SELECT MIN(${i(o.field)}) AS expiry FROM ${t.identifier(o.table)}${n}`,d=l(r,e).toArray()[0]?.expiry;return typeof d=="number"?d+(o.after??0):void 0};export{S as isTtlExpired,h as nextTtlExpiry,L as selectExpiredIds,c as ttlIndexColumns};
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BhK79123.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{migrateClientWatermark as P}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as H}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Q,i as Z,g as J,a as q,b as ee,A as O}from"./do-sql-RROYQPCM.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./isTtlExpired-BmiUp7MF.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class U extends X{}const F=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new U("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&F(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&F(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof U))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Q(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const M=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(M==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${t.identifier(z)} TEXT NOT NULL
5
+ )`),d(e,l(`${o}${D}`,o,g,!1)),_e(e,o,s,a),Te(e,o,s),Ae(e,o,s),Ie(e,o,s),Le(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>R(o,c.name)),...(s.rankIndexes??[]).map(c=>x(o,c.name))));return G(e,i),n.cdc&&(k(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),w(e),P(e),K(e),W(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),ne(e),v(e),j(e),Y(e),te(e),a??[]};export{Ye as runShardMigrations};
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-BjY4rnqb.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-RROYQPCM.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-BjY4rnqb.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.171",
3
+ "version": "1.0.0-alpha.173",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,9 +48,9 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
+ "@lunora/errors": ">=1.0.0-alpha.75 <2.0.0-0",
52
52
  "@lunora/platform": "1.0.0-alpha.76",
53
- "@lunora/wire": "1.0.0-alpha.3",
53
+ "@lunora/wire": "1.0.0-alpha.4",
54
54
  "drizzle-orm": "1.0.0-rc.5"
55
55
  },
56
56
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{decodeWire as T,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{e as $}from"./effective-kind-BmG_zCAy.mjs";import{S as O,i as g,s as y,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as f}from"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return h(n)?JSON.stringify(A(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return y(e)}catch(t){throw t instanceof N?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(g(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${O[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${b(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||$(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
@@ -1,5 +0,0 @@
1
- import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as P}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as H}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Z,i as J,g as Q,a as q,b as ee,A as O}from"./do-sql-BWrJQAOh.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./isTtlExpired-CozZXOL3.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends X{}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=Q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const U=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(U==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${t.identifier(z)} TEXT NOT NULL
5
- )`),d(e,l(`${o}${D}`,o,g,!1)),_e(e,o,s,a),Te(e,o,s),Ae(e,o,s),Ie(e,o,s),Le(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>R(o,c.name)),...(s.rankIndexes??[]).map(c=>x(o,c.name))));return P(e,i),n.cdc&&(k(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),w(e),B(e),K(e),W(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&G(e),ne(e),v(e),j(e),Y(e),te(e),a??[]};export{Ye as runShardMigrations};