@lunora/shard-engine 1.0.0-alpha.122 → 1.0.0-alpha.124

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 (52) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +100 -28
  3. package/dist/index.d.ts +100 -28
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-BGXP6oxh.mjs → ADMIN_FUNCTIONS-Bsvi2ytY.mjs} +1 -1
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-D77Ynq1b.mjs +1 -0
  8. package/dist/packem_shared/{CDC_LOG_TABLE-GKlDpuM2.mjs → CDC_LOG_TABLE-BPEzVAil.mjs} +1 -1
  9. package/dist/packem_shared/CURSOR_PREFIX-BztyXqNP.mjs +1 -0
  10. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs → DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs} +1 -1
  11. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs +1 -0
  12. package/dist/packem_shared/NotUniqueError-Btdx6-eQ.mjs +1 -0
  13. package/dist/packem_shared/{RANK_TIEBREAK-DrISKVKe.mjs → RANK_TIEBREAK-BKugKf70.mjs} +1 -1
  14. package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-e7viSuiO.mjs → RELATED_DEFAULT_LIMIT-Me5elP-K.mjs} +1 -1
  15. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  16. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs +1 -0
  17. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs → VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs} +1 -1
  18. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  19. package/dist/packem_shared/applyOnDelete-CGVYKtaW.mjs +1 -0
  20. package/dist/packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs +1 -0
  21. package/dist/packem_shared/{backfillAggregateIndexes-B1yVAkvK.mjs → backfillAggregateIndexes-CJrtolQ9.mjs} +1 -1
  22. package/dist/packem_shared/{buildReprojectionMigration-BnUbAUwT.mjs → buildReprojectionMigration-CRS4SNgc.mjs} +1 -1
  23. package/dist/packem_shared/{buildShapeDiff-AxUzi_GL.mjs → buildShapeDiff-C3hPtSKO.mjs} +1 -1
  24. package/dist/packem_shared/compileWhereSql-BaMGeXXq.mjs +1 -0
  25. package/dist/packem_shared/{computeRankPage-BI2lNKPu.mjs → computeRankPage-CFeFkZ_k.mjs} +1 -1
  26. package/dist/packem_shared/createCompanionSync-B7dV2y4L.mjs +1 -0
  27. package/dist/packem_shared/{createReplicaLink-CJn5lH0o.mjs → createReplicaLink-B9F5PAQ0.mjs} +1 -1
  28. package/dist/packem_shared/defineEngineContractSuite-DTLpGhSW.mjs +1 -0
  29. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  30. package/dist/packem_shared/do-sql-Cg3zXJpF.mjs +1 -0
  31. package/dist/packem_shared/{isSoftDeleted-BHlFkAsr.mjs → isSoftDeleted-BTGu2iBl.mjs} +1 -1
  32. package/dist/packem_shared/json-field-path-B2fjnGc3.mjs +1 -0
  33. package/dist/packem_shared/{materializeExternalRows-Csa8ELkU.mjs → materializeExternalRows-Cx6_A2W3.mjs} +1 -1
  34. package/dist/packem_shared/{runShardMigrations-3BBkjGHs.mjs → runShardMigrations-eqHNBW6S.mjs} +1 -1
  35. package/dist/packem_shared/{selectExpiredIds-5bAT7X28.mjs → selectExpiredIds-CilDdUr2.mjs} +1 -1
  36. package/dist/packem_shared/selectShapeMembers-CU8Kl2Bq.mjs +1 -0
  37. package/dist/packem_shared/where-sql-Dn9trjRu.mjs +1 -0
  38. package/package.json +2 -2
  39. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs +0 -1
  40. package/dist/packem_shared/AGG_COUNT-BIGZgU8U.mjs +0 -1
  41. package/dist/packem_shared/CURSOR_PREFIX-C1jsjAPd.mjs +0 -1
  42. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs +0 -1
  43. package/dist/packem_shared/NotUniqueError-thbeLn0g.mjs +0 -1
  44. package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +0 -1
  45. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-Dv9crDfv.mjs +0 -1
  46. package/dist/packem_shared/applyOnDelete-8n5PzcI0.mjs +0 -1
  47. package/dist/packem_shared/compileWhereSql-DLfUbHc-.mjs +0 -1
  48. package/dist/packem_shared/createCompanionSync-hGCzG0O1.mjs +0 -1
  49. package/dist/packem_shared/defineEngineContractSuite-eCIuMGrM.mjs +0 -1
  50. package/dist/packem_shared/do-sql-CyWszGdM.mjs +0 -1
  51. package/dist/packem_shared/selectShapeMembers-CNpeUQ-H.mjs +0 -1
  52. package/dist/packem_shared/where-sql-DFs8Zw7-.mjs +0 -1
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-thbeLn0g.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B1yVAkvK.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-GKlDpuM2.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as xe,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Me}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-hGCzG0O1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as we}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BI2lNKPu.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as nr,readDueScheduleOutbox as sr,recordScheduleOutbox as lr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as Er,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Cr,readShapePokeCursor as Rr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CNpeUQ-H.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs";import{SCAN_DEP as Fr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as wr,a as Kr,b as vr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-CyWszGdM.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as lo,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Fo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Csa8ELkU.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as wo}from"./packem_shared/isSoftDeleted-BHlFkAsr.mjs";import{f as vo,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as sa,FLAGS_FUNCTION_PREFIX as la,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as xa,listTables as Ea,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ca,recordShapeProbePass as Ra,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-BGXP6oxh.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Ma}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ka,readBookmark as Ba}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ga,applySelect as qa,buildSeekBeforeWhere as wa,buildSeekWhere as Ka,decodeCursor as va,encodeCursor as Wa,equalityPinnedFields as Xa,normalizeOrderKeys as Ha,softDeleteScope as Va,tiebreakDirectionFor as za,uniqueIndexFields as Qa}from"./packem_shared/CURSOR_PREFIX-C1jsjAPd.mjs";import{QUEUE_TABLE as ja,clearQueueMessages as Ja,isLossyBody as Za,readQueueMessageById as $a,readQueueMessages as et,recordQueueMessages as rt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as at,encodePartitionKey as tt,matchesRankStaticWhere as it,rankKeyFromDoc as nt,rankPivotConditionSql as st,rankTableName as lt,resolveRankPartition as dt,sortColumnName as ct}from"./packem_shared/RANK_TIEBREAK-DrISKVKe.mjs";import{ReactiveCache as pt,reactiveCacheKey as St}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as ft,listReactorStates as xt,migrateReactorState as Et,reactorNeedsRun as ht,readReactorState as Tt,writeReactorState as Ct}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as At,createReadFootprint as gt,markUnvouchableReads as _t}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as bt,indexKeysForRow as Lt,keysTouchRanges as Dt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Ot,whereFilter as Mt,whereOfFilter as Ft}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Nt,RELATED_DEPTH_DECAY as kt,RELATED_MAX_DEPTH as Bt,RELATED_MAX_LIMIT as Ut,deriveRelationEdges as Gt,findRelated as qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{DEFAULT_MAX_RELATION_KEYS as Kt,assertFlatPredicate as vt,assertShapeShardable as Wt,containsRelationPredicate as Xt,isRelationPredicate as Ht,resolveRelationPredicates as Vt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{applyOnDelete as Qt,distinctValues as Yt,fanOutScalarCounts as jt,relationHooks as Jt,resolveWith as Zt,runRowValidators as $t}from"./packem_shared/applyOnDelete-8n5PzcI0.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ri,clampPromotionThresholds as oi,nextPromotionState as ai,relayCountFor as ti,shapeRoutingKey as ii}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as si,OwnerRelay as li,RelayMember as di,createRelayLink as ci}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as pi,gateReplicaDispatch as Si,handleReplicaControl as ui}from"./packem_shared/createReplicaLink-CJn5lH0o.mjs";import{buildReprojectionMigration as xi,countLegacyRows as Ei,reprojectableFields as hi,reprojectionTables as Ti}from"./packem_shared/buildReprojectionMigration-BnUbAUwT.mjs";import{RLS_UNWRAP_SYMBOL as Ri,RlsRequiredError as Ai,guardWriter as gi}from"./packem_shared/RLS_UNWRAP_SYMBOL-Dv9crDfv.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ii,readSchemaHistory as bi,readSchemaVersion as Li,recordSchemaVersion as Di}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Oi}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Fi,isDevEnvironment as yi,readDeployInfo as Ni}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Bi}from"./packem_shared/buildShapeDiff-AxUzi_GL.mjs";import{ShapeDiffCache as Gi,createShapeDiffCache as qi,globalShapeReadKey as wi}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as vi,diffGlobalMembership as Wi,encodeRowsPatch as Xi,projectColumns as Hi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as zi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Yi}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as Ji}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as $i,assertReadonly as en,lintReadonlySql as rn,runReadonlySql as on}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as tn,bigintSqlKey as nn,decodeBigintSqlKey as sn,decodeFloat64SqlKey as ln,float64SqlKey as dn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as mn,subscriptionFrames as pn,subscriptionListDeltas as Sn,trySendFrame as un}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as xn,recordChangedKeys as En,writeTouchesMemo as hn}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Cn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as An}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _n,TransactionHeadroomTracker as In}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ln,runTriggers as Dn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as On}from"./packem_shared/selectExpiredIds-5bAT7X28.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Fn,backfillVectorIndexes as yn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs";import{c as kn,s as Bn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Gn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as wn,reprojectionMigrationId as Kn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Wn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Hn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as zn}from"./packem_shared/runShardMigrations-3BBkjGHs.mjs";import{stableStringify as Yn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Jn}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{ia as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,wr as AGG_COUNT,Kr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,tn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ga as CURSOR_PREFIX,An as ConflictError,R as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,sa as DEFAULT_FANOUT_TOPIC_LIMIT,Kt as DEFAULT_MAX_RELATION_KEYS,si as DEFAULT_MAX_RELAYS,ri as DEFAULT_PROMOTION_THRESHOLDS,_n as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,ho as DurableStreamRunner,la as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,ve as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,$i as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,li as OwnerRelay,ja as QUEUE_TABLE,at as RANK_TIEBREAK,ft as REACTOR_STATE_TABLE,Nt as RELATED_DEFAULT_LIMIT,kt as RELATED_DEPTH_DECAY,Bt as RELATED_MAX_DEPTH,Ut as RELATED_MAX_LIMIT,Gn as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,wn as REPROJECTION_MIGRATION_PREFIX,Ri as RLS_UNWRAP_SYMBOL,pt as ReactiveCache,di as RelayMember,Ai as RlsRequiredError,Fr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ii as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Gi as ShapeDiffCache,zi as ShardRunner,In as TransactionHeadroomTracker,At as UNVOUCHABLE_DEP,Fn as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Re as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,lo as appendStreamChunk,Y as applyCdcChanges,Qt as applyOnDelete,qa as applySelect,ue as archiveCdcSegment,ka as armRestore,vt as assertFlatPredicate,N as assertNoExplicitUndefined,en as assertReadonly,Wt as assertShapeShardable,k as assertValidClientId,mn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,yn as backfillVectorIndexes,nn as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,bt as buildIndexRange,vi as buildPokeFrames,xi as buildReprojectionMigration,wa as buildSeekBeforeWhere,Ka as buildSeekWhere,Fi as buildSettings,Bi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,oi as clampPromotionThresholds,Da as clearCapturedMail,Me as clearCompanionSignatures,Qe as clearMemoryTables,Ja as clearQueueMessages,x as coerceAggregateNumber,oe as compactCdcDocs,kn as compileWhereSql,Ze as computeRankPage,Xt as containsRelationPredicate,Ei as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,gt as createReadFootprint,ci as createRelayLink,pi as createReplicaLink,qi as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Cn as createSystemReader,ae as cursorBelowRetainedFloor,Ro as decideDurableAttach,sn as decodeBigintSqlKey,va as decodeCursor,ln as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,Er as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Gt as deriveRelationEdges,bo as diffExternalSource,Wi as diffGlobalMembership,Yt as distinctValues,E as encodeAggregateKey,Wa as encodeCursor,$o as encodeGeohash,tt as encodePartitionKey,Xi as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,Xa as equalityPinnedFields,o as exportShardRows,ua as facetColumn,jt as fanOutScalarCounts,qt as findRelated,fa as findStorageReferences,po as finishStreamRun,dn as float64SqlKey,h as foldAggregateTally,ar as forgetScheduleOutbox,vo as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Si as gateReplicaDispatch,Vr as geoTableName,wi as globalShapeReadKey,zo as groupUnmappedRows,gi as guardWriter,ui as handleReplicaControl,Ln as hasTrigger,ea as haversineMeters,a as importShardRows,Lt as indexKeysForRow,yi as isDevEnvironment,zr as isFtsAvailable,Wn as isInternalTableName,Za as isLossyBody,Ye as isMemoryTable,Ot as isPushableWhere,Ht as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,xa as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Dt as keysTouchRanges,Do as liftSourceId,rn as lintReadonlySql,xt as listReactorStates,Ea as listTables,_t as markUnvouchableReads,it as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,xn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,Et as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,Cr as minShapePokeCursor,ai as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ha as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,ra as pointInBoundingBox,nr as probeScheduleOutbox,Hi as projectColumns,qo as pullExternalSourceIncrementalTick,wo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,Hn as quoteIdentifier,nt as rankKeyFromDoc,st as rankPivotConditionSql,lt as rankTableName,St as reactiveCacheKey,ht as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Ba as readBookmark,Oa as readCapturedMail,Ee as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ni as readDeployInfo,sr as readDueScheduleOutbox,No as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,$a as readQueueMessageById,et as readQueueMessages,Tt as readReactorState,bi as readSchemaHistory,Li as readSchemaVersion,Sr as readSearchBackfillState,Rr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,ha as readTablePage,Ma as recordCapturedMail,En as recordChangedKeys,Ta as recordFanoutPass,Ca as recordGlobalPollPass,rt as recordQueueMessages,lr as recordScheduleOutbox,Di as recordSchemaVersion,Ra as recordShapeProbePass,Jt as relationHooks,ti as relayCountFor,to as renderSql,hi as reprojectableFields,Kn as reprojectionMigrationId,Ti as reprojectionTables,dt as resolveRankPartition,$e as resolveRankSeekTuple,Vt as resolveRelationPredicates,Zt as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,on as runReadonlySql,$t as runRowValidators,zn as runShardMigrations,Ji as runSocketPool,Gr as runSql,Dn as runTriggers,On as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Oi as serializeSqlValue,Bn as serverInList,ii as shapeRoutingKey,Va as softDeleteScope,ct as sortColumnName,io as sqliteInList,Yn as stableStringify,Jn as stableWireKey,G as stripReservedPatchFields,Yi as stubByName,pn as subscriptionFrames,Sn as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,za as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,xo as trimStreamRuns,eo as tryRowToDocument,un as trySendFrame,no as unionAll,Qa as uniqueIndexFields,s as validateImportRow,Mt as whereFilter,Ft as whereOfFilter,he as writeCdcArchivedThrough,we as writeGlobalShapeSnapshot,Ve as writeIdempotent,Ct as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,hn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-Btdx6-eQ.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-CJrtolQ9.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as se,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-BPEzVAil.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-B7dV2y4L.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-CFeFkZ_k.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as sr,probeScheduleOutbox as ir,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Cr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CU8Kl2Bq.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-Cg3zXJpF.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as so,unionAll as io}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Cx6_A2W3.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-BTGu2iBl.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as ia,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as ha,listTables as xa,readTablePage as Ea,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Ca,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-Bsvi2ytY.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-BztyXqNP.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as st,isLossyBody as it,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as ht,resolveRankPartition as xt,sortColumnName as Et}from"./packem_shared/RANK_TIEBREAK-BKugKf70.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as es,resolveRelationPredicates as rs}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs";import{describeRelationWrites as as}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ss,distinctValues as is,fanOutScalarCounts as ls,relationHooks as ns,resolveWith as ds,runRowValidators as cs}from"./packem_shared/applyOnDelete-CGVYKtaW.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ps,clampPromotionThresholds as Ss,nextPromotionState as us,relayCountFor as fs,shapeRoutingKey as hs}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-B9F5PAQ0.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-CRS4SNgc.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Ws,isDevEnvironment as Xs,readDeployInfo as Hs}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zs}from"./packem_shared/buildShapeDiff-C3hPtSKO.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as ti}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ii}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as ni}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ci,assertReadonly as mi,lintReadonlySql as pi,runReadonlySql as Si}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as fi,bigintSqlKey as hi,decodeBigintSqlKey as xi,decodeFloat64SqlKey as Ei,float64SqlKey as Ti}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Oi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ni,TransactionHeadroomTracker as ki}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-CilDdUr2.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-Dn9trjRu.mjs";import{RELATION_EXISTS_KEY as Qi}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ji,reprojectionMigrationId as Ji}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as $i}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as rl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as al}from"./packem_shared/runShardMigrations-eqHNBW6S.mjs";import{stableStringify as sl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ll}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{sa as ADMIN_FUNCTIONS,ia as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,fi as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Mi as ConflictError,C as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Es as DEFAULT_MAX_RELAYS,ps as DEFAULT_PROMOTION_THRESHOLDS,Ni as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,ci as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ts as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Qi as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ji as REPROJECTION_MIGRATION_PREFIX,Ms as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Rs as RelayMember,ys as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bs as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Ys as ShapeDiffCache,ti as ShardRunner,ki as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Ki as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ss as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,mi as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Ci as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Wi as backfillVectorIndexes,hi as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$s as buildPokeFrames,Ls as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Ws as buildSettings,zs as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Ss as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,st as clearQueueMessages,h as coerceAggregateNumber,oe as compactCdcDocs,Hi as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Ds as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Cs as createRelayLink,gs as createReplicaLink,js as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Oi as createSystemReader,ae as cursorBelowRetainedFloor,Co as decideDurableAttach,xi as decodeBigintSqlKey,Qa as decodeCursor,Ei as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,as as describeRelationWrites,bo as diffExternalSource,ei as diffGlobalMembership,is as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,ri as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ls as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,Ti as float64SqlKey,E as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_s as gateReplicaDispatch,Vr as geoTableName,Js as globalShapeReadKey,zo as groupUnmappedRows,Ns as guardWriter,Is as handleReplicaControl,Ui as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xs as isDevEnvironment,zr as isFtsAvailable,$i as isInternalTableName,it as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,es as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,ha as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,pi as lintReadonlySql,_t as listReactorStates,xa as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,bi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,se as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,us as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,sr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,ir as probeScheduleOutbox,oi as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,rl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,ht as rankTableName,Ct as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hs as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Us as readSchemaHistory,Gs as readSchemaVersion,Sr as readSearchBackfillState,Cr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,Ea as readTablePage,Fa as recordCapturedMail,Li as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,ws as recordSchemaVersion,Ca as recordShapeProbePass,ns as relationHooks,fs as relayCountFor,to as renderSql,Ps as reprojectableFields,Ji as reprojectionMigrationId,Os as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,rs as resolveRelationPredicates,ds as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,Si as runReadonlySql,cs as runRowValidators,al as runShardMigrations,ni as runSocketPool,Gr as runSql,Gi as runTriggers,qi as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vs as serializeSqlValue,Vi as serverInList,hs as shapeRoutingKey,et as softDeleteScope,Et as sortColumnName,so as sqliteInList,sl as stableStringify,ll as stableWireKey,G as stripReservedPatchFields,ii as stubByName,Ai as subscriptionFrames,gi as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,ho as trimStreamRuns,eo as tryRowToDocument,_i as trySendFrame,io as unionAll,ot as uniqueIndexFields,l as validateImportRow,wt as whereFilter,qt as whereOfFilter,Ee as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,Di as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{sql as x}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{m as A,n as j}from"./do-sql-CyWszGdM.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{d as U}from"./wire-codec-BYCSiazv.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={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",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...U(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${j(e)}`]}},z=/^-?\d+$/u,Z=(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(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(x.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(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}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
1
+ import{LunoraError as S}from"@lunora/errors";import{sql as x}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as j}from"./do-sql-Cg3zXJpF.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{d as U}from"./wire-codec-BYCSiazv.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={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",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...U(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${j(e)}`]}},z=/^-?\d+$/u,Z=(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(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(x.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(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}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{r as f}from"./json-field-path-B2fjnGc3.mjs";const a=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},d=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=f(e,n)??null;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==(t.eq??null))return!1;continue}return!1}if(o!==t)return!1}return!0},y=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>a.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},A=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},w={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,A as aggregateSqlFunction,d as matchesStaticWhere,y as normalizeCountArgument,w as throwingScheduler};
@@ -0,0 +1 @@
1
+ import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-B2fjnGc3.mjs";import{A as i,a as n,b as d,D as m,n as p,c as u,d as q,l as G,s as c,m as S,k as f,g as A,i as D,j as h,e as T,p as _,u as g,q as j,f as y,r as C,t as O,h as b}from"./do-sql-Cg3zXJpF.mjs";import{quoteIdentifier as I}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BYCSiazv.mjs";import"./runDrizzle-Du5HLitO.mjs";import{serializeSqlValue as N}from"./serializeSqlValue-BbZ5hKM7.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";export{i as AGG_COUNT,n as AGG_KEY,d as AGG_VALUE,m as DOC_COLUMN,p as DOC_ORIGINALS_KEY,u as aggUpsertSql,q as createIndexSql,G as decodeDocJson,c as decodeGroupKeyValue,S as doWhereSqlStrategy,f as encodeDocJson,A as geoTableName,D as isFtsAvailable,h as jsonPath,T as jsonPathSql,_ as jsonTypeGuard,g as jsonTypeGuardSql,j as qualifiedJsonPath,y as qualifiedJsonPathSql,I as quoteIdentifier,C as rowToDocument,N as serializeSqlValue,O as tableColumns,b 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 A,runDrizzle as n}from"./runDrizzle-Du5HLitO.mjs";import{k as m,l as u}from"./do-sql-CyWszGdM.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
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 A,runDrizzle as n}from"./runDrizzle-Du5HLitO.mjs";import{k as m,l as u}from"./do-sql-Cg3zXJpF.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{v as p}from"./accepts-null-D1zmJbyR.mjs";import{r as O}from"./json-field-path-B2fjnGc3.mjs";import{d as _,e as E}from"./wire-codec-BYCSiazv.mjs";import{SEEK_RANGE as A}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||p(n)},T=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(T.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},I=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",D=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},L=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!D(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=L(c,s,t),{direction:a}=u;l=a,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||I(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,v=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},C=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},f="~4",z=(e,t)=>{const n=t.map(r=>O(e,r.field)??null);return n.push(e._id),f+v(JSON.stringify(E(n)))},d=()=>new S("BAD_REQUEST","invalid cursor"),G=e=>{if(!e.startsWith(f))throw d();let t;try{t=_(JSON.parse(C(e.slice(f.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[A]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const a=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?a:{OR:[a,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],Q=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},X=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,Y=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{f as CURSOR_PREFIX,Q as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,C as fromBase64,Y as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,X as softDeleteScope,h as tiebreakDirectionFor,v as toBase64,x as uniqueIndexFields};
@@ -1,4 +1,4 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-Bdh5JSdg.mjs";import{runSql as E}from"./runDrizzle-Du5HLitO.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-Bdh5JSdg.mjs";import{runSql as E}from"./runDrizzle-Du5HLitO.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{i as M,R as P}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as O}from"./clearMemoryTables-CogAvVHR.mjs";import{normalizeOrderKeys as S,uniqueIndexFields as _,equalityPinnedFields as L,buildSeekWhere as k,decodeCursor as K,softDeleteScope as D}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{distinctValues as I}from"./applyOnDelete-CGVYKtaW.mjs";import{RELATION_EXISTS_KEY as B}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R={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}},v=e=>P.has(e)?e:void 0,y=e=>{const t=v(e),r=t===void 0?void 0:R[t];if(!r)throw new f("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},F=5e3,u=Symbol("relation-key-overflow"),g=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>M(e),h=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?g(s).some(a=>h(a,t,r)):o==="NOT"?h(s??{},t,r):!!n[o]&&p(s)})},ne=(e,t,r,n)=>{if(e&&h(e,t,r))throw new f("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},T=async(e,t,r,n,o)=>{const s=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),limit:o,relationBaseWhere:n.relationBaseWhere,where:s});return{keys:I(a,r),rows:a.length}},N=(e,t,r,n=!1)=>{throw new f("INTERNAL",`relation predicate on "${e.table}" matched ${n?"at least ":""}${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},W=async(e,t,r,n,o)=>{const{keys:s}=await T(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?u:N(e,s.length,n)},w=async(e,t,r,n)=>{const{keys:o,rows:s}=await T(e,t,r,n,n.maxRelationKeys+1);return s>n.maxRelationKeys?N(e,s,n,!0):o},q=async(e,t,r,n,o)=>{const s=y(e),{clause:a,project:d}=C(t),i=await W(t,s.negateChild?{NOT:r}:r,d,n,o);return i===u?u:s.negated?s.nullDisjunct?{OR:[{[a]:{notIn:i}},{[a]:{isNull:!0}}]}:{[a]:{notIn:i}}:{[a]:{in:i}}},H=async(e,t,r,n)=>{const o=y(e),{from:s,table:a,to:d}=t.through,i=await w(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await w({table:a},{[d]:{in:i}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const s=y(e),a=o.relationBaseWhere?.(t.table),d=s.negateChild?{NOT:r}:r,j={childWhere:await l(a?{AND:[a,d]}:d,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[B]:j}},Y=(e,t,r)=>{const n=v(e),o=n===void 0?void 0:R[n];if(o&&o.kind!==r.kind)throw new f("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const s=[];for(const a of Object.keys(r)){Y(a,e,t);const d=r[a]??{};if(t.through!==void 0){s.push(await H(a,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){s.push(await E(a,t,d,n,o));continue}const c=await q(a,t,d,o,i);c===u?s.push(await E(a,t,d,n,o)):s.push(c)}return A(s)},z=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const a of g(t))s.push(await l(a,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&p(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 z(o,e[o],t,r));return A(n)},Q=async(e,t)=>!e||!h(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??F,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),oe=async(e,t,r)=>{const n=S(t.orderBy,e.shape,{pinned:L(t.where),uniqueBy:_(e.indexes,e.shape)}),o=t.cursor?k(n,K(t.cursor)):void 0;let s=b(t.baseWhere,t.where);s=b(s,D(e.softDeleteMode,t.includeDeleted)),s=await Q(s,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(s=s?{AND:[s,o]}:o);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:s}},m=(e,t,r)=>{for(const n of e){const o=$(n,t,r);if(o)return o}},X=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(g(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!p(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],a=s.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(a!==void 0)return{kind:"shard",relation:e,target:a};const d=s.find(i=>O(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},$=(e,t,r)=>{for(const n of Object.keys(e)){const o=X(n,e[n],t,r);if(o)return o}},U=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!h(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(O(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=$(e,t,r);if(!n){U(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{F as DEFAULT_MAX_RELATION_KEYS,ne as assertFlatPredicate,se as assertShapeShardable,oe as composeReadPredicate,h as containsRelationPredicate,p as isRelationPredicate,Q as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Sn,l as Fe,h as _n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as Rn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as Ct}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{backfillAggregateIndexes as ni,backfillRankIndexes as ri,backfillSearchIndexes as oi}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{CDC_LOG_TABLE as si,applyCdcChanges as ci,bumpCdcEpoch as ai,cdcCanVouchFor as di,cdcForkedError as li,cdcSeqLeavingRows as ui,cdcTouchesTables as fi,cdcTrimmedError as hi,compactCdcDocs as wi,cursorBelowRetainedFloor as pi,minCdcReplayableSeq as gi,minCdcSeq as yi,readCdcChangeKeys as $i,readCdcChanges as Ei,readCdcCursor as mi,readCdcEpoch as Si,trimCdcChanges as _i}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-B7dV2y4L.mjs";import{isMemoryTable as xt}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as bt}from"./computeRankPage-CFeFkZ_k.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as G}from"./runDrizzle-Du5HLitO.mjs";import{p as qn,j as ct,D as oe,r as Te,k as le,b as We,A as nt,a as Be,m as fe,e as he,s as Wn,t as tn,i as Bn,q as Mt,h as nn,g as Pn}from"./do-sql-Cg3zXJpF.mjs";import{renderSql as rn,unionAll as ut,WORKERD_SQLITE_LIMITS as on,sqliteInList as Un}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as On,boundingBoxGeohashes as Hn,haversineMeters as Gn,pointInBoundingBox as jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Kn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Nn,assertPatchAllowed as Qn,operatorFields as Vn,readPatchField as Dt}from"./assertPatchAllowed-BJ_2LgkQ.mjs";import{tiebreakDirectionFor as Jn,encodeCursor as He,nullsOrderSuffix as zn,normalizeOrderKeys as kt,uniqueIndexFields as Yn,buildSeekWhere as Xn,decodeCursor as Lt,buildSeekBeforeWhere as Zn,softDeleteScope as Re,applySelect as Ft}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as qt,sortColumnName as Wt,resolveRankPartition as er,encodePartitionKey as tr,RANK_TIEBREAK as nr,rankPivotConditionSql as rr}from"./RANK_TIEBREAK-BKugKf70.mjs";import{UNVOUCHABLE_DEP as Bt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as or,buildIndexRange as ir}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as ve,c as X,t as je,i as Pt}from"./where-sql-Dn9trjRu.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ie}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as sr,isPushableWhere as cr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ar,findRelated as dr}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{assertFlatPredicate as rt,resolveRelationPredicates as lr,composeReadPredicate as ur}from"./DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs";import{describeRelationWrites as fr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as ot,resolveWith as Ut,relationHooks as Ot,applyOnDelete as hr,fanOutScalarCounts as wr}from"./applyOnDelete-CGVYKtaW.mjs";import{guardWriter as pr}from"./RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{mayHoldProjectedValue as gr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as yr}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $r}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ti,migrateClientWatermark as vi,readClientWatermark as Ai}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as Ci,readIdempotent as xi,trimIdempotent as bi,writeIdempotent as Mi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as ki}from"./runShardMigrations-eqHNBW6S.mjs";import{selectShapeMembers as Fi,selectShapeRows as qi}from"./selectShapeMembers-CU8Kl2Bq.mjs";const Er=n=>{const i=atob(n),r=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},mr=()=>new y("BAD_REQUEST","invalid cursor"),Ht=16,Gt=8,z=1024,ft=(n,i)=>i.query(n),Sr=(n,i)=>{if(n.length===0)return 0;let r=0;for(const[a,s]of i.entries()){const w=a===i.length-1;let A=0;for(const T of n)(w?T.startsWith(s):T===s)&&(A+=1);if(A===0)return 0;r+=A}return r},_r=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},Rr=(n,i,r)=>{const a={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>=Gt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Gt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const A=n;if(s!==A.definition.field)throw new y("INTERNAL",`search index "${A.indexName}" on table "${i}" indexes "${A.definition.field}", not "${s}"`);const T=ft(w,r).length;if(T>Ht)throw new y("BAD_REQUEST",`search index "${A.indexName}" on table "${i}": at most ${String(Ht)} search terms are supported (got ${String(T)})`);return A.field=s,A.query=w,A.hasQuery=!0,a}};return a},Tr=n=>{if(n.length>z)throw new y("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},vr=n=>Math.min(n.offset+n.numItems+1,z),Ar=n=>btoa(`search:${String(n)}`),Ir=n=>{let i;try{i=Er(n)}catch{return}if(!i.startsWith("search:"))return;const r=Number(i.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},Cr=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)),r=n.cursor?Ir(n.cursor):0;if(r===void 0)throw mr();if(r+i>=z)throw new y("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:r}},xr=(n,i)=>{const r=i.offset+i.numItems,a=i.numItems>0&&n.length>r;return{continueCursor:a?Ar(r):null,isDone:!a,page:n.slice(i.offset,r)}},br=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new y("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Mr=32,Dr=1024,sn=(n,i,r,a)=>{const s=`SELECT id, _creationTime, ${Ie(oe)} FROM ${Ie(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return i===void 0?Ge(`${s} ${w}`):ve(`${s} WHERE `,i,` ${w}`)},Ke={fieldRef:n=>Ge(ct(n)),rangeTypeGuard:(n,i)=>Ge(qn(n,i)),serialize:Ae},kr=n=>n===void 0?"":zn(n==="first"),cn=n=>{const i=n.map(r=>`${ct(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${kr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||i.push(`${ct("id")} ${Jn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Lr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Fr=n=>{const i=an(n);let r=0;for(;r<n.indexFields.length&&i.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},qr=(n,i)=>{const r=n.order,a=Fr(n),{shape:s}=i;return a.length>0?kt(a.map(w=>({[w]:r})),s,{pinned:an(n),uniqueBy:Yn(i.indexes,s)}):kt([{_creationTime:r}],s)},Wr=(n,i,r,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Lr[w.comparator]??"eq"]:w.value}}));if(r&&s.push(Xn(i,Lt(r))),a&&s.push(Zn(i,Lt(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},Br=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Mr):n.want},at=(n,i,r,a,s,w,A)=>{const T=qr(a,r),b=cn(T),g=[],{filters:k,want:v}=w;let C=w.cursor??void 0,x=Br(w);if(v===0)return{documents:g,orderKeys:T};for(;;){const U=X(Wr(a,T,C,w.endCursor),Ke,je),q=sn(i,s&&U?ve(U," AND ",s):s??U,b,x),F=we(n,q.text,...q.params).toArray();let W={};A(F.length);for(const j of F)if(W=Te(j),k.every(L=>L(W))&&g.push(W)===v)return{documents:g,orderKeys:T};if(x===void 0||F.length<x)return{documents:g,orderKeys:T};C=He(W,T),x=Math.max(x,Math.min(x*2,Dr))}},Pr=(n,i,r,a,s,w,A,T)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:U,orderKeys:q}=at(n,i,r,a,w,{cursor:s.cursor,endCursor:s.endCursor,filters:A.all,selective:A.selective,want:void 0},T),F=U.length>=2?U[Math.floor(U.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:U,splitCursor:F?He(F,q):null}}const{documents:g,orderKeys:k}=at(n,i,r,a,w,{cursor:s.cursor,filters:A.all,selective:A.selective,want:b+1},T),v=g.length>b,C=v?g.slice(0,b):g,x=C.at(-1);return{continueCursor:v&&x?He(x,k):null,isDone:!v,page:C}},Ne=n=>{const i=new Map;return r=>{const a=i.get(r);if(a!==void 0)return a;const s=n(Ie(r));return i.set(r,s),s}},pe=Ie(oe),Ur=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),jt=Ne(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Or=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),Hr=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Gr="SELECT changes() AS changed",Kt=new Map,jr="",Kr=n=>{const i=JSON.stringify(n),r=Kt.get(i);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${jr}`),{sql:s}=rn("sqlite",c`${ut(a)} LIMIT 1`);return Kt.set(i,s),s},Nr=(n,i)=>i.map(()=>n),Qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Vr=n=>{if(!Qr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Nt=50,dn=500,Pe=Math.floor(on.boundParams/3),_e=on.boundParams,Jr=128,ue=(n,i,r)=>{const a=i??dn;if(n>a)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},zr=n=>{const i={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),i),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),i),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),i),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),i),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),i)};return i},Yr=n=>Math.max(n,z),ln=(n,i)=>{const r=n.filters.map(a=>c`${he(a.field)} = ${Ae(a.value)}`);return i&&r.push(i),r},Xr=(n,i,r,a,s)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const A=Sn(i,r.indexName),T=`${A}__vocab`,b=w.length-1,g=w.map((q,F)=>{const W=_r(q,F===b),j=W.exact?c`${c.identifier("term")} = ${W.lower}`:c`${c.identifier("term")} >= ${W.lower} AND ${c.identifier("term")} < ${W.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(T)} WHERE ${j} GROUP BY ${c.identifier("doc")}`}),k=w.map((q,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(k,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(g)}) u JOIN ${c.identifier(A)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(k.map(q=>c`${q} > 0`),c` AND `)}`,C=ln(r,s);let x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(i)} m ON m.id = s.${c.identifier(Fe)}`;C.length>0&&(x=c`${x} WHERE ${c.join(C,c` AND `)}`),x=c`${x} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const U=[];for(const q of G(n,x)){const F=nn(q);if(F){const W=q.__score__;U.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return U},Zr=(n,i,r,a,s)=>{const w=lt(r.definition.language),A=ft(r.query,w);if(A.length===0)return[];const T=ln(r,s);let b=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(i)}`;T.length>0&&(b=c`${b} WHERE ${c.join(T,c` AND `)}`),b=c`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Yr(a)))}`;const g=G(n,b).toArray(),k=[];for(const v of g){const C=nn(v);if(!C)continue;const x=Sr(_n(C,r.definition),A);x>0&&k.push({creationTime:typeof C._creationTime=="number"?C._creationTime:0,doc:C,id:typeof C._id=="string"?C._id:"",score:x})}return k.sort((v,C)=>C.score-v.score||C.creationTime-v.creationTime||v.id.localeCompare(C.id)),k.slice(0,a).map(v=>({document:v.doc,score:v.score}))},it=(n,i,r,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${r}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},eo=(n,i)=>{const r=n,a={near:(s,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s,".near() point",i,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s.sw,".within() sw corner",i,r.indexName),it(s.ne,".within() ne corner",i,r.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.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 "${r.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 r.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},to=(n,i)=>{const r=n[i];if(r===null||typeof r!="object")return;const{lat:a,lng:s}=r;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},no=(n,i)=>{const r=to(n,i.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Gn(i.near.point,r);return s<=i.near.radiusMeters?{creationTime:a,distance:s}:void 0}return jn(r,i.within)?{creationTime:a,distance:0}:void 0},ro=(n,i,r,a)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=r.near?On(r.near.point,r.near.radiusMeters):Hn(r.within),w=Pn(i,r.indexName),A=s.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),T=[c`(${c.join(A,c` OR `)})`];a&&T.push(a);const b=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(i)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(T,c` AND `)}`,g=G(n,b).toArray(),k=[];for(const v of g){const C=Te(v),x=C?no(C,r):void 0;C&&x&&k.push({creationTime:x.creationTime,distance:x.distance,doc:C})}return k.sort((v,C)=>v.distance-C.distance||C.creationTime-v.creationTime),k},un=(n,i,r,a)=>{const s=[];for(const w of n)if(i.every(A=>A(a(w)))&&(s.push(w),typeof r=="number"&&s.length>=r))break;return s},oo=(n,i,r,a,s,w=()=>{})=>{const A=r.within!==void 0,T=ro(n,i,r,s).map(b=>({distanceMeters:A?null:b.distance,document:b.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Qt=(n,i,r,a,s,w,A=()=>{})=>{const{geo:T}=r;if(!T)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,g=oo(n,i,T,b?void 0:w,a,A);return b?un(g,s,w,k=>k.document):g},Vt=(n,i,r)=>{const a=n.shape[i];if(a!==void 0&&gr(a))throw new y("BAD_REQUEST",`${r}: "${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)`)},io=n=>{let i=0;const r=[],a={...Ke,relationExists:s=>{const{childWhere:w,negated:A,parentTable:T,relation:b}=s,g=`__rel_${String(i)}`,k=r.at(-1)??T;i+=1,n(b.table,O);const v=b.kind==="one"?b.field:b.references,C=b.kind==="one"?b.references:b.field,x=Ge(`${Mt(g,C)} = ${Mt(k,v)}`);r.push(g);const U=X(w,a,je);r.pop();const q=U===void 0?x:ve(x," AND ",U),F=ve("EXISTS (SELECT 1 FROM ",Pt(b.table)," AS ",Pt(g)," WHERE ",q,")");return A?ve("NOT ",F):F}};return a};class so extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const co=/\s/u,ao=String.fromCodePoint(0),Jt=(n,i,r)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof r!="string"||r.length===0||co.test(r)||r.includes(ao)?null:r},fn=(n,i,r,a=()=>{},s=()=>{},w=()=>{},A)=>{const T=i.tables[r];if(!T)throw new y("INTERNAL",`unknown table: ${r}`);const b=Re(T.softDeleteMode,void 0),g=A??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const $=N(b,g.pushedWhere);return $?X($,fe):void 0},v=()=>{const $=N(b,g.pushedWhere);return $?X($,Ke,je):void 0},C=()=>[...g.inMemoryFilters,...g.verifyFilters];let x=0;const U=$=>{const{search:I}=g;if(!I)throw new y("INTERNAL","runSearchFetch called without a staged search");xn(n,r,T);const M=g.inMemoryFilters.length>0,D=br(M?void 0:$),Q=Bn(n);if(Q&&!bn(n,r,I.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ge=k(),ie=Q?Xr(n,r,I,D,ge):Zr(n,r,I,D,ge);!M&&$===void 0&&Tr(ie);const re=C();return x=ie.length,re.length>0?un(ie,re,$,se=>se.document):ie},q=$=>U($).map(I=>I.document),F=$=>{const I=Cr($);return xr(q(vr(I)),I)},W=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(ir(r,g.indexName,g.indexFields,g.sqlConditions,Ae))},j=$=>{W();let I=0;const M=(()=>{if(g.search){const D=q($);return I=x,D}return g.geo?Qt(n,r,g,k(),C(),$,D=>{I=D}).map(D=>D.document):at(n,r,T,g,v(),{filters:C(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},D=>{I+=D}).documents})();return w(Math.max(I,M.length)),M},L=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const I=(()=>{if(g.search){const M=U(void 0);return $=x,M}return Qt(n,r,g,k(),C(),void 0,M=>{$=M})})();return w(Math.max($,I.length)),I},J={async*[Symbol.asyncIterator](){const $=fn(n,i,r,a,s,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let I;for(;;){const M=await $.paginate({cursor:I??null,numItems:Jr});if(yield*M.page,M.isDone||M.continueCursor===null)return;I=M.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return L()},filter($){const I=sr($);return I!==void 0&&cr(I,T.shape)?(g.pushedWhere=N(g.pushedWhere,I),g.verifyFilters.push($)):g.inMemoryFilters.push($),J},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",J},async paginate($){let I=0;if(W(),g.search){const D=F($);return w(D.page.length),D}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Pr(n,r,T,g,$,v(),{all:C(),selective:g.inMemoryFilters.length>0},D=>{I+=D});return w(Math.max(I,M.page.length)),M},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new so(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,I){const M=(T.geoIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);a(r,$,"geo");const D={definition:M,indexName:$};if(g.geo=D,I(eo(D,r)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return J},withIndex($,I){const M=T.indexes.find(D=>D.name===$);if(!M)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return a(r,$,"index"),g.indexName=$,g.indexFields=M.fields,I&&I(zr(g)),J},withSearchIndex($,I){const M=(T.searchIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);a(r,$,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=D,I(Rr(D,r,lt(M.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return J}};return J},zt=(n,i,r)=>{const a={...i};for(const[s,w]of tn(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:r});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},st=(n,i,r,a)=>{const s=r;for(const[w,A]of tn(n)){if(A.serverDefault){w in i&&(s[w]=A.serverDefault({auth:a}));continue}A.onUpdateFn&&!(w in i)&&(s[w]=A.onUpdateFn())}},Yt=5,Xt=(n,i)=>{for(const r of Object.keys(i))if(i[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Zt=["_commitSeq","_creationTime","_id"],Ue=n=>Zt.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!Zt.includes(i))):n,lo=/unique constraint failed/i,uo=n=>n instanceof Error&&lo.test(n.message),fo=/string or blob too big/iu,ho=(n,i)=>{if(!(!(n instanceof Error)||!fo.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.`)},dt=(n,i,r,a)=>{try{we(n,r,...a)}catch(s){throw uo(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(ho(s,i),s)}},Oe=(n,i,r,a)=>{if(dt(n,i,r,a),we(n,Gr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},en=(n,i,r,a,s,w,A)=>{const T=[];for(let v=0;v<r.length+1;v+=1){const C=r[v],x=a[v],U=x?.direction==="desc"?"desc":"asc",q=C===void 0||x===void 0?c`${c.identifier(nr)} < ${A}`:rr(C,w[v],U,!1);if(q===void 0)continue;const F=[];for(let j=0;j<v;j+=1)F.push(c`${c.identifier(r[j])} IS ${w[j]}`);F.push(q);const[W]=F;T.push(F.length===1&&W!==void 0?W:c`(${c.join(F,c` AND `)})`)}const b=T.length>0?c.join(T,c` OR `):c`1 = 0`,g=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:g.c,total:k.c}},Zo=n=>{const{baselineSeq:i,onStalePatchDropped:r}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),A=ar(s),T=fr(s,n.inTransaction);let b;const g=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((b===void 0||!g())&&(b=kn(a)),{[Ln]:b}),v=(e,...t)=>{const o=s.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...or(o,h,Ae));return u.length>0?u:void 0},{headroom:C}=n;let x=!1;const U=async e=>{const t=x;x=!0;try{return await e()}finally{x=t}},q=n.onRead??(()=>{}),F=e=>{xt(s.tables[e])&&q(Bt,Bt)},W=n.onReadRange??(e=>{q(e.table,O)}),j=e=>{F(e.table),W(e)},L=(e,t)=>{t!==void 0&&t!==O&&!x&&C?.recordRead(1),F(e),q(e,t)},J=n.onIndexUse??(()=>{}),$=n.onWrite??(()=>{}),I=e=>{x||C?.recordWrite(e)},M=async e=>{I(e.doc),await $(e)},{cache:D}=n,Q=n.clock??(()=>Date.now()),ge=n.idGenerator??(()=>crypto.randomUUID()),ie=n.scheduler??Tn,{globalDb:re}=n,se=n.auth??{identity:null,userId:null},ht=n.cdc??!1,Qe=ie,hn=yr({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),ye=(e,t,o,u)=>{ht&&!xt(s.tables[e])&&Mn(a,Q(),e,t,o,u)},wt=(e,t,o,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!ht)return!1;const f=i?.();if(f===void 0)return!1;const d=Dn(a,e,t,f);if(d===void 0)return!1;const l=Vn(h,o);return Object.keys(Ue(o)).some(p=>!l.has(p)&&Ct(Dt(d,p))!==Ct(Dt(u,p)))},ce=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}return B},Ve=e=>pt(e,"cascade"),K=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}},gt=async(e,t,o,u,h)=>{h&&I(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},Je=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ce(e)&&L(e,O),Je(e,t)),wn=e=>!ce(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,o)=>lr(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:o,schema:s,tableName:t}),St=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return L(e,O),wr((_,H)=>h.count(_,H),e,t,o,u);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const d=Re(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),R=await Ce(p,e,void 0),E=X(R,fe),S=he(t);let m=c`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(m=c`${m} WHERE ${E}`),m=c`${m} GROUP BY ${S}`;const P=G(a,m).toArray();return new Map(P.map(_=>[_.__fk__,_.count]))};let xe=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const o of Object.values(t.triggerMap??{}))_t.add(`${e} ${o.timing} ${o.op}`);const Z=(e,t,o)=>_t.has(`${e} ${t} ${o}`),ee=async(e,t,o)=>{if(xe+=1,xe>Nt)throw xe-=1,new ae(`trigger recursion exceeded ${String(Nt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await $r({ctx:En,event:o,op:t,schema:s,tableName:o.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:$e,ensureBackfilledIndex:ze,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:Ee,syncAggregates:be,syncCompanionsForInsert:Rt,syncGeo:Me,syncRanks:me,syncSearch:De}=Fn({broadcast:w,indexKeysFor:(e,t)=>v(e,t),invalidateCache:(e,t,o)=>D?.invalidate(e,t,v(e,o)),recordCdc:ye,schema:s,sql:a}),Tt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Se=e=>e===void 0||ce(e)?re:void 0,te=(e,t)=>{const o=vt(t);for(let u=0;u<o.length;u+=_e){const h=o.slice(u,u+_e),[f]=we(a,Kr(h),...Nr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=Te(f);if(typeof d!="string"||!l)return;const p=f[oe];return{docJson:typeof p=="string"?p:le(p??{}),row:l,tableName:d}}},pn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=vt(t);for(let f=0;f<h.length;f+=_e){const d=h.slice(f,f+_e),l=Math.floor(_e/d.length),p=Un(c`${c.identifier("id")}`,o,!1,l),R=d.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of G(a,ut(R))){const{id:S,__t__:m}=E;typeof m=="string"&&typeof S=="string"&&u.set(S,m)}}return u},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:L,rowToDocument:Te,schema:s,sql:a},gn=(e,t,o)=>{const u=X(o,fe);return u===void 0||G(a,c`SELECT 1 FROM ${c.identifier(e)} WHERE ${c.identifier("id")} = ${t} AND ${u}`).toArray().length>0},yn=(e,t,o,u)=>wt(e,t,o,u)?(r?.({fields:Object.keys(Ue(o)),id:t,table:e}),!0):!1,$n=async(e,t,o,u,h)=>{const f=te(t,e);if(!f)return{applied:!1,doc:null};if(L(e,t),!gn(e,t,o.where)||yn(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:te(t,e)?.row??null}},It=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await ur(t,o,{canPushExists:Et?wn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,schema:s,tableName:e}),p=Et?io(u):Ke,R=X(l,p,je),E=sn(e,R,cn(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:hn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return L(e,O),o.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return B.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`);L(e,O);const h=Re(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await Ce(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const _=Cn(u.aggregateIndexes,t.op,t.field,t.where);if(_){ze(e,_.index);const H=Ze(_.index.by??[],_.key),ne=Xe(e,_.index.name),Y=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(ne)} WHERE ${Be} = ${H}`).toArray()[0];return et(t.op,Y)}}Vt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(d,fe),R=qe(t.op),E=he(t.field);let S=c`SELECT ${c.raw(R)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(S=c`${S} WHERE ${p}`);const P=G(a,S).toArray()[0]?.value;return P??null},asId(e,t){const o=Jt(s,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return L(e,O),o.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);L(e,O);const f=Re(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await Ce(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=In(u.aggregateIndexes,h.where);if(m){ze(e,m.index);const P=Ze(m.index.by??[],m.key),_=Xe(e,m.index.name),H=G(a,c`SELECT ${We} AS value FROM ${c.identifier(_)} WHERE ${Be} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const R=X(l,fe);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return R&&(E=c`${E} WHERE ${R}`),G(a,E).one().count},async delete(e,t,o){const u=te(e,t);if(!u){const S=Se(t);S&&(I(void 0),await S.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],p=o?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,E=R?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:d}),await hr({deletedId:e,deletedReference:S=>f[S],findHolders:async(S,m,P)=>(await Ve(S).findMany(S,{includeDeleted:p,where:{[m]:P}})).page,onCascade:(S,m)=>Ve(S).delete(m,void 0,o),onRestrict:S=>{throw new ae(S,"restrict")},onSetNull:(S,m,P)=>Ve(S).patch(m,{[P]:null}),schema:s,tableName:d}),$e(d),Ee(d),R&&E){const S={[E]:Q()},m={...f,...k(d),...S,_id:e};st(R,S,m,se),Oe(a,d,jt(d),[le(m),e,h]),De(d,e,m,f),Me(d,e,void 0),be(d,f,m),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f,m)),ye(d,e,"update",m),w({indexKeys:v(d,f,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d});return}Oe(a,d,Hr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,f,void 0),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f)),ye(d,e,"delete"),w({indexKeys:v(d,f),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??dn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ce(e)?void 0:e;let f=0;return await U(async()=>{for(;;){const l=(await B.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await B.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){ue(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(f.length,o?.limit,"deleteWhere"),B.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,o)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await B.findFirst(e,t);if(o===null)throw new Kn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return L(e,O),o.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?L(e,O):L(e);const{limit:f,orderKeys:d,statement:l}=await It(e,u,t,L),p=we(a,l.text,...l.params).toArray();h&&!x&&C?.recordRead(p.length);const R=[];for(const P of p){const _=Te(P);_&&(R.push(_),!h&&typeof _._id=="string"&&L(e,_._id))}if(f===void 0)return t.with&&await Ut({groupedCounter:St,fetcher:Je,parents:R,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ft(R,t.select,t.with)};const E=R.length>f,S=E?R.slice(0,f):R,m=S.at(-1);return t.with&&await Ut({fetcher:Je,groupedCounter:St,parents:S,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?He(m,d):null,isDone:!E,page:Ft(S,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await It(e,u,t,()=>{}),f=we(a,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=te(e,t);if(!o){const u=Se(t);return u?u.get(e,t):null}return L(o.tableName,e),o.row},async lookupById(e,t){const o=te(e,t);return o?(L(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return L(e,O),o.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Re(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await Ce(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const _=An(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=_===void 0?0:Object.keys(_.partial).length,ne=_?.index.by?.length??0;if(_&&(H===0||H===ne)){ze(e,_.index);const Y=Xe(e,_.index.name),V=Object.keys(_.partial),de=[];if(V.length===(_.index.by??[]).length&&V.length>0){const ke=Ze(_.index.by??[],_.partial),Le=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)} WHERE ${Be} = ${ke}`).toArray();return Le.length>0&&de.push({key:{..._.partial},value:et(h.op,Le[0])}),de}const mn=G(a,c`SELECT ${Be} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)}`).toArray();for(const ke of mn){const Le=Rn(JSON.parse(ke.key));de.push({key:Le,value:et(h.op,ke)})}return de}}for(const _ of[...t.by,h.field]){if(_===void 0)continue;const H=_===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${_}" } })`:`groupBy(${e}, { by: [..."${_}"] })`;Vt(u,_,H)}const R=X(l,fe),E=t.by.map(_=>c`${he(_)} AS ${c.identifier(_)}`);if(h.op==="count")E.push(c`COUNT(*) AS value`);else{const{field:_}=h;if(_===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(c`${c.raw(qe(h.op))}(${he(_)}) AS value`)}let S=c`SELECT ${c.join(E,c`, `)} FROM ${c.identifier(e)}`;R&&(S=c`${S} WHERE ${R}`),S=c`${S} GROUP BY ${c.join(t.by.map(_=>he(_)),c`, `)}`;const m=G(a,S).toArray(),P=[];for(const _ of m){const H={};for(const Y of t.by)H[Y]=Wn(u.shape[Y],_[Y]??null);const{value:ne}=_;P.push({key:H,value:ne==null?null:Number(ne)})}return P},async insert(e,t,o){const u=K(e,"insert");if(u)return gt(u,e,t,o,!0);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=zt(h,t,se);ot(h,f);let d;o?.clientId!==void 0?(Vr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=ge();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Q(),p={...f,...k(e),_creationTime:l,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),$e(e),Ee(e),dt(a,e,Ur(e),[d,l,le(p)]),Rt(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await M({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(ue(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)I(p);for(const p of t){const R=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:R,op:"insert",row:{...p,_id:R},table:e}),l.push(R)}return l}const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);$e(e),Ee(e);const f=[];for(let l=0;l<t.length;l+=Pe)f.push(k(e));const d=t.map((l,p)=>{const R=zt(h,l,se),E=o?.allowExplicitId===!0&&typeof R._id=="string"?R._id:ge(),S=o?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:Q(),m={...R,...f[Math.floor(p/Pe)],_creationTime:S,_id:E};return{creationTime:S,document:m,id:E}});for(const l of d)I(l.document);for(let l=0;l<d.length;l+=Pe){const p=c.join(d.slice(l,l+Pe).map(E=>c`(${E.id}, ${E.creationTime}, ${le(E.document)})`),c`, `),R=rn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);dt(a,e,R.sql,R.params)}for(const{document:l,id:p}of d)Rt(e,p,l),await $({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){ue(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)I(l);const d=async l=>f?gt(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ae&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Jt(s,e,t)},async patch(e,t,o,u){const h=te(e,o);if(!h){const S=Se(o);if(S){I(t),await S.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(L(l,e),Xt("patch",t),wt(l,e,t,d)){r?.({fields:Object.keys(Ue(t)),id:e,table:l});return}const R=Nn(p,t,d),E={...d,...Ue(R),...k(l),_id:e};st(p,R,E,se),Qn(u,d,E),ot(p,E,!0),Z(l,"before","update")&&await ee("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,jt(l),[le(E),e,f]),De(l,e,E,d),Me(l,e,E),be(l,d,E),me(l,e,d,E),D?.invalidate(l,e,v(l,d,E)),ye(l,e,"update",E),w({indexKeys:v(l,d,E),key:e,op:"update",row:E,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await M({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return I(o.patch),u.patchIf(e,t,o)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Yt;h+=1){const f=await $n(e,t,o,h<Yt,d=>B.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){ue(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(f.length,o?.limit,"patchWhere"),B.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,o),{patched:f.length}},async related(e,t){return dr(B,A,e,t)},relationEdges:A,relationWrites:T,query(e){const t=K(e,"query");return t?(L(e,O),t.query(e)):fn(a,s,e,J,o=>{o?j(o):L(e,O)},o=>{x||C?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return L(e,O),u.rank(e,t,o);J(e,t,"rank");const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,f),o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=qt(e,f.name),p=f.sortBy.map((V,de)=>Wt(de)),R=p.map(V=>Ie(V)).join(", "),E=G(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(R)} FROM ${c.identifier(l)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[S]=E;if(S===void 0)return null;let m=S.__partition__;const P=N(o.baseWhere,o.where);rt(P,s,e,"rank");const _=er(f,P);if(_){const V=tr(f.partitionBy??[],_);if(V!==m)return null;m=V}const H=p.map(V=>S[V]),{before:ne,total:Y}=en(a,l,p,f.sortBy,m,H,d);return{position:ne+1,total:Y}},async rankBefore(e,t,o){if(ce(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 u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,h);const f=qt(e,h.name),d=h.sortBy.map((p,R)=>Wt(R)),l=h.sortBy.map((p,R)=>Ae(o.sortValues[R]??null));return en(a,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage");const u=K(e,"rankPage");if(u)return L(e,O),u.rankPage(e,t,o);J(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=bt(At,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage"),J(e,t,"rank");const{directions:u,hasMore:h,rows:f}=bt(At,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=te(e,t);if(!o){const f=Se(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&me(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=te(e,o);if(!h){const P=Se(o);if(P){I(t),await P.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Xt("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,S=R??E??Q(),m={...t,...k(l),_creationTime:S,_id:e};st(p,t,m,se),ot(p,m),Z(l,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,Or(l),[S,le(m),e,f]),De(l,e,m,d),Me(l,e,m),be(l,d,m),me(l,e,d,m),D?.invalidate(l,e,v(l,d,m)),ye(l,e,"update",m),w({indexKeys:v(l,d,m),key:e,op:"update",row:m,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await M({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},En={db:B,scheduler:ie};return n.enforceRls===!0?pr(B,s,(e,t)=>te(e,t)?.tableName,(e,t)=>pn(e,t),A):B};export{si as CDC_LOG_TABLE,Ci as IDEMPOTENCY_TABLE,so as NotUniqueError,Ti as advanceClientWatermark,ci as applyCdcChanges,Xt as assertNoExplicitUndefined,Vr as assertValidClientId,ni as backfillAggregateIndexes,ri as backfillRankIndexes,oi as backfillSearchIndexes,ai as bumpCdcEpoch,di as cdcCanVouchFor,li as cdcForkedError,ui as cdcSeqLeavingRows,fi as cdcTouchesTables,hi as cdcTrimmedError,wi as compactCdcDocs,Zo as createShardCtxDb,pi as cursorBelowRetainedFloor,vi as migrateClientWatermark,gi as minCdcReplayableSeq,yi as minCdcSeq,Jt as normalizeIdStructurally,$i as readCdcChangeKeys,Ei as readCdcChanges,mi as readCdcCursor,Si as readCdcEpoch,Ai as readClientWatermark,xi as readIdempotent,ki as runShardMigrations,Fi as selectShapeMembers,qi as selectShapeRows,Ue as stripReservedPatchFields,_i as trimCdcChanges,bi as trimIdempotent,Mi as writeIdempotent};
@@ -1 +1 @@
1
- import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{compareStrings as l}from"./aggregateTableName-DbAttCNH.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-BbZ5hKM7.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
1
+ import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{compareStrings as l}from"./aggregateTableName-DbAttCNH.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-BbZ5hKM7.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-C1jsjAPd.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
1
+ import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-BztyXqNP.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
@@ -0,0 +1 @@
1
+ const E=Symbol("lunora.seekRange"),o="__relationExists";export{o as RELATION_EXISTS_KEY,E as SEEK_RANGE};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const E=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),b=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",relationWrites:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(b(E(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-DVCp4JQf.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{runDrizzle as p}from"./runDrizzle-Du5HLitO.mjs";import{h}from"./do-sql-CyWszGdM.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-DVCp4JQf.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{runDrizzle as p}from"./runDrizzle-Du5HLitO.mjs";import{h}from"./do-sql-Cg3zXJpF.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};
@@ -0,0 +1 @@
1
+ import{e as o}from"./effective-kind-BmG_zCAy.mjs";const a=new Set(["any","null"]),s=(t,n)=>{const l=n.kindOf(t);return l!==void 0&&a.has(l)||n.nullableOf(t)?!0:l==="union"&&(n.membersOf(t)??[]).some(i=>s(i,n))},e=t=>{const n=t._meta?.inner;return t.kind==="optional"&&n?e(n):t},u=t=>s(t,{kindOf:o,membersOf:n=>e(n)._meta?.members,nullableOf:n=>e(n)._meta?.column?.notNull===!1});export{u as v};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{applySelect as x}from"./CURSOR_PREFIX-BztyXqNP.mjs";const L=Symbol.for("lunora.relations.fanOutBudget"),q=c=>({fanOutBudget:c[L],relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),I=(c,r)=>r.select?x(c,r.select,r.with):c,J=async(c,r,i,u,s)=>{const d=await Promise.all(u.map(async f=>{const y=s?{AND:[{[i]:f},s]}:{[i]:f};return[f,await c(r,y)]}));return new Map(d)},P=32,R=1e4,U=(c,r,i)=>{const u=new Map;for(const s of c)for(const d of i(s)){const f=d[r],y=u.get(f);y?y.push(d):u.set(f,[d])}return u},W=(c,r)=>({...c,[L]:r}),G=(c,r)=>{const i=new Map;for(const[s,d]of c)for(const f of d){const y=i.get(f);y?y.push(s):i.set(f,[s])}const u=new Map;for(const s of r)for(const d of i.get(s._id)??[]){const f=u.get(d);f?f.push(s):u.set(d,[s])}return u},N=(c,r)=>{const i=new Set;for(const u of c){const s=u[r];s!=null&&i.add(s)}return[...i]},Q=async c=>{const{groupedCounter:r,fanOutBudget:i,fetcher:u,parents:s,relationBaseWhere:d,relationMask:f,schema:y,tableName:M,with:B}=c,b=i??{remaining:P},k=(t,e)=>f?.(t,e)??e;if(s.length===0)return;const _=y.tables[M];if(!_)throw new S("INTERNAL",`unknown table: ${M}`);const v=_.relationMap??{},T=(t,e)=>{const n=a=>y.tables[a]?.shardMode?.kind??"root";return n(t)===n(e)&&n(t)!=="shardBy"},A=t=>{const e=v[t];if(!e)throw new S("INTERNAL",`unknown relation "${t}" on table "${M}"`);return e},j=async(t,e,n)=>{const a=N(s,e.field);if(a.length===0){for(const l of s)l[t]=null;return}const{page:o}=await u(e.table,W({baseWhere:d?.(e.table),relationBaseWhere:d,relationMask:f,where:{[e.references]:{in:a}},with:n.with},b)),w=new Map;for(const l of k(e.table,o))w.set(l[e.references],l);for(const l of s){const g=w.get(l[e.field]);l[t]=g?I([g],n)[0]??null:null}},O=async(t,e,n,a)=>{const{page:o}=await u(t,W({baseWhere:d?.(t),limit:a,orderBy:e.orderBy,relationBaseWhere:d,relationMask:f,where:e.where?{AND:[e.where,n]}:n,with:e.with},b));return o},D=(t,e,n,a,o)=>{for(const w of s){const l=o.get(w[a])??[];w[t]=I(n===void 0?l:l.slice(0,n),e)}},E=async(t,e,n)=>{const a=N(s,e.references);if(a.length===0){for(const h of s)h[t]=[];return}const o=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,w=(h,m)=>O(e.table,n,h,m);if(o===0){for(const h of s)h[t]=[];return}const l=o!==void 0&&a.length<=b.remaining;l&&(b.remaining-=a.length);const g=l?await Promise.all(a.map(async h=>w({[e.field]:h},o))):[await w({[e.field]:{in:a}},void 0)],p=U(g,e.field,h=>k(e.table,h));D(t,n,o,e.references,p)},$=async t=>{const{from:e,table:n,to:a}=t.through,o=new Map,w=N(s,"_id");if(w.length===0)return o;const l=await O(n,{},{[e]:{in:w}},R+1);if(l.length>R)throw new S("INTERNAL",`loading "${M}" relations through "${n}" read more than ${String(R)} join rows for one page; load fewer ${M} rows at a time`);for(const g of k(n,l)){const p=g[e],h=g[a];if(p==null||h===null||h===void 0)continue;const m=o.get(p);m?m.add(h):o.set(p,new Set([h]))}return o},V=async(t,e,n)=>{const a=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,o=a===0?new Map:await $(e),w=(g,p)=>O(e.table,n,{_id:{in:[...g]}},p);let l=new Map;if(o.size>0&&a!==void 0&&o.size<=b.remaining){b.remaining-=o.size;const g=[...o.keys()],p=await Promise.all([...o.values()].map(async h=>w(h,a)));l=new Map(g.map((h,m)=>[h,k(e.table,p[m]??[])]))}else if(o.size>0){const g=new Set([...o.values()].flatMap(p=>[...p]));l=G(o,k(e.table,await w(g,void 0)))}D(t,n,a,"_id",l)},C=async(t,e)=>{const n=[...e];if(n.length===0)return new Set;if(T(M,t)){const o=await r(t,"_id",n,d?.(t));return new Set(n.filter(w=>(o.get(w)??0)>0))}const a=await O(t,{},{_id:{in:n}},void 0);return new Set(a.map(o=>o._id))},F=async(t,e)=>{const n=await $(e),a=await C(e.table,new Set([...n.values()].flatMap(o=>[...o])));for(const o of s){const w=o._count??{};w[t]=[...n.get(o._id)??[]].filter(l=>a.has(l)).length,o._count=w}},z=async t=>{for(const e of Object.keys(t)){const n=A(e);if(n.through!==void 0){await F(e,n);continue}const[a,o]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],w=d?.(n.table),l=N(s,o),g=l.length===0?new Map:await r(n.table,a,l,w);for(const p of s){const h=p._count??{},m=p[o];h[e]=m==null?0:g.get(m)??0,p._count=h}}};for(const[t,e]of Object.entries(B)){if(e===void 0||e===!1)continue;if(t==="_count"){await z(e);continue}const n=A(t),a=e===!0?{}:e;n.through===void 0?await(n.kind==="one"?j(t,n,a):E(t,n,a)):await V(t,n,a)}},H=async(c,r,i)=>{const{deletedId:u,deletedReference:s,findHolders:d,onCascade:f,onRestrict:y,onSetNull:M,tableName:B}=c,b=i.references==="_id"?u:s(i.references);if(b==null)return;const k=await d(r,i.field,b);if(k.length!==0){i.onDelete==="restrict"&&y(`cannot delete "${B}" row: "${r}.${i.field}" still references it`);for(const _ of k){const v=_._id;typeof v=="string"&&await(i.onDelete==="cascade"?f(r,v):M(r,v,i.field))}}},Y=async c=>{const{schema:r,tableName:i}=c;if(!r.tables[i])throw new S("INTERNAL",`unknown table: ${i}`);for(const[u,s]of Object.entries(r.tables)){const d=s.relationMap;if(d)for(const f of Object.values(d))f.kind!=="one"||f.table!==i||!f.onDelete||await H(c,u,f)}},Z=(c,r,i=!1)=>{for(const[u,s]of Object.entries(c.shape))u in r&&typeof s.parse=="function"&&(i&&r[u]===null&&s.kind==="optional"||s.parse(r[u]))};export{R as MAX_LINK_ROWS,Y as applyOnDelete,N as distinctValues,J as fanOutScalarCounts,q as relationHooks,Q as resolveWith,Z as runRowValidators};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{i as k}from"./wire-codec-BYCSiazv.mjs";import{i as m,r as $,F as g,e as R,s as F}from"./json-field-path-B2fjnGc3.mjs";const d={decrement:{apply:(t,e)=>t-e,kind:"number"},divide:{apply:(t,e)=>t/e,kind:"number"},increment:{apply:(t,e)=>t+e,kind:"number"},multiply:{apply:(t,e)=>t*e,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=t=>{if(!k(t))return;const e=Object.keys(t),[n]=e;if(!(e.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:t[n],operator:n}},b=t=>w(t)!==void 0,P=(t,e,n,o)=>{const r=d[e];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${t}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${t}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${e}" on "${t}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${e} "${t}" — its current value is ${String(o)}; set a number first.`);if(e==="divide"&&n===0)throw new s(`patch: cannot divide "${t}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${e}" on "${t}" overflows to ${String(i)}.`);return i},v=(t,e)=>{const n=new Set;for(const[o,r]of Object.entries(t))e(o)!==void 0&&b(r)&&n.add(o);return n},E=(t,e,n)=>{let o;for(const r of v(t,n)){const{operand:i,operator:c}=w(t[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...t},o[r]=P(r,c,i,e[r])}return o??t},j=new Set(["date","number","timestamp"]),l=t=>t.kind==="optional"&&t._meta?.inner!==void 0?l(t._meta.inner):t,p=t=>{const e=l(t);if(e.kind!==void 0&&j.has(e.kind))return"number";if(e.kind==="boolean")return"boolean";if(e.kind!=="union")return;const n=new Set((e._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=t=>e=>{const n=Object.hasOwn(t.shape,e)?t.shape[e]:void 0;return n===void 0?void 0:p(n)},A=(t,e)=>v(e,O(t)),I=(t,e,n)=>{try{return E(e,n,O(t))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=t=>{throw t instanceof g?new a("VALIDATION_ERROR",t.message):t},y=t=>{if(t===void 0)return;const e=l(t);if(e.kind==="object")return e._meta?.shape;if(e.kind!=="union")return;const n=(e._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(t,e)=>{let n=t.shape[e[0]??""];for(const o of e.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(t,e,n)=>{let o=[];try{o=F(e)}catch(i){h(i)}const r=N(t,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${e}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${e}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${e}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(t,e,n)=>{for(const[o,r]of Object.entries(e))m(o)&&_(t,o,r);try{return R(e,n)}catch(o){return h(o)}},x=(t,e,n)=>S(t,I(t,e,n),n),z=(t,e)=>A(t,e).size>0||Object.keys(e).some(n=>m(n)),K=(t,e,n)=>{if(t?.verify!==void 0&&!t.verify(e,n))throw new a("FORBIDDEN","update denied by policy")},B=(t,e)=>{try{return $(t,e)}catch(n){return h(n)}};export{K as assertPatchAllowed,A as operatorFields,z as patchDependsOnRow,B as readPatchField,x as resolvePatch};
@@ -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-DVCp4JQf.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-pUdD6kF-.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-hGCzG0O1.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-Du5HLitO.mjs";import{i as M,D as m,h as A}from"./do-sql-CyWszGdM.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.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-DVCp4JQf.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-pUdD6kF-.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-B7dV2y4L.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-Du5HLitO.mjs";import{i as M,D as m,h as A}from"./do-sql-Cg3zXJpF.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.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{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-Du5HLitO.mjs";import{k as m,D as E}from"./do-sql-CyWszGdM.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(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=u(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{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-Du5HLitO.mjs";import{k as m,D as E}from"./do-sql-Cg3zXJpF.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(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=u(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-GKlDpuM2.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CNpeUQ-H.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-Br3kxusw.mjs";import{projectColumns as g}from"./buildPokeFrames-CDOP-XYp.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-BPEzVAil.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CU8Kl2Bq.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-Br3kxusw.mjs";import{projectColumns as g}from"./buildPokeFrames-CDOP-XYp.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};
@@ -0,0 +1 @@
1
+ import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{c as p,s}from"./where-sql-Dn9trjRu.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-Du5HLitO.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-DrISKVKe.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-Du5HLitO.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-BKugKf70.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-pUdD6kF-.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-B2fjnGc3.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-DbAttCNH.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-C2CSfkeQ.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-Du5HLitO.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-Cg3zXJpF.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-BKugKf70.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-BbZ5hKM7.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{verifySiblingBody as A,RELAY_SIGNATURE_HEADER as g,siblingStub as N,siblingSecretOf as E,signSiblingBody as T}from"./stubByName-C_P73AOx.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),I=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!I(r)))return{ownerKey:t,region:r}},b=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
1
+ import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{verifySiblingBody as A,RELAY_SIGNATURE_HEADER as g,siblingStub as N,siblingSecretOf as E,signSiblingBody as T}from"./stubByName-C_P73AOx.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),I=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!I(r)))return{ownerKey:t,region:r}},b=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,