@lunora/shard-engine 1.0.0-alpha.210 → 1.0.0-alpha.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-B_CuudJA.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BnnvYfoI.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -2383,8 +2383,10 @@ interface ApplyOnDeleteOptions {
2383
2383
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
2384
2384
  interface RowValidatorOptions {
2385
2385
  only?: ReadonlySet<string>;
2386
+ patched?: ReadonlySet<string>;
2386
2387
  previous?: () => Readonly<Record<string, unknown>> | undefined;
2387
2388
  supplied?: Readonly<Record<string, unknown>>;
2389
+ table?: string;
2388
2390
  tolerateStoredNull?: boolean;
2389
2391
  trusted?: boolean;
2390
2392
  }
package/dist/index.d.ts CHANGED
@@ -2383,8 +2383,10 @@ interface ApplyOnDeleteOptions {
2383
2383
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
2384
2384
  interface RowValidatorOptions {
2385
2385
  only?: ReadonlySet<string>;
2386
+ patched?: ReadonlySet<string>;
2386
2387
  previous?: () => Readonly<Record<string, unknown>> | undefined;
2387
2388
  supplied?: Readonly<Record<string, unknown>>;
2389
+ table?: string;
2388
2390
  tolerateStoredNull?: boolean;
2389
2391
  trusted?: boolean;
2390
2392
  }
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-CDB9Ooq4.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-fCPCjSE4.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-jmlDbPlr.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-DmciS_rv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Ce6pOHKe.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-Cf2rnuLV.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-gZqs4Rsj.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-By7iuPdW.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-olXwJWFQ.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DrcbZM0t.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-CYSHgpFD.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-BapaAUfm.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-wSas3lLT.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-DrXTkXKH.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-Bymg2-13.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-Cb_dSAMj.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-4_ene2xR.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-DceH7dQi.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-fCPCjSE4.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-jmlDbPlr.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-DmciS_rv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Ce6pOHKe.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-Cf2rnuLV.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-gZqs4Rsj.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-By7iuPdW.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-olXwJWFQ.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-CaVH3fJ7.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-BapaAUfm.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-wSas3lLT.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-DrXTkXKH.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-Bymg2-13.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-Cb_dSAMj.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-4_ene2xR.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{i as L,R as P}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as O}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as $}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as D,uniqueIndexFields as _,equalityPinnedFields as K,buildSeekWhere as I,decodeCursor as v,buildSeekBeforeWhere as B,softDeleteScope as W,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as S}from"./applyInsertDefaults-CYSHgpFD.mjs";import{RELATION_EXISTS_KEY as F}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const C={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}},M=e=>P.has(e)?e:void 0,E=e=>{const t=M(e),r=t===void 0?void 0:C[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},q=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},H=5e3,m=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],j=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>L(e),g=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const i=e[o];return o==="AND"||o==="OR"?p(i).some(s=>g(s,t,r)):o==="NOT"?g(i??{},t,r):!!n[o]&&y(i)})},z=e=>e.through===void 0?[e.table]:[e.table,e.through.table],b=(e,t,r,n,o=new Set)=>{const i=t.tables[r]?.relationMap??{};for(const[s,a]of Object.entries(e??{})){const d=i[s],c=s==="NOT"?[a??{}]:p(a);s==="AND"||s==="OR"||s==="NOT"?c.forEach(l=>b(l,t,r,n,o)):d&&y(a)&&(z(d).filter(l=>!o.has(l)).forEach(l=>{o.add(l),b(n?.(l),t,l,n,o)}),Object.values(a).forEach(l=>b(l,t,d.table,n,o)))}return o},le=(e,t,r,n)=>{if(e&&g(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},Y=async(e,t,r,n)=>{const o=await f(t,e.table,n),{page:i}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return S(i,r)},Q=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},X=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},x=async(e,t,r,n,o)=>{const i=await Y(e,t,r,n);return i.length<=n.maxRelationKeys?i:o?m:Q(e,i.length,n)},A=async(e,t,r,n)=>{const o=await f(t,e.table,n),i=n.maxRelationKeys+1,s=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:i,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>i)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(i)}; the fetcher did not honour the page limit`);for(const c of S(d.page,r))s.add(c);if(s.size>n.maxRelationKeys&&X(e,s.size,n),d.isDone)return[...s];if(typeof d.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},U=async(e,t,r,n,o)=>{const i=E(e),{clause:s,project:a}=q(t),d=await x(t,i.negateChild?{NOT:r}:r,a,n,o);return d===m?m:i.negated?i.nullDisjunct?{OR:[{[s]:{notIn:d}},{[s]:{isNull:!0}}]}:{[s]:{notIn:d}}:{[s]:{in:d}}},V=async(e,t,r,n)=>{const o=E(e),{from:i,table:s,to:a}=t.through,d=await A(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await A({table:s},{[a]:{in:d}},i,n);return{_id:o.negated?{notIn:c}:{in:c}}},T=async(e,t,r,n,o)=>{const i=E(e),s=o.relationBaseWhere?.(t.table),a=i.negateChild?{NOT:r}:r,l={childWhere:await f(s?{AND:[s,a]}:a,t.table,o),negated:i.negated,parentTable:n,relation:t};return{[F]:l}},J=(e,t,r)=>{const n=M(e),o=n===void 0?void 0:C[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},G=async(e,t,r,n,o)=>{const i=[];for(const s of Object.keys(r)){J(s,e,t);const a=r[s]??{};if(t.through!==void 0){i.push(await V(s,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){i.push(await T(s,t,a,n,o));continue}const c=await U(s,t,a,o,d);c===m?i.push(await T(s,t,a,n,o)):i.push(c)}return j(i)},Z=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const i=[];for(const s of p(t))i.push(await f(s,r,n));return{[e]:i}}if(e==="NOT")return{NOT:await f(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?G(e,o,t,r,n):{[e]:t}},f=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Z(o,e[o],t,r));return j(n)},ee=async(e,t)=>!e||!g(e,t.schema,t.tableName)?e:f(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??H,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),N=100,u=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,i)=>o+u(i),0):r==="NOT"?t+=u(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},he=async(e,t,r)=>{const n=D(t.orderBy,e.shape,{pinned:K(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?I(n,v(t.cursor)):void 0,i=typeof t.endCursor=="string"?B(n,v(t.endCursor)):void 0;if(i!==void 0&&u(o)+u(i)>N)throw new h("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(u(o)+u(i))} cursor parameters, and a statement takes at most ${String(N)} — order by fewer fields`);let s=O(t.baseWhere,t.where);s=O(s,W(e.softDeleteMode,t.includeDeleted)),s=await ee(s,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,i])d&&(s=s?{AND:[s,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:s}},ue=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:i}=t,s=n!==void 0&&e.length>n,a=s?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:s&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,i):null,...s?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:s&&d&&o!==!0?R(d,i):null,isDone:!s,page:a}},w=(e,t,r)=>{for(const n of e){const o=k(n,t,r);if(o)return o}},te=(e,t,r,n)=>{if(e==="AND"||e==="OR")return w(p(t),r,n);if(e==="NOT")return w([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const i=o.through===void 0?[o.table]:[o.table,o.through.table],s=i.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const a=i.find(d=>$(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:w(Object.values(t),r,o.table)},k=(e,t,r)=>{for(const n of Object.keys(e)){const o=te(n,e[n],t,r);if(o)return o}},re=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!g(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})},fe=(e,t,r)=>{if($(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=k(e,t,r);if(!n){re(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{H as DEFAULT_MAX_RELATION_KEYS,le as assertFlatPredicate,fe as assertShapeShardable,he as composeReadPredicate,g as containsRelationPredicate,ue as findManyPage,y as isRelationPredicate,b as relationPredicateTables,ee as resolveRelationPredicates};
1
+ import{LunoraError as h}from"@lunora/errors";import{i as L,R as P}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as O}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as $}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as D,uniqueIndexFields as _,equalityPinnedFields as K,buildSeekWhere as I,decodeCursor as v,buildSeekBeforeWhere as B,softDeleteScope as W,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as S}from"./applyInsertDefaults-CaVH3fJ7.mjs";import{RELATION_EXISTS_KEY as F}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const C={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}},M=e=>P.has(e)?e:void 0,E=e=>{const t=M(e),r=t===void 0?void 0:C[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},q=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},H=5e3,m=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],j=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>L(e),g=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const i=e[o];return o==="AND"||o==="OR"?p(i).some(s=>g(s,t,r)):o==="NOT"?g(i??{},t,r):!!n[o]&&y(i)})},z=e=>e.through===void 0?[e.table]:[e.table,e.through.table],b=(e,t,r,n,o=new Set)=>{const i=t.tables[r]?.relationMap??{};for(const[s,a]of Object.entries(e??{})){const d=i[s],c=s==="NOT"?[a??{}]:p(a);s==="AND"||s==="OR"||s==="NOT"?c.forEach(l=>b(l,t,r,n,o)):d&&y(a)&&(z(d).filter(l=>!o.has(l)).forEach(l=>{o.add(l),b(n?.(l),t,l,n,o)}),Object.values(a).forEach(l=>b(l,t,d.table,n,o)))}return o},le=(e,t,r,n)=>{if(e&&g(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},Y=async(e,t,r,n)=>{const o=await f(t,e.table,n),{page:i}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return S(i,r)},Q=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},X=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},x=async(e,t,r,n,o)=>{const i=await Y(e,t,r,n);return i.length<=n.maxRelationKeys?i:o?m:Q(e,i.length,n)},A=async(e,t,r,n)=>{const o=await f(t,e.table,n),i=n.maxRelationKeys+1,s=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:i,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>i)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(i)}; the fetcher did not honour the page limit`);for(const c of S(d.page,r))s.add(c);if(s.size>n.maxRelationKeys&&X(e,s.size,n),d.isDone)return[...s];if(typeof d.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},U=async(e,t,r,n,o)=>{const i=E(e),{clause:s,project:a}=q(t),d=await x(t,i.negateChild?{NOT:r}:r,a,n,o);return d===m?m:i.negated?i.nullDisjunct?{OR:[{[s]:{notIn:d}},{[s]:{isNull:!0}}]}:{[s]:{notIn:d}}:{[s]:{in:d}}},V=async(e,t,r,n)=>{const o=E(e),{from:i,table:s,to:a}=t.through,d=await A(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await A({table:s},{[a]:{in:d}},i,n);return{_id:o.negated?{notIn:c}:{in:c}}},T=async(e,t,r,n,o)=>{const i=E(e),s=o.relationBaseWhere?.(t.table),a=i.negateChild?{NOT:r}:r,l={childWhere:await f(s?{AND:[s,a]}:a,t.table,o),negated:i.negated,parentTable:n,relation:t};return{[F]:l}},J=(e,t,r)=>{const n=M(e),o=n===void 0?void 0:C[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},G=async(e,t,r,n,o)=>{const i=[];for(const s of Object.keys(r)){J(s,e,t);const a=r[s]??{};if(t.through!==void 0){i.push(await V(s,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){i.push(await T(s,t,a,n,o));continue}const c=await U(s,t,a,o,d);c===m?i.push(await T(s,t,a,n,o)):i.push(c)}return j(i)},Z=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const i=[];for(const s of p(t))i.push(await f(s,r,n));return{[e]:i}}if(e==="NOT")return{NOT:await f(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?G(e,o,t,r,n):{[e]:t}},f=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Z(o,e[o],t,r));return j(n)},ee=async(e,t)=>!e||!g(e,t.schema,t.tableName)?e:f(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??H,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),N=100,u=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,i)=>o+u(i),0):r==="NOT"?t+=u(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},he=async(e,t,r)=>{const n=D(t.orderBy,e.shape,{pinned:K(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?I(n,v(t.cursor)):void 0,i=typeof t.endCursor=="string"?B(n,v(t.endCursor)):void 0;if(i!==void 0&&u(o)+u(i)>N)throw new h("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(u(o)+u(i))} cursor parameters, and a statement takes at most ${String(N)} — order by fewer fields`);let s=O(t.baseWhere,t.where);s=O(s,W(e.softDeleteMode,t.includeDeleted)),s=await ee(s,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,i])d&&(s=s?{AND:[s,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:s}},ue=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:i}=t,s=n!==void 0&&e.length>n,a=s?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:s&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,i):null,...s?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:s&&d&&o!==!0?R(d,i):null,isDone:!s,page:a}},w=(e,t,r)=>{for(const n of e){const o=k(n,t,r);if(o)return o}},te=(e,t,r,n)=>{if(e==="AND"||e==="OR")return w(p(t),r,n);if(e==="NOT")return w([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const i=o.through===void 0?[o.table]:[o.table,o.through.table],s=i.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const a=i.find(d=>$(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:w(Object.values(t),r,o.table)},k=(e,t,r)=>{for(const n of Object.keys(e)){const o=te(n,e[n],t,r);if(o)return o}},re=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!g(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})},fe=(e,t,r)=>{if($(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=k(e,t,r);if(!n){re(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{H as DEFAULT_MAX_RELATION_KEYS,le as assertFlatPredicate,fe as assertShapeShardable,he as composeReadPredicate,g as containsRelationPredicate,ue as findManyPage,y as isRelationPredicate,b as relationPredicateTables,ee as resolveRelationPredicates};
@@ -1 +1 @@
1
- import{LunoraError as R}from"@lunora/errors";import{q as _t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as zn,l as Ue,s as Yn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Xn,stableWireKey as jt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as Zn,aggregateSqlFunction as Oe,normalizeCountArgument as Ht}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as at,encodeAggregateKey as dt,readAggregateValue as lt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ut,selectIndexForGroupBy as eo,selectIndexForCount as to,selectIndexForAggregate as no}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as oo,searchIndexCoversTable as ro}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{backfillAggregateIndexes as os,backfillRankIndexes as rs,backfillSearchIndexes as is}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{appendCdcChange as io,readCdcDocAtOrBefore as so}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{CDC_LOG_TABLE as cs,applyCdcChanges as as,bumpCdcEpoch as ds,cdcCanVouchFor as ls,cdcForkedError as us,cdcSeqLeavingRows as fs,cdcTouchesTables as hs,cdcTrimmedError as ws,compactCdcDocs as ps,cursorBelowRetainedFloor as gs,minCdcReplayableSeq as ys,minCdcSeq as $s,readCdcChangeKeys as Es,readCdcChanges as ms,readCdcCursor as Rs,readCdcEpoch as vs,trimCdcChanges as Ss}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{allocateCommitSeq as co,COMMIT_SEQ_FIELD as ao}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as lo}from"./createCompanionSync-DmciS_rv.mjs";import{isMemoryTable as Kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Nt}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as uo}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as ye,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as fo,j as yt,D as ie,r as Ce,W as ho,k as ae,b as Ge,A as ft,a as je,m as pe,e as ge,s as wo,t as po,u as go,i as yo,q as Qt,h as mn,g as $o}from"./do-sql-Cf2rnuLV.mjs";import{renderSql as Rn,unionAll as vn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as Eo,u as mo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as Ro,boundingBoxGeohashes as vo,haversineMeters as So,pointInBoundingBox as _o}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as To}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Ao,assertPatchAllowed as Io,operatorFields as bo,readPatchField as Vt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as xo,encodeCursor as $t,nullsOrderSuffix as Co,normalizeOrderKeys as Jt,uniqueIndexFields as Mo,buildSeekWhere as Do,decodeCursor as zt,buildSeekBeforeWhere as ko,softDeleteScope as be,applySelect as _n}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Yt,sortColumnName as Xt,resolveRankPartition as Lo,encodePartitionKey as Fo,RANK_TIEBREAK as Wo,rankPivotConditionSql as Bo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Zt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as qo,withUnknownIndexKeys as Po,indexKeysForRow as Uo,buildIndexRange as Oo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Je,j as Me,c as ee,t as Xe,i as en}from"./where-sql-Cb_dSAMj.mjs";import{serializeSqlValue as De}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as ke}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Go,isPushableWhere as jo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Ho,findRelated as Ko}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ht,findManyPage as No,relationPredicateTables as Qo,resolveRelationPredicates as Vo,composeReadPredicate as Jo}from"./DEFAULT_MAX_RELATION_KEYS-DrcbZM0t.mjs";import{describeRelationWrites as zo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as He,transformOnlyDefinition as Yo,applyInsertDefaults as Et,resolveWith as Xo,relationHooks as Zo,applyOnDelete as er,fanOutScalarCounts as tr,CASCADE_MAX_ROWS as nr}from"./applyInsertDefaults-CYSHgpFD.mjs";import{guardWriter as or}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as ir}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as tn,runTriggers as sr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ts,migrateClientWatermark as As,readClientWatermark as Is}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as xs,readIdempotent as Cs,trimIdempotent as Ms,writeIdempotent as Ds}from"./IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{runShardMigrations as Ls}from"./runShardMigrations-4_ene2xR.mjs";import{selectShapeMembers as Ws,selectShapeRows as Bs}from"./selectShapeMembers-Ce6pOHKe.mjs";const cr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ar=()=>new R("INVALID_CURSOR","invalid cursor"),nn=16,on=8,Z=1024,Tt=(n,i)=>i.query(n),dr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,a]of i.entries()){const w=s===i.length-1;let g=0;for(const E of n)(w?E.startsWith(a):E===a)&&(g+=1);if(g===0)return 0;o+=g}return o},lr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const a=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:a+String.fromCodePoint(s)}},ur=(n,i,o)=>{const s={eq:(a,w)=>{if(!n.definition.filterFields?.includes(a))throw new R("INTERNAL",`field "${a}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=on)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(on)} .eq() filters are supported per search query`);return n.filters.push({field:a,value:w}),s},search:(a,w)=>{const g=n;if(a!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${a}"`);const E=Tt(w,o).length;if(E>nn)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(nn)} search terms are supported (got ${String(E)})`);return g.field=a,g.query=w,g.hasQuery=!0,s}};return s},fr=n=>{if(n.length>Z)throw new R("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},hr=n=>Math.min(n.offset+n.numItems+1,Z),wr=n=>btoa(`search:${String(n)}`),pr=n=>{let i;try{i=cr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},gr=n=>{if(typeof n.endCursor=="string")throw new R("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?pr(n.cursor):0;if(o===void 0)throw ar();if(o+i>=Z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(Z)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},yr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?wr(o):null,isDone:!s,page:n.slice(i.offset,o)}},$r=n=>{if(n===void 0)return Z+1;if(!Number.isFinite(n))return Z;const i=Math.max(0,Math.floor(n));if(i>Z)throw new R("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Tn=500,An=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??Tn},In=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Er=32,mr=1024,bn=(n,i,o,s)=>{const a=`SELECT id, _creationTime, ${ke(ie)} FROM ${ke(n)}`,w=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${a} ${w}`):Me(`${a} WHERE `,i,` ${w}`)},Ze={fieldRef:n=>Je(yt(n)),rangeTypeGuard:(n,i)=>Je(fo(n,i)),serialize:De},Rr=n=>n===void 0?"":Co(n==="first"),xn=n=>{const i=n.map(o=>`${yt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${yt("id")} ${xo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},vr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Cn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Sr=n=>{const i=Cn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},_r=(n,i)=>{const o=n.order,s=Sr(n),{shape:a}=i;return s.length>0?Jt(s.map(w=>({[w]:o})),a,{pinned:Cn(n),uniqueBy:Mo(i.indexes,a)}):Jt([{_creationTime:o}],a)},Tr=(n,i,o,s)=>{const a=n.sqlConditions.map(w=>({[w.field]:{[vr[w.comparator]??"eq"]:w.value}}));if(o&&a.push(Do(i,zt(o))),s&&a.push(ko(i,zt(s))),a.length!==0)return a.length===1?a[0]:{AND:a}},Ar=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Er):n.want},mt=(n,i,o,s,a,w,g)=>{const E=_r(s,o),y=xn(E),u=[],{filters:C,want:I}=w;let A=w.cursor??void 0,x=Ar(w);if(I===0)return{documents:u,orderKeys:E};for(;;){const q=ee(Tr(s,E,A,w.endCursor),Ze,Xe),P=bn(i,a&&q?Me(q," AND ",a):a??q,y,x),W=ye(n,P.text,...P.params).toArray();let U={};g(W.length);for(const j of W)if(U=Ce(j),C.every(te=>te(U))&&u.push(U)===I)return{documents:u,orderKeys:E};if(x===void 0||W.length<x)return{documents:u,orderKeys:E};A=$t(U,E),x=Math.max(x,Math.min(x*2,mr))}},Ir=(n,i,o,s,a,w,g,E)=>{const y=Math.max(0,Math.floor(a.numItems));if(typeof a.endCursor=="string"){const{documents:q,orderKeys:P}=mt(n,i,o,s,w,{cursor:a.cursor,endCursor:a.endCursor,filters:g.all,selective:g.selective,want:void 0},E),W=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:a.endCursor,isDone:!0,page:q,splitCursor:W?$t(W,P):null}}const{documents:u,orderKeys:C}=mt(n,i,o,s,w,{cursor:a.cursor,filters:g.all,selective:g.selective,want:y+1},E),I=u.length>y,A=I?u.slice(0,y):u,x=A.at(-1);return{continueCursor:I&&x?$t(x,C):null,isDone:!I,page:A}},et=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const a=n(ke(o));return i.set(o,a),a}},$e=ke(ie),br=et(n=>`INSERT INTO ${n} (id, _creationTime, ${$e}) VALUES (?, ?, ?)`),rn=et(n=>`UPDATE ${n} SET ${$e} = ? WHERE id = ? AND ${$e} = ?`),xr=et(n=>`UPDATE ${n} SET _creationTime = ?, ${$e} = ? WHERE id = ? AND ${$e} = ?`),Cr=et(n=>`DELETE FROM ${n} WHERE id = ? AND ${$e} = ?`),Mr="SELECT changes() AS changed",sn=new Map,Dr="",kr=n=>{const i=JSON.stringify(n),o=sn.get(i);if(o!==void 0)return o;const s=n.map(w=>f`SELECT ${f.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(w)} WHERE id = ${Dr}`),{sql:a}=Rn("sqlite",f`${vn(s)} LIMIT 1`);return sn.set(i,a),a},Lr=(n,i)=>i.map(()=>n),Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wr=n=>{if(!Fr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Br=(n,i,o,s)=>{if(o!==!0)return;const a=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const g=a?Et(n,w,s)._id:w._id;typeof g=="string"&&Rt(g)}},cn=50,Ke=Math.floor(Sn.boundParams/3),an=Sn.boundParams,qr=128,ze=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ne=(n,i,o)=>{In(n,An(i,o,ze),o,ze)},dn=async(n,i,o,s,a)=>{const w=An(s,a,ze),{page:g}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>w&&In(Math.max(await n.count(i,{where:o}),g.length),w,a,ze),g},Pr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Ur=n=>Math.max(n,Z),Mn=(n,i)=>{const o=n.filters.map(s=>f`${ge(s.field)} = ${De(s.value)}`);return i&&o.push(i),o},Or=(n,i,o,s,a)=>{const w=Tt(o.query,_t(o.definition.language));if(w.length===0)return[];const g=zn(i,o.indexName),E=`${g}__vocab`,y=w.length-1,u=w.map((P,W)=>{const U=lr(P,W===y),j=U.exact?f`${f.identifier("term")} = ${U.lower}`:f`${f.identifier("term")} >= ${U.lower} AND ${f.identifier("term")} < ${U.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(W))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(E)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=w.map((P,W)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(W))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),I=f`SELECT f.${f.identifier(Ue)} AS ${f.identifier(Ue)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${vn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Ue)} HAVING ${f.join(C.map(P=>f`${P} > 0`),f` AND `)}`,A=Mn(o,a);let x=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${I}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Ue)}`;A.length>0&&(x=f`${x} WHERE ${f.join(A,f` AND `)}`),x=f`${x} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const q=[];for(const P of K(n,x)){const W=mn(P);if(W){const U=P.__score__;q.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return q},Gr=(n,i,o,s,a)=>{const w=_t(o.definition.language),g=Tt(o.query,w);if(g.length===0)return[];const E=Mn(o,a);let y=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;E.length>0&&(y=f`${y} WHERE ${f.join(E,f` AND `)}`),y=f`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Ur(s)))}`;const u=K(n,y).toArray(),C=[];for(const I of u){const A=mn(I);if(!A)continue;const x=dr(Yn(A,o.definition),g);x>0&&C.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:x})}return C.sort((I,A)=>A.score-I.score||A.creationTime-I.creationTime||I.id.localeCompare(A.id)),C.slice(0,s).map(I=>({document:I.doc,score:I.score}))},wt=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},jr=(n,i)=>{const o=n,s={near:(a,w)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:a.lat,lng:a.lng},radiusMeters:w},s},within:a=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a.sw,".within() sw corner",i,o.indexName),wt(a.ne,".within() ne corner",i,o.indexName),a.sw.lat>a.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(a.sw.lng>a.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:a.ne.lat,lng:a.ne.lng},sw:{lat:a.sw.lat,lng:a.sw.lng}},s}};return s},Hr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:a}=o;return typeof s=="number"&&typeof a=="number"?{lat:s,lng:a}:void 0},Kr=(n,i)=>{const o=Hr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const a=So(i.near.point,o);return a<=i.near.radiusMeters?{creationTime:s,distance:a}:void 0}return _o(o,i.within)?{creationTime:s,distance:0}:void 0},Nr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const a=o.near?Ro(o.near.point,o.near.radiusMeters):vo(o.within),w=$o(i,o.indexName),g=a.map(I=>f`(g.${f.identifier("__geohash__")} >= ${I} AND g.${f.identifier("__geohash__")} < ${`${I}{`})`),E=[f`(${f.join(g,f` OR `)})`];s&&E.push(s);const y=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(w)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(E,f` AND `)}`,u=K(n,y).toArray(),C=[];for(const I of u){const A=Ce(I),x=A?Kr(A,o):void 0;A&&x&&C.push({creationTime:x.creationTime,distance:x.distance,doc:A})}return C.sort((I,A)=>I.distance-A.distance||A.creationTime-I.creationTime),C},Dn=(n,i,o,s)=>{const a=[];for(const w of n)if(i.every(g=>g(s(w)))&&(a.push(w),typeof o=="number"&&a.length>=o))break;return a},Qr=(n,i,o,s,a,w=()=>{})=>{const g=o.within!==void 0,E=Nr(n,i,o,a).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return w(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},ln=(n,i,o,s,a,w,g=()=>{})=>{const{geo:E}=o;if(!E)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=a.length>0,u=Qr(n,i,E,y?void 0:w,s,g);return y?Dn(u,a,w,C=>C.document):u},un=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&rr(s))throw new R("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vr=n=>{let i=0;const o=[],s={...Ze,relationExists:a=>{const{childWhere:w,negated:g,parentTable:E,relation:y}=a,u=`__rel_${String(i)}`,C=o.at(-1)??E;i+=1,n(y.table,G);const I=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,x=Je(`${Qt(u,A)} = ${Qt(C,I)}`);o.push(u);const q=ee(w,s,Xe);o.pop();const P=q===void 0?x:Me(x," AND ",q),W=Me("EXISTS (SELECT 1 FROM ",en(y.table)," AS ",en(u)," WHERE ",P,")");return g?Me("NOT ",W):W}};return s};class Jr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const zr=/\s/u,Yr=String.fromCodePoint(0),fn=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||zr.test(o)||o.includes(Yr)?null:o},kn=(n,i,o,s=()=>{},a=()=>{},w=()=>{},g)=>{const E=i.tables[o];if(!E)throw new R("INTERNAL",`unknown table: ${o}`);const y=be(E.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const v=Q(y,u.pushedWhere);return v?ee(v,pe):void 0},I=()=>{const v=Q(y,u.pushedWhere);return v?ee(v,Ze,Xe):void 0},A=()=>[...u.inMemoryFilters,...u.verifyFilters];let x=0;const q=v=>{const{search:D}=u;if(!D)throw new R("INTERNAL","runSearchFetch called without a staged search");oo(go(n),o,E);const k=u.inMemoryFilters.length>0,F=$r(k?void 0:v),L=yo(n);if(L&&!ro(n,o,D.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${D.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Ee=C(),ne=L?Or(n,o,D,F,Ee):Gr(n,o,D,F,Ee);!k&&v===void 0&&fr(ne);const le=A();return x=ne.length,le.length>0?Dn(ne,le,v,Y=>Y.document):ne},P=v=>q(v).map(D=>D.document),W=v=>{const D=gr(v);return yr(P(hr(D)),D)},U=()=>{if(u.search||u.geo||u.indexName===void 0){a(void 0);return}a(Oo(o,u.indexName,u.indexFields,u.sqlConditions,De))},j=v=>{U();let D=0;const k=(()=>{if(u.search){const F=P(v);return D=x,F}return u.geo?ln(n,o,u,C(),A(),v,F=>{D=F}).map(F=>F.document):mt(n,o,E,u,I(),{filters:A(),selective:u.inMemoryFilters.length>0,want:v===void 0?void 0:Math.max(0,Math.floor(v))},F=>{D+=F}).documents})();return w(Math.max(D,k.length)),k},te=()=>{if(!u.search&&!u.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let v=0;const D=(()=>{if(u.search){const k=q(void 0);return v=x,k}return ln(n,o,u,C(),A(),void 0,k=>{v=k})})();return w(Math.max(v,D.length)),D},V={async*[Symbol.asyncIterator](){const v=kn(n,i,o,s,a,w,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await v.collect();return}let D;for(;;){const k=await v.paginate({cursor:D??null,numItems:qr});if(yield*k.page,k.isDone||k.continueCursor===null)return;D=k.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return te()},filter(v){const D=Go(v);return D!==void 0&&jo(D,E.shape)?(u.pushedWhere=Q(u.pushedWhere,D),u.verifyFilters.push(v)):u.inMemoryFilters.push(v),V},async first(){return j(1)[0]??null},order(v){return u.order=v==="desc"?"desc":"asc",V},async paginate(v){let D=0;if(U(),u.search){const F=W(v);return w(F.page.length),F}if(u.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Ir(n,o,E,u,v,I(),{all:A(),selective:u.inMemoryFilters.length>0},F=>{D+=F});return w(Math.max(D,k.page.length)),k},async take(v){return j(v)},async unique(){const v=j(2);if(v.length>1)throw new Jr(`unique() on table "${o}" matched ${String(v.length)} documents; expected at most one`);return v[0]??null},withGeoIndex(v,D){const k=(E.geoIndexes??[]).find(L=>L.name===v);if(!k)throw new R("INTERNAL",`unknown geo index "${v}" on table "${o}"`);s(o,v,"geo");const F={definition:k,indexName:v};if(u.geo=F,D(jr(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${v}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return V},withIndex(v,D){const k=E.indexes.find(F=>F.name===v);if(!k)throw new R("INTERNAL",`unknown index "${v}" on table "${o}"`);return s(o,v,"index"),u.indexName=v,u.indexFields=k.fields,D&&D(Pr(u)),V},withSearchIndex(v,D){const k=(E.searchIndexes??[]).find(L=>L.name===v);if(!k)throw new R("INTERNAL",`unknown search index "${v}" on table "${o}"`);s(o,v,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:v,query:""};if(u.search=F,D(ur(F,o,_t(k.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${v}" on table "${o}" requires a .search(field, query) call`);return V}};return V},pt=(n,i,o,s)=>{const a=o;for(const[w,g]of po(n)){if(g.serverDefault){w in i&&(a[w]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(w in i)&&(a[w]=g.onUpdateFn())}},hn=5,wn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},pn=["_commitSeq","_creationTime","_id"],Qe=n=>pn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!pn.includes(i))):n,Xr=/unique constraint failed/i,Zr=n=>n instanceof Error&&Xr.test(n.message),ei=/string or blob too big/iu,ti=(n,i)=>{if(!(!(n instanceof Error)||!ei.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},vt=(n,i,o,s)=>{try{ye(n,o,...s)}catch(a){throw Zr(a)?new de(`unique constraint violation on "${i}"`,"unique"):(ti(a,i),a)}},Ve=(n,i,o,s)=>{if(vt(n,i,o,s),ye(n,Mr).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},gn=(n,i,o,s,a,w,g)=>{const E=[];for(let I=0;I<o.length+1;I+=1){const A=o[I],x=s[I],q=x?.direction==="desc"?"desc":"asc",P=A===void 0||x===void 0?f`${f.identifier(Wo)} < ${g}`:Bo(A,w[I],q,!1);if(P===void 0)continue;const W=[];for(let j=0;j<I;j+=1)W.push(f`${f.identifier(o[j])} IS ${w[j]}`);W.push(P);const[U]=W;E.push(W.length===1&&U!==void 0?U:f`(${f.join(W,f` AND `)})`)}const y=E.length>0?f.join(E,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a} AND (${y})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a}`).one();return{before:u.c,total:C.c}},ni=n=>{const i=new Map;for(const[s,a]of Object.entries(n.tables))for(const w of Object.values(a.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:s,op:w.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const a=new Set,w=[s];for(let g=w.pop();g!==void 0;g=w.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||tn(n,E,y))return!0;a.has(E)||(a.add(E),w.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,a])=>a.shardMode?.kind==="global"||tn(n,s,"delete")||o(s)).map(([s])=>s))},oi=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},gt=new WeakMap,ri=(n,i)=>{let o=gt.get(i.tables);if(!gt.has(i.tables)){const a=Object.keys(i.tables).map(w=>w.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=a.length===0?void 0:new RegExp(`"(${a.join("|")})"`,"gu"),gt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const a of n.matchAll(o))s.add(a[1]);return s.size===1?[...s][0]:void 0},ii=(n,i,o)=>{for(const s of n){const a=s,w=a?.[ie];if(typeof w=="string"){const g=a?.id,E=mo(w);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},si=(n,i,o)=>{if(i===void 0)return n;const s=(a,...w)=>{const g=n.exec(a,...w),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ri(a,o);let C=!1;const I=A=>{ii(A,i,u)};return g.toArray=()=>{const A=[];for(const x of{[Symbol.iterator]:y})I([x]),A.push(x);return A},g.one=()=>{C=!0;try{const A=E();return I([A]),A}finally{C=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})C||I([x]),yield x},g};return new Proxy(n,{get:(a,w)=>w==="exec"?s:w===ho?a:Reflect.get(a,w,a)})},ci=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ai=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Eo(n);if(s===void 0)return;const a=n._id;typeof a=="string"?o.recordDocumentRead(`global\0${i}\0${a}`,s):o.recordReadBytes(s)},Ye=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const a=n;switch(i){case"lookup":{xe(a.row,typeof a.tableName=="string"?a.tableName:o,s);return}case"page":{for(const w of a.page??[])xe(w,o,s);return}case"rows":{for(const w of Array.isArray(n)?n:[n])xe(w,o,s);return}default:for(const w of Array.isArray(n)?n:[])xe(w.document,o,s)}},Ln=(n,i,o)=>new Proxy(n,{get:(s,a)=>{const w=Reflect.get(s,a,s);if(typeof w!="function")return w;if(a===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(w,s,[]))xe(y,i,o),yield y};const g=ai.get(a);return(...E)=>{const y=Reflect.apply(w,s,E);return g!==void 0?Promise.resolve(y).then(u=>(Ye(u,g,i,o),u)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Ln(y,i,o):y}}}),di=new Set(["findFirst","findFirstOrThrow","findMany"]),li=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),a=s.with,w=g=>_n(g,o,a);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:w(g.page)}:w([g])[0]}},yn=256,St=4096,ui=1024*1024,fi=async(n,i,o,s)=>{const a=i[1]??{},w=[];let{cursor:g}=a,E=yn,y=0;for(;;){const u=await n([i[0],{...a,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(u))return Ye(u,"rows",o,s),[...w,...u];const C=s.headroom().readBytes;if(Ye(u,"page",o,s),w.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:w};g=u.continueCursor,y+=s.headroom().readBytes-C,E=y>0?Math.min(St,Math.max(yn,Math.floor(ui*w.length/y))):St}},hi=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const a=Reflect.get(o,s,o);if(typeof a!="function")return a;if(s==="query")return(...g)=>Ln(Reflect.apply(a,o,g),String(g[0]),i);const w=ci.get(s);return w===void 0?a:async(...g)=>{const E=di.has(s)?li(g):void 0;let y=E?.args??g;const u=String(g[0]),C=y[1],I=s==="findMany"&&typeof C?.endCursor=="string",A=s==="findMany"&&typeof C?.limit!="number"&&!I;if(I&&typeof C.limit!="number"&&(y=[y[0],{...C,limit:St},...y.slice(2)]),A){const q=await fi(P=>Reflect.apply(a,o,P),y,u,i);return E===void 0?q:E.project(q,w)}const x=await Reflect.apply(a,o,y);return Ye(x,w,u,i),E===void 0?x:E.project(x,w)}}}),$n=new WeakMap,En=new WeakMap,wi=500,pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,a=$n.get(n)??{value:void 0},w=En.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};$n.set(e,a),En.set(e,w),g=pi(e)}return g},y=si(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),I=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},A=Ho(u),x=new Map;for(const e of A){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const q=(e,t,r)=>{for(const c of x.get(e)??[]){const l=t[c.column];if(typeof l!="string"||r?.[c.column]===l||c.targetTable===e&&t._id===l)continue;if(K(y,f`SELECT 1 FROM ${f.identifier(c.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${c.name} references ${c.targetTable} row "${l}", which does not exist`)}},P=zo(u,n.inTransaction),W=ni(u),U=oi(u),j=()=>n.inTransaction?.()===!0,te=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((a.value===void 0||!j())&&(a.value=co(y)),{[ao]:a.value}),V=(e,...t)=>{const r=u.tables[e]?.indexes??[],c=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,c.push(qo(l))),c.push(...Po(r,Uo(r,p,De))));return c.length>0?c:void 0},v=n.onRead??(()=>{}),D=e=>{Kt(u.tables[e])&&v(Zt,Zt)},k=n.onReadRange??(e=>{v(e.table,G)}),F=e=>{D(e.table),k(e)},L=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),D(e),v(e,t,r)},Ee=(e,t)=>{const r=e.row._id;L(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ne=n.onIndexUse??(()=>{}),le=n.onWrite??(()=>{}),Y=e=>{s?.recordWrite(e)},me=async e=>{Y(e.doc),await le(e)},{cache:ue}=n,Re=n.clock??(()=>Date.now()),At=n.idGenerator??(()=>crypto.randomUUID()),It=n.scheduler??Zn,ve=hi(n.globalDb,s),fe=n.auth??{identity:null,userId:null},bt=n.cdc??!1,tt=It,Fn=ir({scheduler:typeof tt.list=="function"&&typeof tt.get=="function"?tt:void 0,storage:n.storage}),Se=(e,t,r,c)=>{bt&&!Kt(u.tables[e])&&io(y,Re(),e,t,r,c)},xt=(e,t,r,c)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!bt)return!1;const p=i?.();if(p===void 0)return!1;const d=so(y,e,t,p);if(d===void 0)return!1;const h=bo(l,r);return Object.keys(Qe(r)).some(m=>!h.has(m)&&jt(Vt(d,m))!==jt(Vt(c,m)))},se=e=>u.tables[e]?.shardMode?.kind==="global",Ct=(e,t)=>{if(se(e)){if(!ve)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}return O},nt=e=>Ct(e,"cascade"),H=(e,t)=>{if(se(e)){if(!ve)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}},_e=(e,t)=>{L(e,G);for(const r of Qo(Q(t.baseWhere,t.where),u,e,t.relationBaseWhere))L(r,G)},ce=(e,t,r)=>{ue?.invalidateTable(t),C({key:r,op:e,table:t})},Mt=async(e,t,r,c,l)=>{l&&Y(r);const p=await e.insert(t,r,c);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Wn=(e,t)=>Ct(e,"relation load").findMany(e,t),Bn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Dt=e=>{for(const t of e===void 0?[]:Bn(e))se(t)&&L(t,G)},kt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[c,l]of Object.entries(t??{})){if(c==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Dt(r[d]);continue}const p=r[c];p===void 0||l===void 0||l===!1||(Dt(p),typeof l=="object"&&kt(p.table,l.with))}},ot=(e,t)=>(se(e)&&(L(e,G),kt(e,t.with)),Wn(e,t)),qn=e=>!se(e.table),Lt=n.relationExistsPushDown??"auto",Ft=Lt!=="never",{maxRelationKeys:Wt}=n,Le=(e,t,r)=>Vo(e,{fetcher:ot,maxRelationKeys:Wt,relationBaseWhere:r,schema:u,tableName:t}),Pn=async(e,t,r,c,l)=>{const p=H(e,"relation grouped count");if(p)return _e(e,{relationBaseWhere:l,where:c}),tr((B,N)=>p.count(B,{relationBaseWhere:l,where:N}),e,t,r,c);const d=u.tables[e];if(!d)throw new R("INTERNAL",`unknown table: ${e}`);L(e,G);const h=be(d.softDeleteMode,void 0),m={[t]:{in:r}},M=Q(Q(m,c),h),_=await Le(M,e,l),T=ee(_,pe),S=ge(t);let b=f`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;T&&(b=f`${b} WHERE ${T}`),b=f`${b} GROUP BY ${S}`;const $=K(y,b).toArray();return new Map($.map(B=>[B.__fk__,B.count]))},Bt=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Bt.add(`${e} ${r.timing} ${r.op}`);const oe=(e,t,r)=>Bt.has(`${e} ${t} ${r}`),re=async(e,t,r)=>{if(w.value+=1,w.value>cn)throw w.value-=1,new de(`trigger recursion exceeded ${String(cn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await sr({ctx:Vn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{w.value-=1}},{ensureBackfilledForTable:Te,ensureBackfilledIndex:rt,ensureRankBackfilled:it,ensureRankBackfilledForTable:Ae,syncAggregates:Fe,syncCompanionsForInsert:st,syncGeo:We,syncRanks:he,syncSearch:Be}=lo({broadcast:C,indexKeysFor:(e,t)=>V(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,V(e,r)),recordCdc:Se,schema:u,sql:y,verified:n.companionMemo?.verified}),Un=async(e,t)=>{const r=t.filter(({document:c,id:l})=>{try{return st(e,l,c),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:c,id:l}of r)if(X(l,e)?.docJson===ae(c))try{await le({doc:c,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},qt=(e,t,r)=>{const{shardMode:c}=t;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(r.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${c.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Pt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ie=e=>e===void 0||se(e)?ve:void 0,On=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(c=>c.through!==void 0||c.kind!=="one"||c.table!==e?[]:c.onDelete!=="cascade"&&c.onDelete!=="set null"?[]:[{action:c.onDelete==="cascade"?"delete":"update",field:c.field,holderTable:t,references:c.references}]):[]),Gn=async(e,t,r,c)=>r==="_id"?c:(await e.get(t,c))?.[r],jn=async(e,t,r,c,l)=>{const p=[];let d;do{const h=await e.findMany(t,{cursor:d,includeDeleted:l,limit:wi,where:{[r]:c}});for(const m of h.page)p.push(String(m._id));d=h.isDone?void 0:h.continueCursor??void 0}while(d!==void 0&&p.length<=nr);return p},Hn=async(e,t,r,c,l,p)=>{const{action:d,field:h,holderTable:m,references:M}=r,_=await Gn(e,t,M,c);if(_==null)return{effects:[],toExpand:[]};const T=await jn(e,m,h,_,p),S=T.filter($=>!l.announced.has(`${d}:${m}:${$}`)),b=d==="delete"?T.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of S)l.announced.add(`${d}:${m}:${$}`);for(const $ of b)l.expanded.add(`${m}:${$}`);return{effects:S.map($=>({id:$,op:d,table:m})),toExpand:b}},Ut=async(e,t,r,c,l)=>{const p=[];for(const d of On(t))for(const h of r){const m=await Hn(e,t,d,h,c,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await Ut(e,d.holderTable,m.toExpand,c,l))}return p},ct=async(e,t,r,c,l)=>{for(let d=0;d<r.length;d+=1)Y(void 0);const p=c?.skipOnDelete===!0?[]:await Ut(e,t,r,{announced:new Set,expanded:new Set},c?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,c)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},X=(e,t)=>{const r=Pt(t);for(let c=0;c<r.length;c+=an){const l=r.slice(c,c+an),[p]=ye(y,kr(l),...Lr(e,l)).toArray();if(!p)continue;const d=p.__t__,h=Ce(p);if(typeof d!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:ae(m??{}),row:h,tableName:d}}},Ot={assertRankPartitionLocal:qt,ensureRankBackfilled:it,onRead:L,rowToDocument:Ce,schema:u,sql:y},Kn=(e,t,r)=>{const c=ee(r,pe);return c===void 0||K(y,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${c}`).toArray().length>0},Nn=(e,t,r,c)=>xt(e,t,r,c)?(o?.({fields:Object.keys(Qe(r)),id:t,table:e}),!0):!1,Qn=async(e,t,r,c,l)=>{const p=X(t,e);if(!p)return{applied:!1,doc:null};if(L(e,t),!Kn(e,t,r.where)||Nn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&c)return;throw d}return{applied:!0,doc:X(t,e)?.row??null}},Gt=async(e,t,r,c)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:h}=await Jo(t,r,{canPushExists:Ft?qn:void 0,existsPushMode:Lt==="always"?"always":"auto",fetcher:ot,maxRelationKeys:Wt,schema:u,tableName:e}),m=Ft?Vr(c):Ze,M=ee(h,m,Xe),_=bn(e,M,xn(d),l);return{limit:p,orderKeys:d,statement:_}},O={system:Fn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return _e(e,t),r.aggregate(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,G);const l=be(c.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await Le(p,e,t.relationBaseWhere),h=d!==p;if(c.aggregateIndexes&&!t.baseWhere&&!h){const $=no(c.aggregateIndexes,t.op,t.field,t.where);if($){rt(e,$.index);const B=dt($.index.by??[],$.key),N=at(e,$.index.name),J=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(N)} WHERE ${je} = ${B}`).toArray()[0];return lt(t.op,J)}}un(c,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=ee(d,pe),M=Oe(t.op),_=ge(t.field);let T=f`SELECT ${f.raw(M)}(${_}) AS value FROM ${f.identifier(e)}`;m&&(T=f`${T} WHERE ${m}`);const b=K(y,T).toArray()[0]?.value;return b??null},asId(e,t){const r=fn(u,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return _e(e,Ht(t)),r.count(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=Ht(t);if(l.restrictsCounts)throw new ut(e);L(e,G);const p=be(c.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),h=await Le(d,e,l.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!l.baseWhere&&!m){const S=to(c.aggregateIndexes,l.where);if(S){rt(e,S.index);const b=dt(S.index.by??[],S.key),$=at(e,S.index.name),B=K(y,f`SELECT ${Ge} AS value FROM ${f.identifier($)} WHERE ${je} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const M=ee(h,pe);let _=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return M&&(_=f`${_} WHERE ${M}`),K(y,_).one().count},async delete(e,t,r){I(e,"ctx.db.delete(table, id)");const c=X(t,e);if(!c){const S=Ie(e);S&&await ct(S,e,[t],r);return}const{docJson:l,row:p,tableName:d}=c,h=u.tables[d],m=r?.hard===!0,M=!m&&h?.softDeleteMode?h:void 0,_=M?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(oe(d,"before","delete")&&await re("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await er({deletedId:t,deletedReference:S=>p[S],findHolders:async(S,b,$,B)=>(await nt(S).findMany(S,{...B,includeDeleted:m,where:{[b]:$}})).page,onCascade:(S,b)=>nt(S).delete(S,b,r),onRestrict:S=>{throw new de(S,"restrict")},onSetNull:(S,b,$)=>nt(S).patch(S,b,{[$]:null}),schema:u,tableName:d}),Te(d),Ae(d),M&&_){const S={[_]:Re()},b={...p,...te(d),...S,_id:t};pt(M,S,b,fe),Ve(y,d,rn(d),[ae(b),t,l]),Be(d,t,b,p),We(d,t,void 0),Fe(d,p,b),he(d,t,p,void 0);const $=V(d,p,b);ue?.invalidate(d,t,$),Se(d,t,"update",b),C({indexKeys:$,key:t,op:"update",row:b,table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d});return}Ve(y,d,Cr(d),[t,l]),Be(d,t,void 0),We(d,t,void 0),Fe(d,p,void 0),he(d,t,p,void 0);const T=V(d,p);ue?.invalidate(d,t,T),Se(d,t,"delete"),C({indexKeys:T,key:t,op:"delete",table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Tn),c=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(l===void 0?O.delete(e,m,c):ct(l,e,[m],c)),p+=1;if(h.length<r)break}return{deleted:p}},async deleteMany(e,t,r){I(e,"ctx.db.deleteMany(table, ids)"),Ne(t.length,r?.limit,"deleteMany");for(const c of t)await O.delete(e,c);return{deleted:t.length}},async deleteWhere(e,t,r){const c=H(e,"deleteWhere"),p=(await dn(c??O,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(c)return ct(c,e,p,void 0,{options:r});if(O.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,r)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await O.findFirst(e,t);if(r===null)throw new To(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return _e(e,t),t.consistency==="primary"&&v(e,uo),r.findMany(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?L(e,G):L(e);const{limit:p,orderKeys:d,statement:h}=await Gt(e,c,t,L),m=ye(y,h.text,...h.params).toArray();l&&s?.recordRead(m.length);const M=[];for(const T of m){const S=Ce(T);S&&(M.push(S),!l&&typeof S._id=="string"&&L(e,S._id))}const _=No(M,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Xo({fetcher:ot,groupedCounter:Pn,parents:_.page,...Zo(t),schema:u,tableName:e,with:t.with}),{..._,page:_n(_.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Gt(e,c,t,()=>{}),p=ye(y,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){I(e,"ctx.db.get(table, id)");const r=X(t,e);if(!r){const c=Ie(e);return c?(v(e,t,!0),c.get(e,t)):(D(e),v(e,t,!0),null)}return Ee(r,t),r.row},async lookupById(e,t){const r=X(e,t);if(!r){for(const c of Pt(t))D(c),v(c,e,!0);return null}return Ee(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return _e(e,t),r.groupBy(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);L(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=be(c.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),h=await Le(d,e,t.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!t.baseWhere&&!m){const $=eo(c.aggregateIndexes,l.op,l.field,t.by,t.where),B=$===void 0?0:Object.keys($.partial).length,N=$?.index.by?.length??0;if($&&(B===0||B===N)){rt(e,$.index);const J=at(e,$.index.name),z=Object.keys($.partial),we=[];if(z.length===($.index.by??[]).length&&z.length>0){const qe=dt($.index.by??[],$.partial),Pe=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)} WHERE ${je} = ${qe}`).toArray();return Pe.length>0&&we.push({key:{...$.partial},value:lt(l.op,Pe[0])}),we}const Jn=K(y,f`SELECT ${je} AS key, ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)}`).toArray();for(const qe of Jn){const Pe=Xn(JSON.parse(qe.key));we.push({key:Pe,value:lt(l.op,qe)})}return we}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const B=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;un(c,$,B)}const M=ee(h,pe),_=t.by.map($=>f`${ge($)} AS ${f.identifier($)}`);if(l.op==="count")_.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(f`${f.raw(Oe(l.op))}(${ge($)}) AS value`)}let T=f`SELECT ${f.join(_,f`, `)} FROM ${f.identifier(e)}`;M&&(T=f`${T} WHERE ${M}`),T=f`${T} GROUP BY ${f.join(t.by.map($=>ge($)),f`, `)}`;const S=K(y,T).toArray(),b=[];for(const $ of S){const B={};for(const J of t.by)B[J]=wo(c.shape[J],$[J]??null);const{value:N}=$;b.push({key:B,value:N==null?null:Number(N)})}return b},async insert(e,t,r){const c=H(e,"insert");if(c)return Mt(c,e,t,r,!0);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=He(l,Et(l,t,fe),{supplied:t,trusted:p});let h;r?.clientId!==void 0?(Wr(r.clientId),h=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),h=d._id):h=At();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Re(),M={...d,...te(e),_creationTime:m,_id:h};return oe(e,"before","insert")&&await re("before","insert",{doc:{...M},id:h,op:"insert",table:e}),p||q(e,M),Te(e),Ae(e),vt(y,e,br(e),[h,m,ae(M)]),st(e,h,M),oe(e,"after","insert")&&await re("after","insert",{doc:M,id:h,op:"insert",table:e}),await me({doc:M,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,r){if(Ne(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const c=H(e,"insert");if(c){const _=[];Br(u.tables[e],t,r?.allowExplicitId,fe);for(const T of t)Y(T);for(const T of t){const S=await c.insert(e,T,{allowExplicitId:r?.allowExplicitId});C({key:S,op:"insert",row:{...T,_id:S},table:e}),_.push(S)}return _}const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);Te(e),Ae(e);const p=[];for(let _=0;_<t.length;_+=Ke)p.push(te(e));const d=r?.allowExplicitId===!0?void 0:Yo(l),h=t.map((_,T)=>{const S=Et(l,_,fe),b=d===void 0?S:He(d,S,{supplied:_}),$=r?.allowExplicitId===!0&&typeof b._id=="string"?b._id:void 0;$!==void 0&&Rt($);const B=$??At(),N=r?.allowExplicitId===!0&&typeof b._creationTime=="number"?b._creationTime:Re(),J={...b,...p[Math.floor(T/Ke)],_creationTime:N,_id:B};return{creationTime:N,document:J,id:B}});for(const _ of h)Y(_.document);const m=async _=>{for(const{document:T,id:S}of _)st(e,S,T);for(const{document:T,id:S}of _)await le({doc:T,id:S,op:"insert",table:e})};let M=0;try{for(let _=0;_<h.length;_+=Ke){const T=h.slice(_,_+Ke),S=f.join(T.map($=>f`(${$.id}, ${$.creationTime}, ${ae($.document)})`),f`, `),b=Rn("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${S}`);vt(y,e,b.sql,b.params),M=_+T.length}}catch(_){throw await Un(e,h.slice(0,M)),_}return await m(h),h.map(_=>_.id)},async insertMany(e,t,r){Ne(t.length,r?.limit,"insertMany");const c=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const h of t)Y(h);const d=async h=>p?Mt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{l.push(await d(h))}catch(m){if(c&&m instanceof de&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return fn(u,e,t)},async patch(e,t,r,c){I(e,"ctx.db.patch(table, id, values)");const l=X(t,e);if(!l){const b=Ie(e);if(b){Y(r);try{await b.patch(e,t,r,c)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new R("INTERNAL",`unknown table: ${h}`);if(L(h,t),wn("patch",r),xt(h,t,r,d)){o?.({fields:Object.keys(Qe(r)),id:t,table:h});return}const M=Ao(m,r,d),_={...d,...Qe(M),...te(h),_id:t};pt(m,M,_,fe);const T=He(m,_,{only:new Set(Object.keys(M)),previous:()=>d,tolerateStoredNull:!0});Io(c,d,T),oe(h,"before","update")&&await re("before","update",{doc:{...T},id:t,op:"update",previous:d,table:h}),q(h,T,d),Te(h),Ae(h),Ve(y,h,rn(h),[ae(T),t,p]),Be(h,t,T,d),We(h,t,T),Fe(h,d,T),he(h,t,d,T);const S=V(h,d,T);ue?.invalidate(h,t,S),Se(h,t,"update",T),C({indexKeys:S,key:t,op:"update",row:T,table:h}),oe(h,"after","update")&&await re("after","update",{doc:T,id:t,op:"update",previous:d,table:h}),await me({doc:T,id:t,op:"update",table:h})},async patchIf(e,t,r){const c=H(e,"patchIf");if(c){if(c.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);Y(r.patch);let l;try{l=await c.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=hn;l+=1){const p=await Qn(e,t,r,l<hn,d=>O.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){I(e,"ctx.db.patchMany(table, patches)"),Ne(t.length,r?.limit,"patchMany");for(const c of t)await O.patch(e,c.id,c.patch);return{patched:t.length}},async patchWhere(e,t,r){const c=H(e,"patchWhere")??O,p=(await dn(c,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(O.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,r),{patched:p.length}},async related(e,t){return Ko(O,A,e,t)},relationEdges:A,deleteRereadTables:W,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(L(e,G),t.query(e)):kn(y,u,e,ne,r=>{r?F(r):L(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const c=H(e,"rank");if(ne(e,t,"rank"),c)return L(e,G),c.rank(e,t,r);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(z=>z.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(qt(e,l,p),r.restrictsCounts)throw new ut(e);L(e,G),it(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const h=Yt(e,p.name),m=p.sortBy.map((z,we)=>Xt(we)),M=m.map(z=>ke(z)).join(", "),_=K(y,f`SELECT ${f.identifier("__partition__")}, ${f.raw(M)} FROM ${f.identifier(h)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[T]=_;if(T===void 0)return null;let S=T.__partition__;const b=Q(r.baseWhere,r.where);ht(b,u,e,"rank");const $=Lo(p,b);if($){const z=Fo(p.partitionBy??[],$);if(z!==S)return null;S=z}const B=m.map(z=>T[z]),{before:N,total:J}=gn(y,h,m,p.sortBy,S,B,d);return{position:N+1,total:J}},async rankBefore(e,t,r){if(se(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=c.rankIndexes?.find(m=>m.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ut(e);L(e,G),it(e,l);const p=Yt(e,l.name),d=l.sortBy.map((m,M)=>Xt(M)),h=l.sortBy.map((m,M)=>De(r.sortValues[M]??null));return gn(y,p,d,l.sortBy,r.partitionKey,h,r.rowId)},async rankPage(e,t,r={}){ht(Q(r.baseWhere,r.where),u,e,"rankPage");const c=H(e,"rankPage");if(ne(e,t,"rank"),c)return L(e,G),c.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Nt(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(h=>h.doc)}},async rankPageRows(e,t,r={}){ht(Q(r.baseWhere,r.where),u,e,"rankPage"),ne(e,t,"rank");const{directions:c,hasMore:l,rows:p}=Nt(Ot,e,t,r);return{directions:c,hasMore:l,rows:p}},async restore(e,t){I(e,"ctx.db.restore(table, id)");const r=X(t,e);if(!r){const d=Ie(e);if(d?.restore){try{await d.restore(e,t)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const c=u.tables[r.tableName]?.softDeleteMode?.field;if(!c)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[c]!==null&&r.row[c]!==void 0;await O.patch(e,t,{[c]:null});const p=l?X(t,e)?.row:void 0;p&&(he(r.tableName,t,p,void 0),he(r.tableName,t,void 0,p))},async replace(e,t,r,c){I(e,"ctx.db.replace(table, id, document)");const l=X(t,e);if(!l){const B=Ie(e);if(B){Y(r);try{await B.replace(e,t,r,c)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new R("INTERNAL",`unknown table: ${h}`);wn("replace",r);const M=c?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,T=M??_??Re(),S={...r,...te(h),_creationTime:T,_id:t};pt(m,r,S,fe);const b=c?.allowExplicitId===!0,$=He(m,S,{previous:()=>d,supplied:r,trusted:b});oe(h,"before","update")&&await re("before","update",{doc:{...$},id:t,op:"update",previous:d,table:h}),b||q(h,$,d),Te(h),Ae(h),Ve(y,h,xr(h),[T,ae($),t,p]),Be(h,t,$,d),We(h,t,$),Fe(h,d,$),he(h,t,d,$),ue?.invalidate(h,t,V(h,d,$)),Se(h,t,"update",$),C({indexKeys:V(h,d,$),key:t,op:"update",row:$,table:h}),oe(h,"after","update")&&await re("after","update",{doc:$,id:t,op:"update",previous:d,table:h}),await me({doc:$,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,c=Object.entries(u.tables).filter(([h,m])=>t.has(h)||r!==void 0&&!r.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(r!==void 0){for(const h of r)if(!u.tables[h])throw new R("INTERNAL",`wipeShard: unknown table: ${h}`)}const l={};let p=0;const{deleteAll:d}=O;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of c){const m=await d(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Vn={db:O,scheduler:It};return n.enforceRls===!0?or(O,u,(e,t)=>X(e,t)?.tableName,A):O};export{cs as CDC_LOG_TABLE,xs as IDEMPOTENCY_TABLE,Jr as NotUniqueError,Ts as advanceClientWatermark,as as applyCdcChanges,wn as assertNoExplicitUndefined,Rt as assertStorableRowId,Wr as assertValidClientId,os as backfillAggregateIndexes,rs as backfillRankIndexes,is as backfillSearchIndexes,ds as bumpCdcEpoch,ls as cdcCanVouchFor,us as cdcForkedError,fs as cdcSeqLeavingRows,hs as cdcTouchesTables,ws as cdcTrimmedError,ps as compactCdcDocs,pi as createShardCtxDb,gs as cursorBelowRetainedFloor,si as meterReadBytes,As as migrateClientWatermark,ys as minCdcReplayableSeq,$s as minCdcSeq,fn as normalizeIdStructurally,Es as readCdcChangeKeys,ms as readCdcChanges,Rs as readCdcCursor,vs as readCdcEpoch,Is as readClientWatermark,Cs as readIdempotent,Ls as runShardMigrations,Ws as selectShapeMembers,Bs as selectShapeRows,Qe as stripReservedPatchFields,Ss as trimCdcChanges,Ms as trimIdempotent,Ds as writeIdempotent};
1
+ import{LunoraError as v}from"@lunora/errors";import{q as _t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as zn,l as Ue,s as Yn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Xn,stableWireKey as jt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as Zn,aggregateSqlFunction as Oe,normalizeCountArgument as Ht}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as at,encodeAggregateKey as dt,readAggregateValue as lt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as ut,selectIndexForGroupBy as eo,selectIndexForCount as to,selectIndexForAggregate as no}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as oo,searchIndexCoversTable as ro}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{backfillAggregateIndexes as os,backfillRankIndexes as rs,backfillSearchIndexes as is}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{appendCdcChange as io,readCdcDocAtOrBefore as so}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{CDC_LOG_TABLE as cs,applyCdcChanges as as,bumpCdcEpoch as ds,cdcCanVouchFor as ls,cdcForkedError as us,cdcSeqLeavingRows as fs,cdcTouchesTables as hs,cdcTrimmedError as ws,compactCdcDocs as ps,cursorBelowRetainedFloor as gs,minCdcReplayableSeq as ys,minCdcSeq as $s,readCdcChangeKeys as Es,readCdcChanges as ms,readCdcCursor as Rs,readCdcEpoch as vs,trimCdcChanges as Ss}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{allocateCommitSeq as co,COMMIT_SEQ_FIELD as ao}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as lo}from"./createCompanionSync-DmciS_rv.mjs";import{isMemoryTable as Kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Qt}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as uo}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as ye,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as fo,j as yt,D as ie,r as Ce,W as ho,k as ae,b as Ge,A as ft,a as je,m as pe,e as ge,s as wo,t as po,u as go,i as yo,q as Nt,h as mn,g as $o}from"./do-sql-Cf2rnuLV.mjs";import{renderSql as Rn,unionAll as vn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as Eo,u as mo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as Ro,boundingBoxGeohashes as vo,haversineMeters as So,pointInBoundingBox as _o}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as To}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Ao,assertPatchAllowed as Io,operatorFields as bo,readPatchField as Vt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as xo,encodeCursor as $t,nullsOrderSuffix as Co,normalizeOrderKeys as Jt,uniqueIndexFields as Mo,buildSeekWhere as Do,decodeCursor as zt,buildSeekBeforeWhere as ko,softDeleteScope as be,applySelect as _n}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Yt,sortColumnName as Xt,resolveRankPartition as Lo,encodePartitionKey as Fo,RANK_TIEBREAK as Wo,rankPivotConditionSql as Bo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Zt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as qo,withUnknownIndexKeys as Po,indexKeysForRow as Uo,buildIndexRange as Oo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Je,j as Me,c as ee,t as Xe,i as en}from"./where-sql-Cb_dSAMj.mjs";import{serializeSqlValue as De}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as ke}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Go,isPushableWhere as jo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Ho,findRelated as Ko}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ht,findManyPage as Qo,relationPredicateTables as No,resolveRelationPredicates as Vo,composeReadPredicate as Jo}from"./DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs";import{describeRelationWrites as zo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as He,transformOnlyDefinition as Yo,applyInsertDefaults as Et,resolveWith as Xo,relationHooks as Zo,applyOnDelete as er,fanOutScalarCounts as tr,CASCADE_MAX_ROWS as nr}from"./applyInsertDefaults-CaVH3fJ7.mjs";import{guardWriter as or}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as ir}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as tn,runTriggers as sr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ts,migrateClientWatermark as As,readClientWatermark as Is}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as xs,readIdempotent as Cs,trimIdempotent as Ms,writeIdempotent as Ds}from"./IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{runShardMigrations as Ls}from"./runShardMigrations-4_ene2xR.mjs";import{selectShapeMembers as Ws,selectShapeRows as Bs}from"./selectShapeMembers-Ce6pOHKe.mjs";const cr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ar=()=>new v("INVALID_CURSOR","invalid cursor"),nn=16,on=8,Z=1024,Tt=(n,i)=>i.query(n),dr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,a]of i.entries()){const w=s===i.length-1;let g=0;for(const E of n)(w?E.startsWith(a):E===a)&&(g+=1);if(g===0)return 0;o+=g}return o},lr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const a=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:a+String.fromCodePoint(s)}},ur=(n,i,o)=>{const s={eq:(a,w)=>{if(!n.definition.filterFields?.includes(a))throw new v("INTERNAL",`field "${a}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=on)throw new v("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(on)} .eq() filters are supported per search query`);return n.filters.push({field:a,value:w}),s},search:(a,w)=>{const g=n;if(a!==g.definition.field)throw new v("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${a}"`);const E=Tt(w,o).length;if(E>nn)throw new v("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(nn)} search terms are supported (got ${String(E)})`);return g.field=a,g.query=w,g.hasQuery=!0,s}};return s},fr=n=>{if(n.length>Z)throw new v("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},hr=n=>Math.min(n.offset+n.numItems+1,Z),wr=n=>btoa(`search:${String(n)}`),pr=n=>{let i;try{i=cr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},gr=n=>{if(typeof n.endCursor=="string")throw new v("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new v("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?pr(n.cursor):0;if(o===void 0)throw ar();if(o+i>=Z)throw new v("BAD_REQUEST",`search pagination reaches the ${String(Z)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},yr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?wr(o):null,isDone:!s,page:n.slice(i.offset,o)}},$r=n=>{if(n===void 0)return Z+1;if(!Number.isFinite(n))return Z;const i=Math.max(0,Math.floor(n));if(i>Z)throw new v("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Tn=500,An=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??Tn},In=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Er=32,mr=1024,bn=(n,i,o,s)=>{const a=`SELECT id, _creationTime, ${ke(ie)} FROM ${ke(n)}`,w=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${a} ${w}`):Me(`${a} WHERE `,i,` ${w}`)},Ze={fieldRef:n=>Je(yt(n)),rangeTypeGuard:(n,i)=>Je(fo(n,i)),serialize:De},Rr=n=>n===void 0?"":Co(n==="first"),xn=n=>{const i=n.map(o=>`${yt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${yt("id")} ${xo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},vr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Cn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Sr=n=>{const i=Cn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},_r=(n,i)=>{const o=n.order,s=Sr(n),{shape:a}=i;return s.length>0?Jt(s.map(w=>({[w]:o})),a,{pinned:Cn(n),uniqueBy:Mo(i.indexes,a)}):Jt([{_creationTime:o}],a)},Tr=(n,i,o,s)=>{const a=n.sqlConditions.map(w=>({[w.field]:{[vr[w.comparator]??"eq"]:w.value}}));if(o&&a.push(Do(i,zt(o))),s&&a.push(ko(i,zt(s))),a.length!==0)return a.length===1?a[0]:{AND:a}},Ar=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Er):n.want},mt=(n,i,o,s,a,w,g)=>{const E=_r(s,o),y=xn(E),u=[],{filters:C,want:A}=w;let T=w.cursor??void 0,b=Ar(w);if(A===0)return{documents:u,orderKeys:E};for(;;){const q=ee(Tr(s,E,T,w.endCursor),Ze,Xe),P=bn(i,a&&q?Me(q," AND ",a):a??q,y,b),W=ye(n,P.text,...P.params).toArray();let U={};g(W.length);for(const j of W)if(U=Ce(j),C.every(te=>te(U))&&u.push(U)===A)return{documents:u,orderKeys:E};if(b===void 0||W.length<b)return{documents:u,orderKeys:E};T=$t(U,E),b=Math.max(b,Math.min(b*2,mr))}},Ir=(n,i,o,s,a,w,g,E)=>{const y=Math.max(0,Math.floor(a.numItems));if(typeof a.endCursor=="string"){const{documents:q,orderKeys:P}=mt(n,i,o,s,w,{cursor:a.cursor,endCursor:a.endCursor,filters:g.all,selective:g.selective,want:void 0},E),W=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:a.endCursor,isDone:!0,page:q,splitCursor:W?$t(W,P):null}}const{documents:u,orderKeys:C}=mt(n,i,o,s,w,{cursor:a.cursor,filters:g.all,selective:g.selective,want:y+1},E),A=u.length>y,T=A?u.slice(0,y):u,b=T.at(-1);return{continueCursor:A&&b?$t(b,C):null,isDone:!A,page:T}},et=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const a=n(ke(o));return i.set(o,a),a}},$e=ke(ie),br=et(n=>`INSERT INTO ${n} (id, _creationTime, ${$e}) VALUES (?, ?, ?)`),rn=et(n=>`UPDATE ${n} SET ${$e} = ? WHERE id = ? AND ${$e} = ?`),xr=et(n=>`UPDATE ${n} SET _creationTime = ?, ${$e} = ? WHERE id = ? AND ${$e} = ?`),Cr=et(n=>`DELETE FROM ${n} WHERE id = ? AND ${$e} = ?`),Mr="SELECT changes() AS changed",sn=new Map,Dr="",kr=n=>{const i=JSON.stringify(n),o=sn.get(i);if(o!==void 0)return o;const s=n.map(w=>f`SELECT ${f.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(w)} WHERE id = ${Dr}`),{sql:a}=Rn("sqlite",f`${vn(s)} LIMIT 1`);return sn.set(i,a),a},Lr=(n,i)=>i.map(()=>n),Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wr=n=>{if(!Fr.test(n))throw new v("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new v("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Br=(n,i,o,s)=>{if(o!==!0)return;const a=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const g=a?Et(n,w,s)._id:w._id;typeof g=="string"&&Rt(g)}},cn=50,Ke=Math.floor(Sn.boundParams/3),an=Sn.boundParams,qr=128,ze=n=>new v("BATCH_LIMIT_EXCEEDED",n,{status:400}),Qe=(n,i,o)=>{In(n,An(i,o,ze),o,ze)},dn=async(n,i,o,s,a)=>{const w=An(s,a,ze),{page:g}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>w&&In(Math.max(await n.count(i,{where:o}),g.length),w,a,ze),g},Pr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Ur=n=>Math.max(n,Z),Mn=(n,i)=>{const o=n.filters.map(s=>f`${ge(s.field)} = ${De(s.value)}`);return i&&o.push(i),o},Or=(n,i,o,s,a)=>{const w=Tt(o.query,_t(o.definition.language));if(w.length===0)return[];const g=zn(i,o.indexName),E=`${g}__vocab`,y=w.length-1,u=w.map((P,W)=>{const U=lr(P,W===y),j=U.exact?f`${f.identifier("term")} = ${U.lower}`:f`${f.identifier("term")} >= ${U.lower} AND ${f.identifier("term")} < ${U.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(W))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(E)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=w.map((P,W)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(W))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),A=f`SELECT f.${f.identifier(Ue)} AS ${f.identifier(Ue)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${vn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Ue)} HAVING ${f.join(C.map(P=>f`${P} > 0`),f` AND `)}`,T=Mn(o,a);let b=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${A}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Ue)}`;T.length>0&&(b=f`${b} WHERE ${f.join(T,f` AND `)}`),b=f`${b} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const q=[];for(const P of K(n,b)){const W=mn(P);if(W){const U=P.__score__;q.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return q},Gr=(n,i,o,s,a)=>{const w=_t(o.definition.language),g=Tt(o.query,w);if(g.length===0)return[];const E=Mn(o,a);let y=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;E.length>0&&(y=f`${y} WHERE ${f.join(E,f` AND `)}`),y=f`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Ur(s)))}`;const u=K(n,y).toArray(),C=[];for(const A of u){const T=mn(A);if(!T)continue;const b=dr(Yn(T,o.definition),g);b>0&&C.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:b})}return C.sort((A,T)=>T.score-A.score||T.creationTime-A.creationTime||A.id.localeCompare(T.id)),C.slice(0,s).map(A=>({document:A.doc,score:A.score}))},wt=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new v("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},jr=(n,i)=>{const o=n,s={near:(a,w)=>{if(o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:a.lat,lng:a.lng},radiusMeters:w},s},within:a=>{if(o.near)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a.sw,".within() sw corner",i,o.indexName),wt(a.ne,".within() ne corner",i,o.indexName),a.sw.lat>a.ne.lat)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(a.sw.lng>a.ne.lng)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:a.ne.lat,lng:a.ne.lng},sw:{lat:a.sw.lat,lng:a.sw.lng}},s}};return s},Hr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:a}=o;return typeof s=="number"&&typeof a=="number"?{lat:s,lng:a}:void 0},Kr=(n,i)=>{const o=Hr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const a=So(i.near.point,o);return a<=i.near.radiusMeters?{creationTime:s,distance:a}:void 0}return _o(o,i.within)?{creationTime:s,distance:0}:void 0},Qr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const a=o.near?Ro(o.near.point,o.near.radiusMeters):vo(o.within),w=$o(i,o.indexName),g=a.map(A=>f`(g.${f.identifier("__geohash__")} >= ${A} AND g.${f.identifier("__geohash__")} < ${`${A}{`})`),E=[f`(${f.join(g,f` OR `)})`];s&&E.push(s);const y=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(w)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(E,f` AND `)}`,u=K(n,y).toArray(),C=[];for(const A of u){const T=Ce(A),b=T?Kr(T,o):void 0;T&&b&&C.push({creationTime:b.creationTime,distance:b.distance,doc:T})}return C.sort((A,T)=>A.distance-T.distance||T.creationTime-A.creationTime),C},Dn=(n,i,o,s)=>{const a=[];for(const w of n)if(i.every(g=>g(s(w)))&&(a.push(w),typeof o=="number"&&a.length>=o))break;return a},Nr=(n,i,o,s,a,w=()=>{})=>{const g=o.within!==void 0,E=Qr(n,i,o,a).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return w(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},ln=(n,i,o,s,a,w,g=()=>{})=>{const{geo:E}=o;if(!E)throw new v("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=a.length>0,u=Nr(n,i,E,y?void 0:w,s,g);return y?Dn(u,a,w,C=>C.document):u},un=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&rr(s))throw new v("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vr=n=>{let i=0;const o=[],s={...Ze,relationExists:a=>{const{childWhere:w,negated:g,parentTable:E,relation:y}=a,u=`__rel_${String(i)}`,C=o.at(-1)??E;i+=1,n(y.table,G);const A=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,b=Je(`${Nt(u,T)} = ${Nt(C,A)}`);o.push(u);const q=ee(w,s,Xe);o.pop();const P=q===void 0?b:Me(b," AND ",q),W=Me("EXISTS (SELECT 1 FROM ",en(y.table)," AS ",en(u)," WHERE ",P,")");return g?Me("NOT ",W):W}};return s};class Jr extends v{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const zr=/\s/u,Yr=String.fromCodePoint(0),fn=(n,i,o)=>{if(!n.tables[i])throw new v("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||zr.test(o)||o.includes(Yr)?null:o},kn=(n,i,o,s=()=>{},a=()=>{},w=()=>{},g)=>{const E=i.tables[o];if(!E)throw new v("INTERNAL",`unknown table: ${o}`);const y=be(E.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const S=N(y,u.pushedWhere);return S?ee(S,pe):void 0},A=()=>{const S=N(y,u.pushedWhere);return S?ee(S,Ze,Xe):void 0},T=()=>[...u.inMemoryFilters,...u.verifyFilters];let b=0;const q=S=>{const{search:D}=u;if(!D)throw new v("INTERNAL","runSearchFetch called without a staged search");oo(go(n),o,E);const k=u.inMemoryFilters.length>0,F=$r(k?void 0:S),L=yo(n);if(L&&!ro(n,o,D.definition))throw new v("SEARCH_INDEX_BUILDING",`search index "${D.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Ee=C(),ne=L?Or(n,o,D,F,Ee):Gr(n,o,D,F,Ee);!k&&S===void 0&&fr(ne);const le=T();return b=ne.length,le.length>0?Dn(ne,le,S,Y=>Y.document):ne},P=S=>q(S).map(D=>D.document),W=S=>{const D=gr(S);return yr(P(hr(D)),D)},U=()=>{if(u.search||u.geo||u.indexName===void 0){a(void 0);return}a(Oo(o,u.indexName,u.indexFields,u.sqlConditions,De))},j=S=>{U();let D=0;const k=(()=>{if(u.search){const F=P(S);return D=b,F}return u.geo?ln(n,o,u,C(),T(),S,F=>{D=F}).map(F=>F.document):mt(n,o,E,u,A(),{filters:T(),selective:u.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{D+=F}).documents})();return w(Math.max(D,k.length)),k},te=()=>{if(!u.search&&!u.geo)throw new v("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const D=(()=>{if(u.search){const k=q(void 0);return S=b,k}return ln(n,o,u,C(),T(),void 0,k=>{S=k})})();return w(Math.max(S,D.length)),D},V={async*[Symbol.asyncIterator](){const S=kn(n,i,o,s,a,w,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await S.collect();return}let D;for(;;){const k=await S.paginate({cursor:D??null,numItems:qr});if(yield*k.page,k.isDone||k.continueCursor===null)return;D=k.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return te()},filter(S){const D=Go(S);return D!==void 0&&jo(D,E.shape)?(u.pushedWhere=N(u.pushedWhere,D),u.verifyFilters.push(S)):u.inMemoryFilters.push(S),V},async first(){return j(1)[0]??null},order(S){return u.order=S==="desc"?"desc":"asc",V},async paginate(S){let D=0;if(U(),u.search){const F=W(S);return w(F.page.length),F}if(u.geo)throw new v("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Ir(n,o,E,u,S,A(),{all:T(),selective:u.inMemoryFilters.length>0},F=>{D+=F});return w(Math.max(D,k.page.length)),k},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Jr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,D){const k=(E.geoIndexes??[]).find(L=>L.name===S);if(!k)throw new v("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:k,indexName:S};if(u.geo=F,D(jr(F,o)),!F.near&&!F.within)throw new v("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return V},withIndex(S,D){const k=E.indexes.find(F=>F.name===S);if(!k)throw new v("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),u.indexName=S,u.indexFields=k.fields,D&&D(Pr(u)),V},withSearchIndex(S,D){const k=(E.searchIndexes??[]).find(L=>L.name===S);if(!k)throw new v("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:S,query:""};if(u.search=F,D(ur(F,o,_t(k.language))),!F.hasQuery)throw new v("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return V}};return V},pt=(n,i,o,s)=>{const a=o;for(const[w,g]of po(n)){if(g.serverDefault){w in i&&(a[w]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(w in i)&&(a[w]=g.onUpdateFn())}},hn=5,wn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new v("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},pn=["_commitSeq","_creationTime","_id"],Ne=n=>pn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!pn.includes(i))):n,Xr=/unique constraint failed/i,Zr=n=>n instanceof Error&&Xr.test(n.message),ei=/string or blob too big/iu,ti=(n,i)=>{if(!(!(n instanceof Error)||!ei.test(n.message)))throw new v("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},vt=(n,i,o,s)=>{try{ye(n,o,...s)}catch(a){throw Zr(a)?new de(`unique constraint violation on "${i}"`,"unique"):(ti(a,i),a)}},Ve=(n,i,o,s)=>{if(vt(n,i,o,s),ye(n,Mr).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},gn=(n,i,o,s,a,w,g)=>{const E=[];for(let A=0;A<o.length+1;A+=1){const T=o[A],b=s[A],q=b?.direction==="desc"?"desc":"asc",P=T===void 0||b===void 0?f`${f.identifier(Wo)} < ${g}`:Bo(T,w[A],q,!1);if(P===void 0)continue;const W=[];for(let j=0;j<A;j+=1)W.push(f`${f.identifier(o[j])} IS ${w[j]}`);W.push(P);const[U]=W;E.push(W.length===1&&U!==void 0?U:f`(${f.join(W,f` AND `)})`)}const y=E.length>0?f.join(E,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a} AND (${y})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a}`).one();return{before:u.c,total:C.c}},ni=n=>{const i=new Map;for(const[s,a]of Object.entries(n.tables))for(const w of Object.values(a.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:s,op:w.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const a=new Set,w=[s];for(let g=w.pop();g!==void 0;g=w.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||tn(n,E,y))return!0;a.has(E)||(a.add(E),w.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,a])=>a.shardMode?.kind==="global"||tn(n,s,"delete")||o(s)).map(([s])=>s))},oi=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},gt=new WeakMap,ri=(n,i)=>{let o=gt.get(i.tables);if(!gt.has(i.tables)){const a=Object.keys(i.tables).map(w=>w.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=a.length===0?void 0:new RegExp(`"(${a.join("|")})"`,"gu"),gt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const a of n.matchAll(o))s.add(a[1]);return s.size===1?[...s][0]:void 0},ii=(n,i,o)=>{for(const s of n){const a=s,w=a?.[ie];if(typeof w=="string"){const g=a?.id,E=mo(w);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},si=(n,i,o)=>{if(i===void 0)return n;const s=(a,...w)=>{const g=n.exec(a,...w),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ri(a,o);let C=!1;const A=T=>{ii(T,i,u)};return g.toArray=()=>{const T=[];for(const b of{[Symbol.iterator]:y})A([b]),T.push(b);return T},g.one=()=>{C=!0;try{const T=E();return A([T]),T}finally{C=!1}},g[Symbol.iterator]=function*(){for(const b of{[Symbol.iterator]:y})C||A([b]),yield b},g};return new Proxy(n,{get:(a,w)=>w==="exec"?s:w===ho?a:Reflect.get(a,w,a)})},ci=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ai=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Eo(n);if(s===void 0)return;const a=n._id;typeof a=="string"?o.recordDocumentRead(`global\0${i}\0${a}`,s):o.recordReadBytes(s)},Ye=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const a=n;switch(i){case"lookup":{xe(a.row,typeof a.tableName=="string"?a.tableName:o,s);return}case"page":{for(const w of a.page??[])xe(w,o,s);return}case"rows":{for(const w of Array.isArray(n)?n:[n])xe(w,o,s);return}default:for(const w of Array.isArray(n)?n:[])xe(w.document,o,s)}},Ln=(n,i,o)=>new Proxy(n,{get:(s,a)=>{const w=Reflect.get(s,a,s);if(typeof w!="function")return w;if(a===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(w,s,[]))xe(y,i,o),yield y};const g=ai.get(a);return(...E)=>{const y=Reflect.apply(w,s,E);return g!==void 0?Promise.resolve(y).then(u=>(Ye(u,g,i,o),u)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Ln(y,i,o):y}}}),di=new Set(["findFirst","findFirstOrThrow","findMany"]),li=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),a=s.with,w=g=>_n(g,o,a);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:w(g.page)}:w([g])[0]}},yn=256,St=4096,ui=1024*1024,fi=async(n,i,o,s)=>{const a=i[1]??{},w=[];let{cursor:g}=a,E=yn,y=0;for(;;){const u=await n([i[0],{...a,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(u))return Ye(u,"rows",o,s),[...w,...u];const C=s.headroom().readBytes;if(Ye(u,"page",o,s),w.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:w};g=u.continueCursor,y+=s.headroom().readBytes-C,E=y>0?Math.min(St,Math.max(yn,Math.floor(ui*w.length/y))):St}},hi=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const a=Reflect.get(o,s,o);if(typeof a!="function")return a;if(s==="query")return(...g)=>Ln(Reflect.apply(a,o,g),String(g[0]),i);const w=ci.get(s);return w===void 0?a:async(...g)=>{const E=di.has(s)?li(g):void 0;let y=E?.args??g;const u=String(g[0]),C=y[1],A=s==="findMany"&&typeof C?.endCursor=="string",T=s==="findMany"&&typeof C?.limit!="number"&&!A;if(A&&typeof C.limit!="number"&&(y=[y[0],{...C,limit:St},...y.slice(2)]),T){const q=await fi(P=>Reflect.apply(a,o,P),y,u,i);return E===void 0?q:E.project(q,w)}const b=await Reflect.apply(a,o,y);return Ye(b,w,u,i),E===void 0?b:E.project(b,w)}}}),$n=new WeakMap,En=new WeakMap,wi=500,pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,a=$n.get(n)??{value:void 0},w=En.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};$n.set(e,a),En.set(e,w),g=pi(e)}return g},y=si(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),A=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new v("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},T=Ho(u),b=new Map;for(const e of T){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&b.set(e.sourceTable,[...b.get(e.sourceTable)??[],e])}const q=(e,t,r)=>{for(const c of b.get(e)??[]){const l=t[c.column];if(typeof l!="string"||r?.[c.column]===l||c.targetTable===e&&t._id===l)continue;if(K(y,f`SELECT 1 FROM ${f.identifier(c.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new v("VALIDATION_ERROR",`${c.name} references ${c.targetTable} row "${l}", which does not exist`)}},P=zo(u,n.inTransaction),W=ni(u),U=oi(u),j=()=>n.inTransaction?.()===!0,te=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((a.value===void 0||!j())&&(a.value=co(y)),{[ao]:a.value}),V=(e,...t)=>{const r=u.tables[e]?.indexes??[],c=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,c.push(qo(l))),c.push(...Po(r,Uo(r,p,De))));return c.length>0?c:void 0},S=n.onRead??(()=>{}),D=e=>{Kt(u.tables[e])&&S(Zt,Zt)},k=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{D(e.table),k(e)},L=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),D(e),S(e,t,r)},Ee=(e,t)=>{const r=e.row._id;L(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ne=n.onIndexUse??(()=>{}),le=n.onWrite??(()=>{}),Y=e=>{s?.recordWrite(e)},me=async e=>{Y(e.doc),await le(e)},{cache:ue}=n,Re=n.clock??(()=>Date.now()),At=n.idGenerator??(()=>crypto.randomUUID()),It=n.scheduler??Zn,ve=hi(n.globalDb,s),fe=n.auth??{identity:null,userId:null},bt=n.cdc??!1,tt=It,Fn=ir({scheduler:typeof tt.list=="function"&&typeof tt.get=="function"?tt:void 0,storage:n.storage}),Se=(e,t,r,c)=>{bt&&!Kt(u.tables[e])&&io(y,Re(),e,t,r,c)},xt=(e,t,r,c)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!bt)return!1;const p=i?.();if(p===void 0)return!1;const d=so(y,e,t,p);if(d===void 0)return!1;const h=bo(l,r);return Object.keys(Ne(r)).some(m=>!h.has(m)&&jt(Vt(d,m))!==jt(Vt(c,m)))},se=e=>u.tables[e]?.shardMode?.kind==="global",Ct=(e,t)=>{if(se(e)){if(!ve)throw new v("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}return O},nt=e=>Ct(e,"cascade"),H=(e,t)=>{if(se(e)){if(!ve)throw new v("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}},_e=(e,t)=>{L(e,G);for(const r of No(N(t.baseWhere,t.where),u,e,t.relationBaseWhere))L(r,G)},ce=(e,t,r)=>{ue?.invalidateTable(t),C({key:r,op:e,table:t})},Mt=async(e,t,r,c,l)=>{l&&Y(r);const p=await e.insert(t,r,c);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Wn=(e,t)=>Ct(e,"relation load").findMany(e,t),Bn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Dt=e=>{for(const t of e===void 0?[]:Bn(e))se(t)&&L(t,G)},kt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[c,l]of Object.entries(t??{})){if(c==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Dt(r[d]);continue}const p=r[c];p===void 0||l===void 0||l===!1||(Dt(p),typeof l=="object"&&kt(p.table,l.with))}},ot=(e,t)=>(se(e)&&(L(e,G),kt(e,t.with)),Wn(e,t)),qn=e=>!se(e.table),Lt=n.relationExistsPushDown??"auto",Ft=Lt!=="never",{maxRelationKeys:Wt}=n,Le=(e,t,r)=>Vo(e,{fetcher:ot,maxRelationKeys:Wt,relationBaseWhere:r,schema:u,tableName:t}),Pn=async(e,t,r,c,l)=>{const p=H(e,"relation grouped count");if(p)return _e(e,{relationBaseWhere:l,where:c}),tr((B,Q)=>p.count(B,{relationBaseWhere:l,where:Q}),e,t,r,c);const d=u.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);L(e,G);const h=be(d.softDeleteMode,void 0),m={[t]:{in:r}},M=N(N(m,c),h),_=await Le(M,e,l),x=ee(_,pe),R=ge(t);let I=f`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;x&&(I=f`${I} WHERE ${x}`),I=f`${I} GROUP BY ${R}`;const $=K(y,I).toArray();return new Map($.map(B=>[B.__fk__,B.count]))},Bt=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Bt.add(`${e} ${r.timing} ${r.op}`);const oe=(e,t,r)=>Bt.has(`${e} ${t} ${r}`),re=async(e,t,r)=>{if(w.value+=1,w.value>cn)throw w.value-=1,new de(`trigger recursion exceeded ${String(cn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await sr({ctx:Vn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{w.value-=1}},{ensureBackfilledForTable:Te,ensureBackfilledIndex:rt,ensureRankBackfilled:it,ensureRankBackfilledForTable:Ae,syncAggregates:Fe,syncCompanionsForInsert:st,syncGeo:We,syncRanks:he,syncSearch:Be}=lo({broadcast:C,indexKeysFor:(e,t)=>V(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,V(e,r)),recordCdc:Se,schema:u,sql:y,verified:n.companionMemo?.verified}),Un=async(e,t)=>{const r=t.filter(({document:c,id:l})=>{try{return st(e,l,c),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:c,id:l}of r)if(X(l,e)?.docJson===ae(c))try{await le({doc:c,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},qt=(e,t,r)=>{const{shardMode:c}=t;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(r.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${c.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Pt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ie=e=>e===void 0||se(e)?ve:void 0,On=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(c=>c.through!==void 0||c.kind!=="one"||c.table!==e?[]:c.onDelete!=="cascade"&&c.onDelete!=="set null"?[]:[{action:c.onDelete==="cascade"?"delete":"update",field:c.field,holderTable:t,references:c.references}]):[]),Gn=async(e,t,r,c)=>r==="_id"?c:(await e.get(t,c))?.[r],jn=async(e,t,r,c,l)=>{const p=[];let d;do{const h=await e.findMany(t,{cursor:d,includeDeleted:l,limit:wi,where:{[r]:c}});for(const m of h.page)p.push(String(m._id));d=h.isDone?void 0:h.continueCursor??void 0}while(d!==void 0&&p.length<=nr);return p},Hn=async(e,t,r,c,l,p)=>{const{action:d,field:h,holderTable:m,references:M}=r,_=await Gn(e,t,M,c);if(_==null)return{effects:[],toExpand:[]};const x=await jn(e,m,h,_,p),R=x.filter($=>!l.announced.has(`${d}:${m}:${$}`)),I=d==="delete"?x.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of R)l.announced.add(`${d}:${m}:${$}`);for(const $ of I)l.expanded.add(`${m}:${$}`);return{effects:R.map($=>({id:$,op:d,table:m})),toExpand:I}},Ut=async(e,t,r,c,l)=>{const p=[];for(const d of On(t))for(const h of r){const m=await Hn(e,t,d,h,c,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await Ut(e,d.holderTable,m.toExpand,c,l))}return p},ct=async(e,t,r,c,l)=>{for(let d=0;d<r.length;d+=1)Y(void 0);const p=c?.skipOnDelete===!0?[]:await Ut(e,t,r,{announced:new Set,expanded:new Set},c?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,c)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},X=(e,t)=>{const r=Pt(t);for(let c=0;c<r.length;c+=an){const l=r.slice(c,c+an),[p]=ye(y,kr(l),...Lr(e,l)).toArray();if(!p)continue;const d=p.__t__,h=Ce(p);if(typeof d!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:ae(m??{}),row:h,tableName:d}}},Ot={assertRankPartitionLocal:qt,ensureRankBackfilled:it,onRead:L,rowToDocument:Ce,schema:u,sql:y},Kn=(e,t,r)=>{const c=ee(r,pe);return c===void 0||K(y,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${c}`).toArray().length>0},Qn=(e,t,r,c)=>xt(e,t,r,c)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Nn=async(e,t,r,c,l)=>{const p=X(t,e);if(!p)return{applied:!1,doc:null};if(L(e,t),!Kn(e,t,r.where)||Qn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&c)return;throw d}return{applied:!0,doc:X(t,e)?.row??null}},Gt=async(e,t,r,c)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:h}=await Jo(t,r,{canPushExists:Ft?qn:void 0,existsPushMode:Lt==="always"?"always":"auto",fetcher:ot,maxRelationKeys:Wt,schema:u,tableName:e}),m=Ft?Vr(c):Ze,M=ee(h,m,Xe),_=bn(e,M,xn(d),l);return{limit:p,orderKeys:d,statement:_}},O={system:Fn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return _e(e,t),r.aggregate(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new v("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,G);const l=be(c.softDeleteMode,void 0),p=N(N(t.baseWhere,t.where),l),d=await Le(p,e,t.relationBaseWhere),h=d!==p;if(c.aggregateIndexes&&!t.baseWhere&&!h){const $=no(c.aggregateIndexes,t.op,t.field,t.where);if($){rt(e,$.index);const B=dt($.index.by??[],$.key),Q=at(e,$.index.name),J=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(Q)} WHERE ${je} = ${B}`).toArray()[0];return lt(t.op,J)}}un(c,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=ee(d,pe),M=Oe(t.op),_=ge(t.field);let x=f`SELECT ${f.raw(M)}(${_}) AS value FROM ${f.identifier(e)}`;m&&(x=f`${x} WHERE ${m}`);const I=K(y,x).toArray()[0]?.value;return I??null},asId(e,t){const r=fn(u,e,t);if(r===null)throw new v("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return _e(e,Ht(t)),r.count(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=Ht(t);if(l.restrictsCounts)throw new ut(e);L(e,G);const p=be(c.softDeleteMode,void 0),d=N(N(l.baseWhere,l.where),p),h=await Le(d,e,l.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!l.baseWhere&&!m){const R=to(c.aggregateIndexes,l.where);if(R){rt(e,R.index);const I=dt(R.index.by??[],R.key),$=at(e,R.index.name),B=K(y,f`SELECT ${Ge} AS value FROM ${f.identifier($)} WHERE ${je} = ${I}`).toArray();return B[0]===void 0?0:B[0].value??0}}const M=ee(h,pe);let _=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return M&&(_=f`${_} WHERE ${M}`),K(y,_).one().count},async delete(e,t,r){A(e,"ctx.db.delete(table, id)");const c=X(t,e);if(!c){const R=Ie(e);R&&await ct(R,e,[t],r);return}const{docJson:l,row:p,tableName:d}=c,h=u.tables[d],m=r?.hard===!0,M=!m&&h?.softDeleteMode?h:void 0,_=M?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(oe(d,"before","delete")&&await re("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await er({deletedId:t,deletedReference:R=>p[R],findHolders:async(R,I,$,B)=>(await nt(R).findMany(R,{...B,includeDeleted:m,where:{[I]:$}})).page,onCascade:(R,I)=>nt(R).delete(R,I,r),onRestrict:R=>{throw new de(R,"restrict")},onSetNull:(R,I,$)=>nt(R).patch(R,I,{[$]:null}),schema:u,tableName:d}),Te(d),Ae(d),M&&_){const R={[_]:Re()},I={...p,...te(d),...R,_id:t};pt(M,R,I,fe),Ve(y,d,rn(d),[ae(I),t,l]),Be(d,t,I,p),We(d,t,void 0),Fe(d,p,I),he(d,t,p,void 0);const $=V(d,p,I);ue?.invalidate(d,t,$),Se(d,t,"update",I),C({indexKeys:$,key:t,op:"update",row:I,table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d});return}Ve(y,d,Cr(d),[t,l]),Be(d,t,void 0),We(d,t,void 0),Fe(d,p,void 0),he(d,t,p,void 0);const x=V(d,p);ue?.invalidate(d,t,x),Se(d,t,"delete"),C({indexKeys:x,key:t,op:"delete",table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Tn),c=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(l===void 0?O.delete(e,m,c):ct(l,e,[m],c)),p+=1;if(h.length<r)break}return{deleted:p}},async deleteMany(e,t,r){A(e,"ctx.db.deleteMany(table, ids)"),Qe(t.length,r?.limit,"deleteMany");for(const c of t)await O.delete(e,c);return{deleted:t.length}},async deleteWhere(e,t,r){const c=H(e,"deleteWhere"),p=(await dn(c??O,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(c)return ct(c,e,p,void 0,{options:r});if(O.deleteMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,r)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await O.findFirst(e,t);if(r===null)throw new To(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return _e(e,t),t.consistency==="primary"&&S(e,uo),r.findMany(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?L(e,G):L(e);const{limit:p,orderKeys:d,statement:h}=await Gt(e,c,t,L),m=ye(y,h.text,...h.params).toArray();l&&s?.recordRead(m.length);const M=[];for(const x of m){const R=Ce(x);R&&(M.push(R),!l&&typeof R._id=="string"&&L(e,R._id))}const _=Qo(M,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Xo({fetcher:ot,groupedCounter:Pn,parents:_.page,...Zo(t),schema:u,tableName:e,with:t.with}),{..._,page:_n(_.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Gt(e,c,t,()=>{}),p=ye(y,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){A(e,"ctx.db.get(table, id)");const r=X(t,e);if(!r){const c=Ie(e);return c?(S(e,t,!0),c.get(e,t)):(D(e),S(e,t,!0),null)}return Ee(r,t),r.row},async lookupById(e,t){const r=X(e,t);if(!r){for(const c of Pt(t))D(c),S(c,e,!0);return null}return Ee(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return _e(e,t),r.groupBy(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);L(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=be(c.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),p),h=await Le(d,e,t.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!t.baseWhere&&!m){const $=eo(c.aggregateIndexes,l.op,l.field,t.by,t.where),B=$===void 0?0:Object.keys($.partial).length,Q=$?.index.by?.length??0;if($&&(B===0||B===Q)){rt(e,$.index);const J=at(e,$.index.name),z=Object.keys($.partial),we=[];if(z.length===($.index.by??[]).length&&z.length>0){const qe=dt($.index.by??[],$.partial),Pe=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)} WHERE ${je} = ${qe}`).toArray();return Pe.length>0&&we.push({key:{...$.partial},value:lt(l.op,Pe[0])}),we}const Jn=K(y,f`SELECT ${je} AS key, ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)}`).toArray();for(const qe of Jn){const Pe=Xn(JSON.parse(qe.key));we.push({key:Pe,value:lt(l.op,qe)})}return we}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const B=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;un(c,$,B)}const M=ee(h,pe),_=t.by.map($=>f`${ge($)} AS ${f.identifier($)}`);if(l.op==="count")_.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(f`${f.raw(Oe(l.op))}(${ge($)}) AS value`)}let x=f`SELECT ${f.join(_,f`, `)} FROM ${f.identifier(e)}`;M&&(x=f`${x} WHERE ${M}`),x=f`${x} GROUP BY ${f.join(t.by.map($=>ge($)),f`, `)}`;const R=K(y,x).toArray(),I=[];for(const $ of R){const B={};for(const J of t.by)B[J]=wo(c.shape[J],$[J]??null);const{value:Q}=$;I.push({key:B,value:Q==null?null:Number(Q)})}return I},async insert(e,t,r){const c=H(e,"insert");if(c)return Mt(c,e,t,r,!0);const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=He(l,Et(l,t,fe),{supplied:t,table:e,trusted:p});let h;r?.clientId!==void 0?(Wr(r.clientId),h=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),h=d._id):h=At();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Re(),M={...d,...te(e),_creationTime:m,_id:h};return oe(e,"before","insert")&&await re("before","insert",{doc:{...M},id:h,op:"insert",table:e}),p||q(e,M),Te(e),Ae(e),vt(y,e,br(e),[h,m,ae(M)]),st(e,h,M),oe(e,"after","insert")&&await re("after","insert",{doc:M,id:h,op:"insert",table:e}),await me({doc:M,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,r){if(Qe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const c=H(e,"insert");if(c){const _=[];Br(u.tables[e],t,r?.allowExplicitId,fe);for(const x of t)Y(x);for(const x of t){const R=await c.insert(e,x,{allowExplicitId:r?.allowExplicitId});C({key:R,op:"insert",row:{...x,_id:R},table:e}),_.push(R)}return _}const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);Te(e),Ae(e);const p=[];for(let _=0;_<t.length;_+=Ke)p.push(te(e));const d=r?.allowExplicitId===!0?void 0:Yo(l),h=t.map((_,x)=>{const R=Et(l,_,fe),I=d===void 0?R:He(d,R,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const B=$??At(),Q=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Re(),J={...I,...p[Math.floor(x/Ke)],_creationTime:Q,_id:B};return{creationTime:Q,document:J,id:B}});for(const _ of h)Y(_.document);const m=async _=>{for(const{document:x,id:R}of _)st(e,R,x);for(const{document:x,id:R}of _)await le({doc:x,id:R,op:"insert",table:e})};let M=0;try{for(let _=0;_<h.length;_+=Ke){const x=h.slice(_,_+Ke),R=f.join(x.map($=>f`(${$.id}, ${$.creationTime}, ${ae($.document)})`),f`, `),I=Rn("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${R}`);vt(y,e,I.sql,I.params),M=_+x.length}}catch(_){throw await Un(e,h.slice(0,M)),_}return await m(h),h.map(_=>_.id)},async insertMany(e,t,r){Qe(t.length,r?.limit,"insertMany");const c=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const h of t)Y(h);const d=async h=>p?Mt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{l.push(await d(h))}catch(m){if(c&&m instanceof de&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return fn(u,e,t)},async patch(e,t,r,c){A(e,"ctx.db.patch(table, id, values)");const l=X(t,e);if(!l){const $=Ie(e);if($){Y(r);try{await $.patch(e,t,r,c)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new v("INTERNAL",`unknown table: ${h}`);if(L(h,t),wn("patch",r),xt(h,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:h});return}const M=Ao(m,r,d),_={...d,...Ne(M),...te(h),_id:t};pt(m,M,_,fe);const x=new Set(Object.keys(M)),R=He(m,_,{only:x,patched:x,previous:()=>d,table:h,tolerateStoredNull:!0});Io(c,d,R),oe(h,"before","update")&&await re("before","update",{doc:{...R},id:t,op:"update",previous:d,table:h}),q(h,R,d),Te(h),Ae(h),Ve(y,h,rn(h),[ae(R),t,p]),Be(h,t,R,d),We(h,t,R),Fe(h,d,R),he(h,t,d,R);const I=V(h,d,R);ue?.invalidate(h,t,I),Se(h,t,"update",R),C({indexKeys:I,key:t,op:"update",row:R,table:h}),oe(h,"after","update")&&await re("after","update",{doc:R,id:t,op:"update",previous:d,table:h}),await me({doc:R,id:t,op:"update",table:h})},async patchIf(e,t,r){const c=H(e,"patchIf");if(c){if(c.patchIf===void 0)throw new v("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);Y(r.patch);let l;try{l=await c.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=hn;l+=1){const p=await Nn(e,t,r,l<hn,d=>O.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){A(e,"ctx.db.patchMany(table, patches)"),Qe(t.length,r?.limit,"patchMany");for(const c of t)await O.patch(e,c.id,c.patch);return{patched:t.length}},async patchWhere(e,t,r){const c=H(e,"patchWhere")??O,p=(await dn(c,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(O.patchMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,r),{patched:p.length}},async related(e,t){return Ko(O,T,e,t)},relationEdges:T,deleteRereadTables:W,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(L(e,G),t.query(e)):kn(y,u,e,ne,r=>{r?F(r):L(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const c=H(e,"rank");if(ne(e,t,"rank"),c)return L(e,G),c.rank(e,t,r);const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(z=>z.name===t);if(!p)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(qt(e,l,p),r.restrictsCounts)throw new ut(e);L(e,G),it(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const h=Yt(e,p.name),m=p.sortBy.map((z,we)=>Xt(we)),M=m.map(z=>ke(z)).join(", "),_=K(y,f`SELECT ${f.identifier("__partition__")}, ${f.raw(M)} FROM ${f.identifier(h)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[x]=_;if(x===void 0)return null;let R=x.__partition__;const I=N(r.baseWhere,r.where);ht(I,u,e,"rank");const $=Lo(p,I);if($){const z=Fo(p.partitionBy??[],$);if(z!==R)return null;R=z}const B=m.map(z=>x[z]),{before:Q,total:J}=gn(y,h,m,p.sortBy,R,B,d);return{position:Q+1,total:J}},async rankBefore(e,t,r){if(se(e))throw new v("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=c.rankIndexes?.find(m=>m.name===t);if(!l)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ut(e);L(e,G),it(e,l);const p=Yt(e,l.name),d=l.sortBy.map((m,M)=>Xt(M)),h=l.sortBy.map((m,M)=>De(r.sortValues[M]??null));return gn(y,p,d,l.sortBy,r.partitionKey,h,r.rowId)},async rankPage(e,t,r={}){ht(N(r.baseWhere,r.where),u,e,"rankPage");const c=H(e,"rankPage");if(ne(e,t,"rank"),c)return L(e,G),c.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Qt(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(h=>h.doc)}},async rankPageRows(e,t,r={}){ht(N(r.baseWhere,r.where),u,e,"rankPage"),ne(e,t,"rank");const{directions:c,hasMore:l,rows:p}=Qt(Ot,e,t,r);return{directions:c,hasMore:l,rows:p}},async restore(e,t){A(e,"ctx.db.restore(table, id)");const r=X(t,e);if(!r){const d=Ie(e);if(d?.restore){try{await d.restore(e,t)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const c=u.tables[r.tableName]?.softDeleteMode?.field;if(!c)throw new v("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[c]!==null&&r.row[c]!==void 0;await O.patch(e,t,{[c]:null});const p=l?X(t,e)?.row:void 0;p&&(he(r.tableName,t,p,void 0),he(r.tableName,t,void 0,p))},async replace(e,t,r,c){A(e,"ctx.db.replace(table, id, document)");const l=X(t,e);if(!l){const B=Ie(e);if(B){Y(r);try{await B.replace(e,t,r,c)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new v("INTERNAL",`unknown table: ${h}`);wn("replace",r);const M=c?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,x=M??_??Re(),R={...r,...te(h),_creationTime:x,_id:t};pt(m,r,R,fe);const I=c?.allowExplicitId===!0,$=He(m,R,{previous:()=>d,supplied:r,table:h,trusted:I});oe(h,"before","update")&&await re("before","update",{doc:{...$},id:t,op:"update",previous:d,table:h}),I||q(h,$,d),Te(h),Ae(h),Ve(y,h,xr(h),[x,ae($),t,p]),Be(h,t,$,d),We(h,t,$),Fe(h,d,$),he(h,t,d,$),ue?.invalidate(h,t,V(h,d,$)),Se(h,t,"update",$),C({indexKeys:V(h,d,$),key:t,op:"update",row:$,table:h}),oe(h,"after","update")&&await re("after","update",{doc:$,id:t,op:"update",previous:d,table:h}),await me({doc:$,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,c=Object.entries(u.tables).filter(([h,m])=>t.has(h)||r!==void 0&&!r.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(r!==void 0){for(const h of r)if(!u.tables[h])throw new v("INTERNAL",`wipeShard: unknown table: ${h}`)}const l={};let p=0;const{deleteAll:d}=O;if(d===void 0)throw new v("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of c){const m=await d(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Vn={db:O,scheduler:It};return n.enforceRls===!0?or(O,u,(e,t)=>X(e,t)?.tableName,T):O};export{cs as CDC_LOG_TABLE,xs as IDEMPOTENCY_TABLE,Jr as NotUniqueError,Ts as advanceClientWatermark,as as applyCdcChanges,wn as assertNoExplicitUndefined,Rt as assertStorableRowId,Wr as assertValidClientId,os as backfillAggregateIndexes,rs as backfillRankIndexes,is as backfillSearchIndexes,ds as bumpCdcEpoch,ls as cdcCanVouchFor,us as cdcForkedError,fs as cdcSeqLeavingRows,hs as cdcTouchesTables,ws as cdcTrimmedError,ps as compactCdcDocs,pi as createShardCtxDb,gs as cursorBelowRetainedFloor,si as meterReadBytes,As as migrateClientWatermark,ys as minCdcReplayableSeq,$s as minCdcSeq,fn as normalizeIdStructurally,Es as readCdcChangeKeys,ms as readCdcChanges,Rs as readCdcCursor,vs as readCdcEpoch,Is as readClientWatermark,Cs as readIdempotent,Ls as runShardMigrations,Ws as selectShapeMembers,Bs as selectShapeRows,Ne as stripReservedPatchFields,Ss as trimCdcChanges,Ms as trimIdempotent,Ds as writeIdempotent};
@@ -0,0 +1,2 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{t as F}from"./do-sql-Cf2rnuLV.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const z=Symbol.for("lunora.relations.fanOutBudget"),me=e=>({fanOutBudget:e[z],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),W=(e,t)=>t.select?Y(e,t.select,t.with):e,be=async(e,t,n,o,s)=>{const i=await Promise.all(o.map(async c=>{const f=s?{AND:[{[n]:c},s]}:{[n]:c};return[c,await e(t,f)]}));return new Map(i)},ee=32,E=1e4,te=(e,t,n)=>{const o=new Map;for(const s of e)for(const i of n(s)){const c=i[t],f=o.get(c);f?f.push(i):o.set(c,[i])}return o},x=(e,t)=>({...e,[z]:t}),ne=(e,t)=>{const n=new Map;for(const[s,i]of e)for(const c of i){const f=n.get(c);f?f.push(s):n.set(c,[s])}const o=new Map;for(const s of t)for(const i of n.get(s._id)??[]){const c=o.get(i);c?c.push(s):o.set(i,[s])}return o},j=(e,t)=>{const n=new Set;for(const o of e){const s=o[t];s!=null&&n.add(s)}return[...n]},ve=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:o,parents:s,relationBaseWhere:i,relationMask:c,schema:f,tableName:h,with:m}=e,g=n??{remaining:ee},b=(l,r)=>c?.(l,r)??r;if(s.length===0)return;const A=f.tables[h];if(!A)throw new S("INTERNAL",`unknown table: ${h}`);const $=A.relationMap??{},G=(l,r)=>{const a=d=>f.tables[d]?.shardMode?.kind??"root";return a(l)===a(r)&&a(l)!=="shardBy"},R=l=>{const r=$[l];if(!r)throw new S("INTERNAL",`unknown relation "${l}" on table "${h}"`);return r},X=async(l,r,a)=>{const d=j(s,r.field);if(d.length===0){for(const p of s)p[l]=null;return}const{page:u}=await o(r.table,x({baseWhere:i?.(r.table),relationBaseWhere:i,relationMask:c,where:{[r.references]:{in:d}},with:a.with},g)),w=new Map;for(const p of b(r.table,u))w.set(p[r.references],p);for(const p of s){const O=w.get(p[r.field]);p[l]=O?W([O],a)[0]??null:null}},_=async(l,r,a,d)=>{const{page:u}=await o(l,x({baseWhere:i?.(l),limit:d,orderBy:r.orderBy,relationBaseWhere:i,relationMask:c,where:r.where?{AND:[r.where,a]}:a,with:r.with},g));return u},T=(l,r,a,d,u)=>{for(const w of s){const p=u.get(w[d])??[];w[l]=W(a===void 0?p:p.slice(0,a),r)}},q=async(l,r,a)=>{const d=j(s,r.references);if(d.length===0){for(const y of s)y[l]=[];return}const u=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,w=(y,k)=>_(r.table,a,y,k);if(u===0){for(const y of s)y[l]=[];return}const p=u!==void 0&&d.length<=g.remaining;p&&(g.remaining-=d.length);const O=p?await Promise.all(d.map(async y=>w({[r.field]:y},u))):[await w({[r.field]:{in:d}},void 0)],v=te(O,r.field,y=>b(r.table,y));T(l,a,u,r.references,v)},I=async l=>{const{from:r,table:a,to:d}=l.through,u=new Map,w=j(s,"_id");if(w.length===0)return u;const p=await _(a,{},{[r]:{in:w}},E+1);if(p.length>E)throw new S("INTERNAL",`loading "${h}" relations through "${a}" read more than ${String(E)} join rows for one page; load fewer ${h} rows at a time`);for(const O of b(a,p)){const v=O[r],y=O[d];if(v==null||y===null||y===void 0)continue;const k=u.get(v);k?k.add(y):u.set(v,new Set([y]))}return u},K=async(l,r,a)=>{const d=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,u=d===0?new Map:await I(r),w=(O,v)=>_(r.table,a,{_id:{in:[...O]}},v);let p=new Map;if(u.size>0&&d!==void 0&&u.size<=g.remaining){g.remaining-=u.size;const O=[...u.keys()],v=await Promise.all([...u.values()].map(async y=>w(y,d)));p=new Map(O.map((y,k)=>[y,b(r.table,v[k]??[])]))}else if(u.size>0){const O=new Set([...u.values()].flatMap(v=>[...v]));p=ne(u,b(r.table,await w(O,void 0)))}T(l,a,d,"_id",p)},Z=async(l,r)=>{const a=[...r];if(a.length===0)return new Set;if(G(h,l)){const u=await t(l,"_id",a,i?.(l),i);return new Set(a.filter(w=>(u.get(w)??0)>0))}const d=await _(l,{},{_id:{in:a}},void 0);return new Set(d.map(u=>u._id))},J=async(l,r)=>{const a=await I(r),d=await Z(r.table,new Set([...a.values()].flatMap(u=>[...u])));for(const u of s){const w=u._count??{};w[l]=[...a.get(u._id)??[]].filter(p=>d.has(p)).length,u._count=w}},Q=async l=>{for(const r of Object.keys(l)){const a=R(r);if(a.through!==void 0){await J(r,a);continue}const[d,u]=a.kind==="many"?[a.field,a.references]:[a.references,a.field],w=i?.(a.table),p=j(s,u),O=p.length===0?new Map:await t(a.table,d,p,w,i);for(const v of s){const y=v._count??{},k=v[u];y[r]=k==null?0:O.get(k)??0,v._count=y}}};for(const[l,r]of Object.entries(m)){if(r===void 0||r===!1)continue;if(l==="_count"){await Q(r);continue}const a=R(l),d=r===!0?{}:r;a.through===void 0?await(a.kind==="one"?X(l,a,d):q(l,a,d)):await K(l,a,d)}},D=1e4,U=500,oe=async(e,t,n,o,s)=>{const i=new Set;let c=s;for(;;){const f=c!==void 0,h=c??await e();let m=!1;c=void 0;for(const g of h){const b=g._id;if(!(typeof b!="string"||i.has(b))){if(i.add(b),m=!0,i.size>D)throw n();await t(b)}}if(!f){if(h.length<U)return;if(!m)throw new S("INTERNAL",o)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(D)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),se=async(e,t,n,o)=>{const{deletedId:s,deletedReference:i,findHolders:c,onRestrict:f,tableName:h}=e,m=n.references==="_id"?s:i(n.references);if(m==null)return;const{field:g}=n,b=`"${t}.${g}"`,A=await c(t,g,m,{limit:o==="restrict"?1:D+1,select:["_id"]});if(A.length!==0){if(o==="restrict")return f(`cannot delete "${h}" row: ${b} still references it`);if(A.length>D)throw H(h,b,o);return{action:o,field:g,holderTable:t,label:b,probe:A,referencedValue:m}}},re=async(e,t,n)=>{const{findHolders:o,onCascade:s,onSetNull:i,tableName:c}=e,{action:f,field:h,holderTable:m,label:g,probe:b,referencedValue:A}=t;await oe(()=>o(m,h,A,{limit:U}),$=>f==="cascade"?s(m,$):i(m,$,h),()=>H(c,g,f),`onDelete on "${c}" made no progress: ${g} rows still match after being processed`,n?b:void 0)},Oe=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const o=[];for(const[s,i]of Object.entries(t.tables)){const c=i.relationMap;if(c)for(const f of Object.values(c)){if(f.kind!=="one"||f.table!==n||!f.onDelete)continue;const h=await se(e,s,f,f.onDelete);h&&o.push(h)}}for(const[s,i]of o.entries())await re(e,i,s===0)},L=new WeakMap,B=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,o=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||o.some(i=>i!==void 0&&B(i));return L.set(e,s),s},C=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,V=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=P(e),o=P(t);if(n!==void 0||o!==void 0)return n!==void 0&&o!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===o.length&&n.every((f,h)=>f===o[h]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((f,h)=>V(f,t[h]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!C(e)||!C(t))return!1;const s=e,i=t,c=Object.keys(s);return c.length===Object.keys(i).length&&c.every(f=>f in i&&V(s[f],i[f]))},N=new WeakMap,Ae=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,o])=>B(o))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},ae=e=>{let t;return(n,o)=>e===void 0?!1:(t??=e()??{},n in t&&V(o,t[n]))},ie=(e,t)=>{const n=new Set(Object.keys(t).filter(o=>t[o]!==void 0));for(const[o,s]of F(e))s.serverDefault&&n.delete(o);return n},ce=(e,t,n,o,s)=>n.trusted===!0||o!==void 0&&!o.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,ke=(e,t,n)=>{const o={...t};for(const[s,i]of F(e)){if(i.serverDefault){o[s]=i.serverDefault({auth:n});continue}if(o[s]===void 0){if(i.defaultFn)o[s]=i.defaultFn();else if("defaultValue"in i){const{defaultValue:c}=i;o[s]=M(c)}}}return o},fe=e=>e.map((t,n)=>typeof t=="number"?`[${String(t)}]`:n===0?t:`.${t}`).join(""),le=(e,t,n,o)=>o.patched===void 0?"":o.patched.has(e)?n?" (set by the column's server default, which replaces what this patch sent)":" (set by this patch)":Object.is(o.previous?.()?.[e],t)?" (a stored value this patch does not set: the row already holds it, and every patch of the row fails until it is fixed)":" (not set by this patch: an update hook assigned it)",ue=e=>e.message.startsWith("object has ")?"object":e.received.startsWith("object")?e.received:e.received.split(" ")[0]??e.received,de=e=>e instanceof Error&&e.code==="VALIDATION_ERROR"&&Array.isArray(e.path)&&typeof e.expected=="string"&&typeof e.received=="string",he=(e,t,n)=>{const{field:o,serverDefault:s,value:i}=t,c=[o,...e.path],f=`${n.table===void 0?"":`${n.table}.`}${fe(c)}`,h=e.message.startsWith(`Expected ${e.expected} at `)&&e.message.endsWith(`, received ${e.received}`),m=ue(e),g=h?`expected ${e.expected}, received ${m}`:e.message,b=e.constructor,A=new b(`${f}: ${g}${le(o,i,s,n)}`,{expected:e.expected,path:c,received:m}),$=e.stack?.indexOf(`
2
+ at `)??-1;return $!==-1&&e.stack!==void 0&&(A.stack=`${A.name}: ${A.message}${e.stack.slice($)}`),A},pe=(e,t,n)=>{try{return e(t.value)}catch(o){throw de(o)?he(o,t,n):o}},$e=(e,t,n={})=>{let o;const s=ae(n.previous),i=n.only??(n.supplied===void 0?void 0:ie(e,n.supplied));for(const[c,f]of Object.entries(e.shape)){if(!(c in t)||typeof f.parse!="function")continue;const h=B(f);if(h&&ce(c,t[c],n,i,s)||n.tolerateStoredNull===!0&&t[c]===null&&f.kind==="optional")continue;const m=pe(g=>f.parse?.(g),{field:c,serverDefault:f._meta?.column?.serverDefault!==void 0,value:t[c]},n);h&&(o??={...t},o[c]=m)}return o??t};export{D as CASCADE_MAX_ROWS,E as MAX_LINK_ROWS,ke as applyInsertDefaults,Oe as applyOnDelete,j as distinctValues,be as fanOutScalarCounts,me as relationHooks,ve as resolveWith,$e as runRowValidators,Ae as transformOnlyDefinition};
@@ -1 +1 @@
1
- import{createShardCtxDb as C}from"./NotUniqueError-CDB9Ooq4.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-4_ene2xR.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as C}from"./NotUniqueError-DceH7dQi.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-4_ene2xR.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.210",
3
+ "version": "1.0.0-alpha.211",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-Cf2rnuLV.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f),a);return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w,a);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{N as CASCADE_MAX_ROWS,B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};