@lunora/shard-engine 1.0.0-alpha.184 → 1.0.0-alpha.185
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NotUniqueError-jYLWUe1u.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-BG9z3FE9.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-B4Uu4g7l.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-BZIpATcs.mjs → computeRankPage-xm-70mLy.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-BiFprp2V.mjs → defineEngineContractSuite-BVQy1TRb.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/NotUniqueError-BjwNIte8.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-5XPk8qfW.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BVQy1TRb.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-BjwNIte8.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-B_4sLV4q.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-5XPk8qfW.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,isRelationPredicate as Si,resolveRelationPredicates as fi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Ei}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ti,applyOnDelete as Ri,distinctValues as Ai,fanOutScalarCounts as Ci,relationHooks as gi,resolveWith as _i,runRowValidators as Ii}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Li,c as Di,n as Oi,r as Pi,s as yi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Fi,OwnerRelay as ki,RelayMember as Ni,createRelayLink as Bi}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as Gi,gateReplicaDispatch as wi,handleReplicaControl as qi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Ki,countLegacyRows as Wi,reprojectableFields as Xi,reprojectionTables as Hi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as zi,RlsRequiredError as Qi,guardWriter as Yi}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as cs,createShapeDiffCache as ms,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Ss,diffGlobalMembership as fs,encodeRowsPatch as xs,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as gs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Is,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Ds}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Ps,bigintSqlKey as ys,decodeBigintSqlKey as Ms,decodeFloat64SqlKey as Fs,float64SqlKey as ks}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Bs,subscriptionFrames as Us,subscriptionListDeltas as Gs,trySendFrame as ws}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as vs,recordChangedKeys as Ks,writeTouchesMemo as Ws}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Hs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as zs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ys,TransactionHeadroomTracker as js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Zs,runTriggers as $s}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as rn,nextTtlExpiry as on,selectExpiredIds as an}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as sn,backfillVectorIndexes as nn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as dn,s as cn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as pn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Sn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as xn,siblingSecretOf as En,signSiblingBody as hn,verifySiblingBody as Tn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as An,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as _n}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as bn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,Sn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,Ps as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,zs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,Fi as DEFAULT_MAX_RELAYS,Li as DEFAULT_PROMOTION_THRESHOLDS,Ys as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,Is as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,ki as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,pn as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,xn as RELAY_SIGNATURE_HEADER,An as REPROJECTION_MIGRATION_PREFIX,zi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Ni as RelayMember,Qi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,cs as ShapeDiffCache,Ts as ShardRunner,js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,sn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ti as applyInsertDefaults,Ri as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,bs as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Bs as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,nn as backfillVectorIndexes,ys as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,Ss as buildPokeFrames,Ki as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Di as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,dn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Wi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Bi as createRelayLink,Gi as createReplicaLink,ms as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Hs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Ms as decodeBigintSqlKey,lt as decodeCursor,Fs as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,Ei as describeRelationWrites,qo as diffExternalSource,fs as diffGlobalMembership,Ai as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,xs as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,Ci as fanOutScalarCounts,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,ks as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,wi as gateReplicaDispatch,so as geoTableName,ps as globalShapeReadKey,na as groupUnmappedRows,Yi as guardWriter,qi as handleReplicaControl,ur as hasScheduleOutboxEntry,Zs as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,is as isDevEnvironment,no as isFtsAvailable,_n as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,Si as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,rn as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ls as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,vs as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Oi as nextPromotionState,on as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,Es as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,bn as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ss as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ks as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,es as recordSchemaVersion,Na as recordShapeProbePass,gi as relationHooks,Pi as relayCountFor,To as renderSql,Xi as reprojectableFields,Cn as reprojectionMigrationId,Hi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,fi as resolveRelationPredicates,_i as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Ds as runReadonlySql,Ii as runRowValidators,Dn as runShardMigrations,gs as runSocketPool,Zr as runSql,$s as runTriggers,an as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,os as serializeSqlValue,cn as serverInList,yi as shapeRoutingKey,En as siblingSecretOf,hn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,Pn as stableStringify,yn as stableWireKey,H as stripReservedPatchFields,As as stubByName,Us as subscriptionFrames,Gs as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,ws as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Tn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Ws as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-jYLWUe1u.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-xm-70mLy.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-B_4sLV4q.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,isRelationPredicate as Si,resolveRelationPredicates as fi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Ei}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ti,applyOnDelete as Ri,distinctValues as Ai,fanOutScalarCounts as Ci,relationHooks as gi,resolveWith as _i,runRowValidators as Ii}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Li,c as Di,n as Oi,r as Pi,s as yi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Fi,OwnerRelay as ki,RelayMember as Ni,createRelayLink as Bi}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as Gi,gateReplicaDispatch as wi,handleReplicaControl as qi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Ki,countLegacyRows as Wi,reprojectableFields as Xi,reprojectionTables as Hi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as zi,RlsRequiredError as Qi,guardWriter as Yi}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as cs,createShapeDiffCache as ms,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Ss,diffGlobalMembership as fs,encodeRowsPatch as xs,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as gs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Is,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Ds}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Ps,bigintSqlKey as ys,decodeBigintSqlKey as Ms,decodeFloat64SqlKey as Fs,float64SqlKey as ks}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Bs,subscriptionFrames as Us,subscriptionListDeltas as Gs,trySendFrame as ws}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as vs,recordChangedKeys as Ks,writeTouchesMemo as Ws}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Hs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as zs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ys,TransactionHeadroomTracker as js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Zs,runTriggers as $s}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as rn,nextTtlExpiry as on,selectExpiredIds as an}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as sn,backfillVectorIndexes as nn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as dn,s as cn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as pn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Sn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as xn,siblingSecretOf as En,signSiblingBody as hn,verifySiblingBody as Tn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as An,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as _n}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as bn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,Sn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,Ps as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,zs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,Fi as DEFAULT_MAX_RELAYS,Li as DEFAULT_PROMOTION_THRESHOLDS,Ys as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,Is as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,ki as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,pn as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,xn as RELAY_SIGNATURE_HEADER,An as REPROJECTION_MIGRATION_PREFIX,zi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Ni as RelayMember,Qi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,cs as ShapeDiffCache,Ts as ShardRunner,js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,sn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ti as applyInsertDefaults,Ri as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,bs as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Bs as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,nn as backfillVectorIndexes,ys as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,Ss as buildPokeFrames,Ki as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Di as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,dn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Wi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Bi as createRelayLink,Gi as createReplicaLink,ms as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Hs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Ms as decodeBigintSqlKey,lt as decodeCursor,Fs as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,Ei as describeRelationWrites,qo as diffExternalSource,fs as diffGlobalMembership,Ai as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,xs as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,Ci as fanOutScalarCounts,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,ks as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,wi as gateReplicaDispatch,so as geoTableName,ps as globalShapeReadKey,na as groupUnmappedRows,Yi as guardWriter,qi as handleReplicaControl,ur as hasScheduleOutboxEntry,Zs as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,is as isDevEnvironment,no as isFtsAvailable,_n as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,Si as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,rn as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ls as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,vs as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Oi as nextPromotionState,on as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,Es as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,bn as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ss as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ks as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,es as recordSchemaVersion,Na as recordShapeProbePass,gi as relationHooks,Pi as relayCountFor,To as renderSql,Xi as reprojectableFields,Cn as reprojectionMigrationId,Hi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,fi as resolveRelationPredicates,_i as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Ds as runReadonlySql,Ii as runRowValidators,Dn as runShardMigrations,gs as runSocketPool,Zr as runSql,$s as runTriggers,an as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,os as serializeSqlValue,cn as serverInList,yi as shapeRoutingKey,En as siblingSecretOf,hn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,Pn as stableStringify,yn as stableWireKey,H as stripReservedPatchFields,As as stubByName,Us as subscriptionFrames,Gs as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,ws as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Tn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Ws as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{q as Rt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Un,l as qe,s as On}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Gn,stableWireKey as Ut}from"@lunora/wire";import{sql as d}from"drizzle-orm";import{throwingScheduler as jn,aggregateSqlFunction as Pe,normalizeCountArgument as Hn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Kn,selectIndexForCount as Nn,selectIndexForAggregate as Qn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Vn,searchIndexCoversTable as Jn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Gi,backfillRankIndexes as ji,backfillSearchIndexes as Hi}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as zn,readCdcDocAtOrBefore as Yn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Ni,applyCdcChanges as Qi,bumpCdcEpoch as Vi,cdcCanVouchFor as Ji,cdcForkedError as zi,cdcSeqLeavingRows as Yi,cdcTouchesTables as Xi,cdcTrimmedError as Zi,compactCdcDocs as es,cursorBelowRetainedFloor as ts,minCdcReplayableSeq as ns,minCdcSeq as os,readCdcChangeKeys as rs,readCdcChanges as is,readCdcCursor as ss,readCdcEpoch as cs,trimCdcChanges as as}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as Xn,COMMIT_SEQ_FIELD as Zn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as eo}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ot}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Gt}from"./computeRankPage-xm-70mLy.mjs";import{SCAN_DEP as G,PRIMARY_READ as to}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as no,j as pt,D as ie,r as xe,W as oo,k as le,b as Ue,A as lt,a as Oe,m as ue,e as fe,s as ro,t as io,u as so,i as co,q as jt,h as $n,g as ao}from"./do-sql-105TONaE.mjs";import{renderSql as mn,unionAll as Rn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as lo,u as uo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as fo,boundingBoxGeohashes as ho,haversineMeters as wo,pointInBoundingBox as po}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as go}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as yo,assertPatchAllowed as Eo,operatorFields as $o,readPatchField as Ht}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as mo,encodeCursor as Qe,nullsOrderSuffix as Ro,normalizeOrderKeys as Kt,uniqueIndexFields as So,buildSeekWhere as vo,decodeCursor as Nt,buildSeekBeforeWhere as _o,softDeleteScope as Ae,applySelect as gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Qt,sortColumnName as Vt,resolveRankPartition as To,encodePartitionKey as Ao,RANK_TIEBREAK as Io,rankPivotConditionSql as xo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Jt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as bo,withUnknownIndexKeys as Co,indexKeysForRow as Mo,buildIndexRange as Do}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as Ye,i as zt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ko,isPushableWhere as Lo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Fo,findRelated as Bo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ut,resolveRelationPredicates as Wo,composeReadPredicate as qo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Po}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Uo,applyInsertDefaults as yt,resolveWith as Yt,relationHooks as Xt,applyOnDelete as Oo,fanOutScalarCounts as Go}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as jo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Ho}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Ko}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as No}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ls,migrateClientWatermark as us,readClientWatermark as fs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ws,readIdempotent as ps,trimIdempotent as gs,writeIdempotent as ys}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as Rs,selectShapeRows as Ss}from"./selectShapeMembers-Dqx_m7BF.mjs";const Qo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Vo=()=>new R("BAD_REQUEST","invalid cursor"),en=16,tn=8,z=1024,St=(n,r)=>r.query(n),Jo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const $ of n)(u?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},zo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Yo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=tn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const $=St(u,o).length;if($>en)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Xo=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()`)},Zo=n=>Math.min(n.offset+n.numItems+1,z),er=n=>btoa(`search:${String(n)}`),tr=n=>{let r;try{r=Qo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},nr=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 r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?tr(n.cursor):0;if(o===void 0)throw Vo();if(o+r>=z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} 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:r,offset:o}},or=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?er(o):null,isDone:!s,page:n.slice(r.offset,o)}},rr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new R("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},vn=500,_n=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},ir=32,sr=1024,An=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,r)=>Ve(no(n,r)),serialize:Ce},cr=n=>n===void 0?"":Ro(n==="first"),In=n=>{const r=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${cr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${pt("id")} ${mo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},ar={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),dr=n=>{const r=xn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},lr=(n,r)=>{const o=n.order,s=dr(n),{shape:c}=r;return s.length>0?Kt(s.map(u=>({[u]:o})),c,{pinned:xn(n),uniqueBy:So(r.indexes,c)}):Kt([{_creationTime:o}],c)},ur=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[ar[u.comparator]??"eq"]:u.value}}));if(o&&c.push(vo(r,Nt(o))),s&&c.push(_o(r,Nt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},fr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,ir):n.want},Et=(n,r,o,s,c,u,g)=>{const $=lr(s,o),y=In($),a=[],{filters:M,want:T}=u;let v=u.cursor??void 0,x=fr(u);if(T===0)return{documents:a,orderKeys:$};for(;;){const W=Z(ur(s,$,v,u.endCursor),Xe,Ye),P=An(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,P.text,...P.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),M.every(ee=>ee(U))&&a.push(U)===T)return{documents:a,orderKeys:$};if(x===void 0||B.length<x)return{documents:a,orderKeys:$};v=Qe(U,$),x=Math.max(x,Math.min(x*2,sr))}},hr=(n,r,o,s,c,u,g,$)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:P}=Et(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?Qe(B,P):null}}const{documents:a,orderKeys:M}=Et(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},$),T=a.length>y,v=T?a.slice(0,y):a,x=v.at(-1);return{continueCursor:T&&x?Qe(x,M):null,isDone:!T,page:v}},Ze=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),wr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),pr=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),yr="SELECT changes() AS changed",on=new Map,Er="",$r=n=>{const r=JSON.stringify(n),o=on.get(r);if(o!==void 0)return o;const s=n.map(u=>d`SELECT ${d.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(u)} WHERE id = ${Er}`),{sql:c}=mn("sqlite",d`${Rn(s)} LIMIT 1`);return on.set(r,c),c},mr=(n,r)=>r.map(()=>n),Rr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sr=n=>{if(!Rr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=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)`)},vr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?yt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},rn=50,je=Math.floor(Sn.boundParams/3),sn=Sn.boundParams,_r=128,Je=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Tn(n,_n(r,o,Je),o,Je)},cn=async(n,r,o,s,c)=>{const u=_n(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Tn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},Tr=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ar=n=>Math.max(n,z),bn=(n,r)=>{const o=n.filters.map(s=>d`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Ir=(n,r,o,s,c)=>{const u=St(o.query,Rt(o.definition.language));if(u.length===0)return[];const g=Un(r,o.indexName),$=`${g}__vocab`,y=u.length-1,a=u.map((P,B)=>{const U=zo(P,B===y),j=U.exact?d`${d.identifier("term")} = ${U.lower}`:d`${d.identifier("term")} >= ${U.lower} AND ${d.identifier("term")} < ${U.upper}`;return d`SELECT ${d.identifier("doc")}, ${d.raw(String(B))} AS ${d.identifier("__term__")}, COUNT(*) AS ${d.identifier("__n__")} FROM ${d.identifier($)} WHERE ${j} GROUP BY ${d.identifier("doc")}`}),M=u.map((P,B)=>d`SUM(CASE WHEN u.${d.identifier("__term__")} = ${d.raw(String(B))} THEN u.${d.identifier("__n__")} ELSE 0 END)`),T=d`SELECT f.${d.identifier(qe)} AS ${d.identifier(qe)}, ${d.join(M,d` + `)} AS ${d.identifier("__score__")} FROM (${Rn(a)}) u JOIN ${d.identifier(g)} f ON f.rowid = u.${d.identifier("doc")} GROUP BY f.${d.identifier(qe)} HAVING ${d.join(M.map(P=>d`${P} > 0`),d` AND `)}`,v=bn(o,c);let x=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)}, s.${d.identifier("__score__")} AS ${d.identifier("__score__")} FROM (${T}) s JOIN ${d.identifier(r)} m ON m.id = s.${d.identifier(qe)}`;v.length>0&&(x=d`${x} WHERE ${d.join(v,d` AND `)}`),x=d`${x} ORDER BY s.${d.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${d.raw(String(s))}`;const W=[];for(const P of K(n,x)){const B=$n(P);if(B){const U=P.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},xr=(n,r,o,s,c)=>{const u=Rt(o.definition.language),g=St(o.query,u);if(g.length===0)return[];const $=bn(o,c);let y=d`SELECT id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(r)}`;$.length>0&&(y=d`${y} WHERE ${d.join($,d` AND `)}`),y=d`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${d.raw(String(Ar(s)))}`;const a=K(n,y).toArray(),M=[];for(const T of a){const v=$n(T);if(!v)continue;const x=Jo(On(v,o.definition),g);x>0&&M.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return M.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),M.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,r,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}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},br=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",r,o.indexName),ft(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Cr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Mr=(n,r)=>{const o=Cr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=wo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return po(o,r.within)?{creationTime:s,distance:0}:void 0},Dr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?fo(o.near.point,o.near.radiusMeters):ho(o.within),u=ao(r,o.indexName),g=c.map(T=>d`(g.${d.identifier("__geohash__")} >= ${T} AND g.${d.identifier("__geohash__")} < ${`${T}{`})`),$=[d`(${d.join(g,d` OR `)})`];s&&$.push(s);const y=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)} FROM ${d.identifier(u)} g JOIN ${d.identifier(r)} m ON m.id = g.${d.identifier("__id__")} WHERE ${d.join($,d` AND `)}`,a=K(n,y).toArray(),M=[];for(const T of a){const v=xe(T),x=v?Mr(v,o):void 0;v&&x&&M.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return M.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),M},Cn=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},kr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,$=Dr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,r,o,s,c,u,g=()=>{})=>{const{geo:$}=o;if(!$)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,a=kr(n,r,$,y?void 0:u,s,g);return y?Cn(a,c,u,M=>M.document):a},dn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ho(s))throw new R("BAD_REQUEST",`${o}: "${r}" 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)`)},Lr=n=>{let r=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:u,negated:g,parentTable:$,relation:y}=c,a=`__rel_${String(r)}`,M=o.at(-1)??$;r+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Ve(`${jt(a,v)} = ${jt(M,T)}`);o.push(a);const W=Z(u,s,Ye);o.pop();const P=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",zt(y.table)," AS ",zt(a)," WHERE ",P,")");return g?be("NOT ",B):B}};return s};class Fr extends R{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Br=/\s/u,Wr=String.fromCodePoint(0),ln=(n,r,o)=>{if(!n.tables[r])throw new R("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Br.test(o)||o.includes(Wr)?null:o},Mn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const $=r.tables[o];if(!$)throw new R("INTERNAL",`unknown table: ${o}`);const y=Ae($.softDeleteMode,void 0),a=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},M=()=>{const S=Q(y,a.pushedWhere);return S?Z(S,ue):void 0},T=()=>{const S=Q(y,a.pushedWhere);return S?Z(S,Xe,Ye):void 0},v=()=>[...a.inMemoryFilters,...a.verifyFilters];let x=0;const W=S=>{const{search:C}=a;if(!C)throw new R("INTERNAL","runSearchFetch called without a staged search");Vn(so(n),o,$);const L=a.inMemoryFilters.length>0,F=rr(L?void 0:S),k=co(n);if(k&&!Jn(n,o,C.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${C.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 pe=M(),te=k?Ir(n,o,C,F,pe):xr(n,o,C,F,pe);!L&&S===void 0&&Xo(te);const ge=v();return x=te.length,ge.length>0?Cn(te,ge,S,J=>J.document):te},P=S=>W(S).map(C=>C.document),B=S=>{const C=nr(S);return or(P(Zo(C)),C)},U=()=>{if(a.search||a.geo||a.indexName===void 0){c(void 0);return}c(Do(o,a.indexName,a.indexFields,a.sqlConditions,Ce))},j=S=>{U();let C=0;const L=(()=>{if(a.search){const F=P(S);return C=x,F}return a.geo?an(n,o,a,M(),v(),S,F=>{C=F}).map(F=>F.document):Et(n,o,$,a,T(),{filters:v(),selective:a.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!a.search&&!a.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const C=(()=>{if(a.search){const L=W(void 0);return S=x,L}return an(n,o,a,M(),v(),void 0,L=>{S=L})})();return u(Math.max(S,C.length)),C},N={async*[Symbol.asyncIterator](){const S=Mn(n,r,o,s,c,u,{...a,indexFields:[...a.indexFields],inMemoryFilters:[...a.inMemoryFilters],sqlConditions:[...a.sqlConditions],verifyFilters:[...a.verifyFilters]});if(a.search){yield*await S.collect();return}let C;for(;;){const L=await S.paginate({cursor:C??null,numItems:_r});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const C=ko(S);return C!==void 0&&Lo(C,$.shape)?(a.pushedWhere=Q(a.pushedWhere,C),a.verifyFilters.push(S)):a.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return a.order=S==="desc"?"desc":"asc",N},async paginate(S){let C=0;if(U(),a.search){const F=B(S);return u(F.page.length),F}if(a.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=hr(n,o,$,a,S,T(),{all:v(),selective:a.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Fr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,C){const L=($.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(a.geo=F,C(br(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,C){const L=$.indexes.find(F=>F.name===S);if(!L)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),a.indexName=S,a.indexFields=L.fields,C&&C(Tr(a)),N},withSearchIndex(S,C){const L=($.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(a.search=F,C(Yo(F,o,Rt(L.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,r,o,s)=>{const c=o;for(const[u,g]of io(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},un=5,fn=(n,r)=>{for(const o of Object.keys(r))if(r[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.`)},hn=["_commitSeq","_creationTime","_id"],Ke=n=>hn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!hn.includes(r))):n,qr=/unique constraint failed/i,Pr=n=>n instanceof Error&&qr.test(n.message),Ur=/string or blob too big/iu,Or=(n,r)=>{if(!(!(n instanceof Error)||!Ur.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": 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.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Pr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Or(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,yr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,r,o,s,c,u,g)=>{const $=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],x=s[T],W=x?.direction==="desc"?"desc":"asc",P=v===void 0||x===void 0?d`${d.identifier(Io)} < ${g}`:xo(v,u[T],W,!1);if(P===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(d`${d.identifier(o[j])} IS ${u[j]}`);B.push(P);const[U]=B;$.push(B.length===1&&U!==void 0?U:d`(${d.join(B,d` AND `)})`)}const y=$.length>0?d.join($,d` OR `):d`1 = 0`,a=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c} AND (${y})`).one(),M=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c}`).one();return{before:a.c,total:M.c}},Gr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:$,op:y}of r.get(g)??[]){if($===s||Zt(n,$,y))return!0;c.has($)||(c.add($),u.push($))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Zt(n,s,"delete")||o(s)).map(([s])=>s))},jr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},wt=new WeakMap,Hr=(n,r)=>{let o=wt.get(r.tables);if(!wt.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Kr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,$=uo(u);typeof g!="string"?r.recordReadBytes($):o===void 0?r.recordDocumentRead(`${g}\0${String($)}`,$):r.recordDocumentRead(`${o}\0${g}`,$)}}},Nr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),$=g.one.bind(g),y=g[Symbol.iterator].bind(g),a=o===void 0?void 0:Hr(c,o);let M=!1;const T=v=>{Kr(v,r,a)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})T([x]),v.push(x);return v},g.one=()=>{M=!0;try{const v=$();return T([v]),v}finally{M=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})M||T([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===oo?c:Reflect.get(c,u,c)})},Qr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Vr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=lo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},ze=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Dn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Vr.get(c);return(...$)=>{const y=Reflect.apply(u,s,$);return g!==void 0?Promise.resolve(y).then(a=>(ze(a,g,r,o),a)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Dn(y,r,o):y}}}),Jr=new Set(["findFirst","findFirstOrThrow","findMany"]),zr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>gt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:u(g.page)}:u([g])[0]}},pn=256,gn=4096,Yr=1024*1024,Xr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,$=pn,y=0;for(;;){const a=await n([r[0],{...c,cursor:g,limit:$},...r.slice(2)]);if(Array.isArray(a))return ze(a,"rows",o,s),[...u,...a];const M=s.headroom().readBytes;if(ze(a,"page",o,s),u.push(...a.page),a.isDone||typeof a.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=a.continueCursor,y+=s.headroom().readBytes-M,$=y>0?Math.min(gn,Math.max(pn,Math.floor(Yr*u.length/y))):gn}},Zr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),r);const u=Qr.get(s);return u===void 0?c:async(...g)=>{const $=Jr.has(s)?zr(g):void 0,y=$?.args??g,a=String(g[0]);if(s==="findMany"&&typeof y[1]?.limit!="number"){const v=await Xr(x=>Reflect.apply(c,o,x),y,a,r);return $===void 0?v:$.project(v,u)}const T=await Reflect.apply(c,o,y);return ze(T,u,a,r),$===void 0?T:$.project(T,u)}}}),yn=new WeakMap,En=new WeakMap,ei=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=yn.get(n)??{value:void 0},u=En.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};yn.set(e,c),En.set(e,u),g=ei(e)}return g},y=Nr(n.sql,s,n.schema),{schema:a}=n,M=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(a.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Fo(a),x=new Map;for(const e of v){const t=i=>(a.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,d`SELECT 1 FROM ${d.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},P=Po(a,n.inTransaction),B=Gr(a),U=jr(a),j=()=>n.inTransaction?.()===!0,ee=e=>a.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=Xn(y)),{[Zn]:c.value}),N=(e,...t)=>{const i=a.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(bo(w))),l.push(...Co(i,Mo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),C=e=>{Ot(a.tables[e])&&S(Jt,Jt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),C(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,$e=n.clock??(()=>Date.now()),vt=n.idGenerator??(()=>crypto.randomUUID()),_t=n.scheduler??jn,me=Zr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,et=_t,kn=Ko({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Re=(e,t,i,l)=>{Tt&&!Ot(a.tables[e])&&zn(y,$e(),e,t,i,l)},At=(e,t,i,l)=>{const w=a.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Yn(y,e,t,p);if(f===void 0)return!1;const h=$o(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Ut(Ht(f,E))!==Ut(Ht(l,E)))},ae=e=>a.tables[e]?.shardMode?.kind==="global",It=(e,t)=>{if(ae(e)){if(!me)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},tt=e=>It(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},xt=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return M({key:p,op:"insert",row:{...i,_id:p},table:t}),p},nt=(e,t)=>It(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),nt(e,t)),Ln=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Wo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:a,tableName:t}),kt=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),Go((m,q)=>w.count(m,q),e,t,i,l);const p=a.tables[e];if(!p)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),_=await De(E,e,void 0),b=Z(_,ue),A=fe(t);let I=d`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${d.identifier(e)}`;b&&(I=d`${I} WHERE ${b}`),I=d`${I} GROUP BY ${A}`;const D=K(y,I).toArray();return new Map(D.map(m=>[m.__fk__,m.count]))},Lt=new Set;for(const[e,t]of Object.entries(a.tables))for(const i of Object.values(t.triggerMap??{}))Lt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>Lt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>rn)throw u.value-=1,new se(`trigger recursion exceeded ${String(rn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await No({ctx:qn,event:i,op:t,schema:a,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Ft,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=eo({broadcast:M,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:a,sql:y,verified:n.companionMemo?.verified}),Bt=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.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})},Wt=e=>Object.entries(a.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?me:void 0,it=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let l=0;l<i.length;l+=sn){const w=i.slice(l,l+sn),[p]=he(y,$r(w),...mr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},qt={assertRankPartitionLocal:Bt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:a,sql:y},Fn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,d`SELECT 1 FROM ${d.identifier(e)} WHERE ${d.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Bn=(e,t,i,l)=>At(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Wn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Fn(e,t,i.where)||Bn(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},Pt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await qo(t,i,{canPushExists:Mt?Ln:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:a,tableName:e}),E=Mt?Lr(l):Xe,_=Z(h,E,Ye),b=An(e,_,In(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:kn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);if(Pe(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`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const m=Qn(l.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const q=ct(m.index.by??[],m.key),Y=st(e,m.index.name),X=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return at(t.op,X)}}dn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),_=Pe(t.op),b=fe(t.field);let A=d`SELECT ${d.raw(_)}(${b}) AS value FROM ${d.identifier(e)}`;E&&(A=d`${A} WHERE ${E}`);const D=K(y,A).toArray()[0]?.value;return D??null},asId(e,t){const i=ln(a,e,t);if(i===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=Hn(t);if(w.restrictsCounts)throw new dt(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const I=Nn(l.aggregateIndexes,w.where);if(I){ot(e,I.index);const D=ct(I.index.by??[],I.key),m=st(e,I.index.name),q=K(y,d`SELECT ${Ue} AS value FROM ${d.identifier(m)} WHERE ${Oe} = ${D}`).toArray();return q[0]===void 0?0:q[0].value??0}}const _=Z(h,ue);let b=d`SELECT COUNT(*) AS count FROM ${d.identifier(e)}`;return _&&(b=d`${b} WHERE ${_}`),K(y,b).one().count},async delete(e,t,i){T(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const I=Te(e);I&&await it(I,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=a.tables[f],E=i?.hard===!0,_=!E&&h?.softDeleteMode?h:void 0,b=_?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Oo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,D,m,q)=>(await tt(I).findMany(I,{...q,includeDeleted:E,where:{[D]:m}})).page,onCascade:(I,D)=>tt(I).delete(I,D,i),onRestrict:I=>{throw new se(I,"restrict")},onSetNull:(I,D,m)=>tt(I).patch(I,D,{[m]:null}),schema:a,tableName:f}),Se(f),ve(f),_&&b){const I={[b]:$e()},D={...p,...ee(f),...I,_id:t};ht(_,I,D,ce),Ne(y,f,nn(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const m=N(f,p,D);Ee?.invalidate(f,t,m),Re(f,t,"update",D),M({indexKeys:m,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,gr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const A=N(f,p);Ee?.invalidate(f,t,A),Re(f,t,"delete"),M({indexKeys:A,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!a.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??vn),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):it(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){T(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await cn(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return it(l,e,p,void 0,{options:i});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,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new go(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,to),i.findMany(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await Pt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const _=[];for(const D of E){const m=xe(D);m&&(_.push(m),!w&&typeof m._id=="string"&&k(e,m._id))}if(p===void 0)return t.with&&await Yt({groupedCounter:kt,fetcher:nt,parents:_,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:gt(_,t.select,t.with)};const b=_.length>p,A=b?_.slice(0,p):_,I=A.at(-1);return t.with&&await Yt({fetcher:nt,groupedCounter:kt,parents:A,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:b&&I&&t.omitContinueCursor!==!0?Qe(I,f):null,isDone:!b,page:gt(A,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:w}=await Pt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(C(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Wt(t))C(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const m=Kn(l.aggregateIndexes,w.op,w.field,t.by,t.where),q=m===void 0?0:Object.keys(m.partial).length,Y=m?.index.by?.length??0;if(m&&(q===0||q===Y)){ot(e,m.index);const X=st(e,m.index.name),V=Object.keys(m.partial),de=[];if(V.length===(m.index.by??[]).length&&V.length>0){const Be=ct(m.index.by??[],m.partial),We=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...m.partial},value:at(w.op,We[0])}),de}const Pn=K(y,d`SELECT ${Oe} AS key, ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)}`).toArray();for(const Be of Pn){const We=Gn(JSON.parse(Be.key));de.push({key:We,value:at(w.op,Be)})}return de}}for(const m of[...t.by,w.field]){if(m===void 0)continue;const q=m===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(l,m,q)}const _=Z(h,ue),b=t.by.map(m=>d`${fe(m)} AS ${d.identifier(m)}`);if(w.op==="count")b.push(d`COUNT(*) AS value`);else{const{field:m}=w;if(m===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(d`${d.raw(Pe(w.op))}(${fe(m)}) AS value`)}let A=d`SELECT ${d.join(b,d`, `)} FROM ${d.identifier(e)}`;_&&(A=d`${A} WHERE ${_}`),A=d`${A} GROUP BY ${d.join(t.by.map(m=>fe(m)),d`, `)}`;const I=K(y,A).toArray(),D=[];for(const m of I){const q={};for(const X of t.by)q[X]=ro(l.shape[X],m[X]??null);const{value:Y}=m;D.push({key:q,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return xt(l,e,t,i,!0);const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,yt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Sr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=vt();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:$e(),_={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{..._},id:h,op:"insert",table:e}),p||W(e,_),Se(e),ve(e),mt(y,e,wr(e),[h,E,le(_)]),Ft(e,h,_),ne(e,"after","insert")&&await oe("after","insert",{doc:_,id:h,op:"insert",table:e}),await ye({doc:_,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];vr(a.tables[e],t,i?.allowExplicitId,ce);for(const _ of t)J(_);for(const _ of t){const b=await l.insert(e,_,{allowExplicitId:i?.allowExplicitId});M({key:b,op:"insert",row:{..._,_id:b},table:e}),E.push(b)}return E}const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Uo(w),h=t.map((E,_)=>{const b=yt(w,E,ce),A=f===void 0?b:Ge(f,b,{supplied:E}),I=i?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const D=I??vt(),m=i?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:$e(),q={...A,...p[Math.floor(_/je)],_creationTime:m,_id:D};return{creationTime:m,document:q,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const _=d.join(h.slice(E,E+je).map(A=>d`(${A.id}, ${A.creationTime}, ${le(A.document)})`),d`, `),b=mn("sqlite",d`INSERT INTO ${d.identifier(e)} (id, _creationTime, ${d.identifier(ie)}) VALUES ${_}`);mt(y,e,b.sql,b.params)}for(const{document:E,id:_}of h)Ft(e,_,E),await ge({doc:E,id:_,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?xt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return ln(a,e,t)},async patch(e,t,i,l){T(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new R("INTERNAL",`unknown table: ${h}`);if(k(h,t),fn("patch",i),At(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const _=yo(E,i,f),b={...f,...Ke(_),...ee(h),_id:t};ht(E,_,b,ce);const A=Ge(E,b,{only:new Set(Object.keys(_)),previous:()=>f,tolerateStoredNull:!0});Eo(l,f,A),ne(h,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:f,table:h}),W(h,A,f),Se(h),ve(h),Ne(y,h,nn(h),[le(A),t,p]),Fe(h,t,A,f),Le(h,t,A),ke(h,f,A),_e(h,t,f,A);const I=N(h,f,A);Ee?.invalidate(h,t,I),Re(h,t,"update",A),M({indexKeys:I,key:t,op:"update",row:A,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:f,table:h}),await ye({doc:A,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!a.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=un;w+=1){const p=await Wn(e,t,i,w<un,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){T(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await cn(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._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,i),{patched:p.length}},async related(e,t){return Bo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(y,a,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Bt(e,w,p),i.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Qt(e,p.name),E=p.sortBy.map((V,de)=>Vt(de)),_=E.map(V=>Me(V)).join(", "),b=K(y,d`SELECT ${d.identifier("__partition__")}, ${d.raw(_)} FROM ${d.identifier(h)} WHERE ${d.identifier("__id__")} = ${f}`).toArray(),[A]=b;if(A===void 0)return null;let I=A.__partition__;const D=Q(i.baseWhere,i.where);ut(D,a,e,"rank");const m=To(p,D);if(m){const V=Ao(p.partitionBy??[],m);if(V!==I)return null;I=V}const q=E.map(V=>A[V]),{before:Y,total:X}=wn(y,h,E,p.sortBy,I,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(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 l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new dt(e);k(e,G),rt(e,w);const p=Qt(e,w.name),f=w.sortBy.map((E,_)=>Vt(_)),h=w.sortBy.map((E,_)=>Ce(i.sortValues[_]??null));return wn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Gt(qt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Gt(qt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const l=a.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new R("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){T(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=Te(e);if(q){J(i),await q.replace(e,t,i,l);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new R("INTERNAL",`unknown table: ${h}`);fn("replace",i);const _=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,A=_??b??$e(),I={...i,...ee(h),_creationTime:A,_id:t};ht(E,i,I,ce);const D=l?.allowExplicitId===!0,m=Ge(E,I,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:f,table:h}),D||W(h,m,f),Se(h),ve(h),Ne(y,h,pr(h),[A,le(m),t,p]),Fe(h,t,m,f),Le(h,t,m),ke(h,f,m),_e(h,t,f,m),Ee?.invalidate(h,t,N(h,f,m)),Re(h,t,"update",m),M({indexKeys:N(h,f,m),key:t,op:"update",row:m,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:f,table:h}),await ye({doc:m,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(a.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!a.tables[h])throw new R("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},qn={db:O,scheduler:_t};return n.enforceRls===!0?jo(O,a,(e,t)=>re(e,t)?.tableName,v):O};export{Ni as CDC_LOG_TABLE,ws as IDEMPOTENCY_TABLE,Fr as NotUniqueError,ls as advanceClientWatermark,Qi as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Sr as assertValidClientId,Gi as backfillAggregateIndexes,ji as backfillRankIndexes,Hi as backfillSearchIndexes,Vi as bumpCdcEpoch,Ji as cdcCanVouchFor,zi as cdcForkedError,Yi as cdcSeqLeavingRows,Xi as cdcTouchesTables,Zi as cdcTrimmedError,es as compactCdcDocs,ei as createShardCtxDb,ts as cursorBelowRetainedFloor,Nr as meterReadBytes,us as migrateClientWatermark,ns as minCdcReplayableSeq,os as minCdcSeq,ln as normalizeIdStructurally,rs as readCdcChangeKeys,is as readCdcChanges,ss as readCdcCursor,cs as readCdcEpoch,fs as readClientWatermark,ps as readIdempotent,$s as runShardMigrations,Rs as selectShapeMembers,Ss as selectShapeRows,Ke as stripReservedPatchFields,as as trimCdcChanges,gs as trimIdempotent,ys as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as y}from"@lunora/wire";import{stableStringify as T,stableWireKey as _}from"@lunora/wire";import{isPrimaryReadDep as p,depKey as l,SCAN_DEP as m}from"./SCAN_DEP-B4Uu4g7l.mjs";import{e as x}from"./estimate-bytes-C-C35VXL.mjs";import{isPointRange as v,keysTouchRanges as E}from"./buildIndexRange-BTChxh3k.mjs";const f=(a,t,e)=>{let s=a.get(t);return s===void 0&&(s=e(),a.set(t,s)),s},B=1e3,I=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??B,this.maxBytes=t.maxBytes??I,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,o=await s();if(this.generation!==c)return o;for(const n of e)if(p(n))return o;const h=x(o);if(h===void 0)return o;const b=i().filter(n=>!v(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:o,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),o}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,m),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)E([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const K=(a,t,e)=>`${e??"\0anon"}\0${a}:${y(t)}`;export{A as ReactiveCache,K as reactiveCacheKey,T as stableStringify,_ as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c="\0primary",r=`:${c}`,s="*scan",R=c,a=e=>e.endsWith(r),o=(e,n)=>`${e}:${n}`,d=e=>{const n=e.indexOf(":");return n===-1?e:e.slice(0,n)},A=()=>{const e=new Set;return{collect(){return e},recordRead(n,t){e.add(o(n,t))}}};export{R as PRIMARY_READ,s as SCAN_DEP,A as createDependencyTracker,o as depKey,a as isPrimaryReadDep,d as tableFromDepKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as A}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-jYLWUe1u.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-xu993yo2.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.
|
|
3
|
+
"version": "1.0.0-alpha.185",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.80",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
54
54
|
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Un,l as qe,s as On}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Gn,stableWireKey as Ut}from"@lunora/wire";import{sql as d}from"drizzle-orm";import{throwingScheduler as jn,aggregateSqlFunction as Pe,normalizeCountArgument as Hn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Kn,selectIndexForCount as Nn,selectIndexForAggregate as Qn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Vn,searchIndexCoversTable as Jn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Oi,backfillRankIndexes as Gi,backfillSearchIndexes as ji}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as zn,readCdcDocAtOrBefore as Yn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Ki,applyCdcChanges as Ni,bumpCdcEpoch as Qi,cdcCanVouchFor as Vi,cdcForkedError as Ji,cdcSeqLeavingRows as zi,cdcTouchesTables as Yi,cdcTrimmedError as Xi,compactCdcDocs as Zi,cursorBelowRetainedFloor as es,minCdcReplayableSeq as ts,minCdcSeq as ns,readCdcChangeKeys as os,readCdcChanges as rs,readCdcCursor as is,readCdcEpoch as ss,trimCdcChanges as cs}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as Xn,COMMIT_SEQ_FIELD as Zn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as eo}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ot}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Gt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as to,j as pt,D as ie,r as xe,W as no,k as le,b as Ue,A as lt,a as Oe,m as ue,e as fe,s as oo,t as ro,u as io,i as so,q as jt,h as $n,g as co}from"./do-sql-105TONaE.mjs";import{renderSql as mn,unionAll as Sn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as ao,u as lo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as uo,boundingBoxGeohashes as fo,haversineMeters as ho,pointInBoundingBox as wo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as po}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as go,assertPatchAllowed as yo,operatorFields as Eo,readPatchField as Ht}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as $o,encodeCursor as Qe,nullsOrderSuffix as mo,normalizeOrderKeys as Kt,uniqueIndexFields as So,buildSeekWhere as Ro,decodeCursor as Nt,buildSeekBeforeWhere as vo,softDeleteScope as Ae,applySelect as gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Qt,sortColumnName as Vt,resolveRankPartition as _o,encodePartitionKey as To,RANK_TIEBREAK as Ao,rankPivotConditionSql as Io}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Jt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as xo,withUnknownIndexKeys as bo,indexKeysForRow as Co,buildIndexRange as Mo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as Ye,i as zt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Do,isPushableWhere as ko}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Lo,findRelated as Fo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ut,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as yt,resolveWith as Yt,relationHooks as Xt,applyOnDelete as Uo,fanOutScalarCounts as Oo}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Go}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as jo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Ho}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as Ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ds,migrateClientWatermark as ls,readClientWatermark as us}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as hs,readIdempotent as ws,trimIdempotent as ps,writeIdempotent as gs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Es}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as ms,selectShapeRows as Ss}from"./selectShapeMembers-Dqx_m7BF.mjs";const No=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Qo=()=>new S("BAD_REQUEST","invalid cursor"),en=16,tn=8,z=1024,Rt=(n,r)=>r.query(n),Vo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const $ of n)(u?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Jo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},zo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=tn)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const $=Rt(u,o).length;if($>en)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Yo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Xo=n=>Math.min(n.offset+n.numItems+1,z),Zo=n=>btoa(`search:${String(n)}`),er=n=>{let r;try{r=No(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},tr=n=>{if(typeof n.endCursor=="string")throw new S("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 S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?er(n.cursor):0;if(o===void 0)throw Qo();if(o+r>=z)throw new S("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} 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:r,offset:o}},nr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Zo(o):null,isDone:!s,page:n.slice(r.offset,o)}},or=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},vn=500,_n=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},rr=32,ir=1024,An=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,r)=>Ve(to(n,r)),serialize:Ce},sr=n=>n===void 0?"":mo(n==="first"),In=n=>{const r=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${sr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${pt("id")} ${$o(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},cr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),ar=n=>{const r=xn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},dr=(n,r)=>{const o=n.order,s=ar(n),{shape:c}=r;return s.length>0?Kt(s.map(u=>({[u]:o})),c,{pinned:xn(n),uniqueBy:So(r.indexes,c)}):Kt([{_creationTime:o}],c)},lr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[cr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Nt(o))),s&&c.push(vo(r,Nt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,rr):n.want},Et=(n,r,o,s,c,u,g)=>{const $=dr(s,o),y=In($),a=[],{filters:M,want:T}=u;let v=u.cursor??void 0,x=ur(u);if(T===0)return{documents:a,orderKeys:$};for(;;){const W=Z(lr(s,$,v,u.endCursor),Xe,Ye),P=An(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,P.text,...P.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),M.every(ee=>ee(U))&&a.push(U)===T)return{documents:a,orderKeys:$};if(x===void 0||B.length<x)return{documents:a,orderKeys:$};v=Qe(U,$),x=Math.max(x,Math.min(x*2,ir))}},fr=(n,r,o,s,c,u,g,$)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:P}=Et(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?Qe(B,P):null}}const{documents:a,orderKeys:M}=Et(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},$),T=a.length>y,v=T?a.slice(0,y):a,x=v.at(-1);return{continueCursor:T&&x?Qe(x,M):null,isDone:!T,page:v}},Ze=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),hr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),wr=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),pr=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),gr="SELECT changes() AS changed",on=new Map,yr="",Er=n=>{const r=JSON.stringify(n),o=on.get(r);if(o!==void 0)return o;const s=n.map(u=>d`SELECT ${d.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(u)} WHERE id = ${yr}`),{sql:c}=mn("sqlite",d`${Sn(s)} LIMIT 1`);return on.set(r,c),c},$r=(n,r)=>r.map(()=>n),mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sr=n=>{if(!mr.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Rr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?yt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},rn=50,je=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,vr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Tn(n,_n(r,o,Je),o,Je)},cn=async(n,r,o,s,c)=>{const u=_n(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Tn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},_r=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Tr=n=>Math.max(n,z),bn=(n,r)=>{const o=n.filters.map(s=>d`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Ar=(n,r,o,s,c)=>{const u=Rt(o.query,St(o.definition.language));if(u.length===0)return[];const g=Un(r,o.indexName),$=`${g}__vocab`,y=u.length-1,a=u.map((P,B)=>{const U=Jo(P,B===y),j=U.exact?d`${d.identifier("term")} = ${U.lower}`:d`${d.identifier("term")} >= ${U.lower} AND ${d.identifier("term")} < ${U.upper}`;return d`SELECT ${d.identifier("doc")}, ${d.raw(String(B))} AS ${d.identifier("__term__")}, COUNT(*) AS ${d.identifier("__n__")} FROM ${d.identifier($)} WHERE ${j} GROUP BY ${d.identifier("doc")}`}),M=u.map((P,B)=>d`SUM(CASE WHEN u.${d.identifier("__term__")} = ${d.raw(String(B))} THEN u.${d.identifier("__n__")} ELSE 0 END)`),T=d`SELECT f.${d.identifier(qe)} AS ${d.identifier(qe)}, ${d.join(M,d` + `)} AS ${d.identifier("__score__")} FROM (${Sn(a)}) u JOIN ${d.identifier(g)} f ON f.rowid = u.${d.identifier("doc")} GROUP BY f.${d.identifier(qe)} HAVING ${d.join(M.map(P=>d`${P} > 0`),d` AND `)}`,v=bn(o,c);let x=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)}, s.${d.identifier("__score__")} AS ${d.identifier("__score__")} FROM (${T}) s JOIN ${d.identifier(r)} m ON m.id = s.${d.identifier(qe)}`;v.length>0&&(x=d`${x} WHERE ${d.join(v,d` AND `)}`),x=d`${x} ORDER BY s.${d.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${d.raw(String(s))}`;const W=[];for(const P of K(n,x)){const B=$n(P);if(B){const U=P.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},Ir=(n,r,o,s,c)=>{const u=St(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const $=bn(o,c);let y=d`SELECT id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(r)}`;$.length>0&&(y=d`${y} WHERE ${d.join($,d` AND `)}`),y=d`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${d.raw(String(Tr(s)))}`;const a=K(n,y).toArray(),M=[];for(const T of a){const v=$n(T);if(!v)continue;const x=Vo(On(v,o.definition),g);x>0&&M.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return M.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),M.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,r,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 S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},xr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",r,o.indexName),ft(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},br=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Cr=(n,r)=>{const o=br(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=ho(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return wo(o,r.within)?{creationTime:s,distance:0}:void 0},Mr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?uo(o.near.point,o.near.radiusMeters):fo(o.within),u=co(r,o.indexName),g=c.map(T=>d`(g.${d.identifier("__geohash__")} >= ${T} AND g.${d.identifier("__geohash__")} < ${`${T}{`})`),$=[d`(${d.join(g,d` OR `)})`];s&&$.push(s);const y=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)} FROM ${d.identifier(u)} g JOIN ${d.identifier(r)} m ON m.id = g.${d.identifier("__id__")} WHERE ${d.join($,d` AND `)}`,a=K(n,y).toArray(),M=[];for(const T of a){const v=xe(T),x=v?Cr(v,o):void 0;v&&x&&M.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return M.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),M},Cn=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Dr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,$=Mr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,r,o,s,c,u,g=()=>{})=>{const{geo:$}=o;if(!$)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,a=Dr(n,r,$,y?void 0:u,s,g);return y?Cn(a,c,u,M=>M.document):a},dn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&jo(s))throw new S("BAD_REQUEST",`${o}: "${r}" 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)`)},kr=n=>{let r=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:u,negated:g,parentTable:$,relation:y}=c,a=`__rel_${String(r)}`,M=o.at(-1)??$;r+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Ve(`${jt(a,v)} = ${jt(M,T)}`);o.push(a);const W=Z(u,s,Ye);o.pop();const P=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",zt(y.table)," AS ",zt(a)," WHERE ",P,")");return g?be("NOT ",B):B}};return s};class Lr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Fr=/\s/u,Br=String.fromCodePoint(0),ln=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Fr.test(o)||o.includes(Br)?null:o},Mn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const $=r.tables[o];if(!$)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae($.softDeleteMode,void 0),a=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},M=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,ue):void 0},T=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,Xe,Ye):void 0},v=()=>[...a.inMemoryFilters,...a.verifyFilters];let x=0;const W=R=>{const{search:C}=a;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Vn(io(n),o,$);const L=a.inMemoryFilters.length>0,F=or(L?void 0:R),k=so(n);if(k&&!Jn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.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 pe=M(),te=k?Ar(n,o,C,F,pe):Ir(n,o,C,F,pe);!L&&R===void 0&&Yo(te);const ge=v();return x=te.length,ge.length>0?Cn(te,ge,R,J=>J.document):te},P=R=>W(R).map(C=>C.document),B=R=>{const C=tr(R);return nr(P(Xo(C)),C)},U=()=>{if(a.search||a.geo||a.indexName===void 0){c(void 0);return}c(Mo(o,a.indexName,a.indexFields,a.sqlConditions,Ce))},j=R=>{U();let C=0;const L=(()=>{if(a.search){const F=P(R);return C=x,F}return a.geo?an(n,o,a,M(),v(),R,F=>{C=F}).map(F=>F.document):Et(n,o,$,a,T(),{filters:v(),selective:a.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!a.search&&!a.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(a.search){const L=W(void 0);return R=x,L}return an(n,o,a,M(),v(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=Mn(n,r,o,s,c,u,{...a,indexFields:[...a.indexFields],inMemoryFilters:[...a.inMemoryFilters],sqlConditions:[...a.sqlConditions],verifyFilters:[...a.verifyFilters]});if(a.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:vr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(R){const C=Do(R);return C!==void 0&&ko(C,$.shape)?(a.pushedWhere=Q(a.pushedWhere,C),a.verifyFilters.push(R)):a.inMemoryFilters.push(R),N},async first(){return j(1)[0]??null},order(R){return a.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),a.search){const F=B(R);return u(F.page.length),F}if(a.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=fr(n,o,$,a,R,T(),{all:v(),selective:a.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return j(R)},async unique(){const R=j(2);if(R.length>1)throw new Lr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=($.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(a.geo=F,C(xr(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=$.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),a.indexName=R,a.indexFields=L.fields,C&&C(_r(a)),N},withSearchIndex(R,C){const L=($.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(a.search=F,C(zo(F,o,St(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,r,o,s)=>{const c=o;for(const[u,g]of ro(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},un=5,fn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ke=n=>hn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!hn.includes(r))):n,Wr=/unique constraint failed/i,qr=n=>n instanceof Error&&Wr.test(n.message),Pr=/string or blob too big/iu,Ur=(n,r)=>{if(!(!(n instanceof Error)||!Pr.test(n.message)))throw new S("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": 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.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw qr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Ur(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,gr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,r,o,s,c,u,g)=>{const $=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],x=s[T],W=x?.direction==="desc"?"desc":"asc",P=v===void 0||x===void 0?d`${d.identifier(Ao)} < ${g}`:Io(v,u[T],W,!1);if(P===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(d`${d.identifier(o[j])} IS ${u[j]}`);B.push(P);const[U]=B;$.push(B.length===1&&U!==void 0?U:d`(${d.join(B,d` AND `)})`)}const y=$.length>0?d.join($,d` OR `):d`1 = 0`,a=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c} AND (${y})`).one(),M=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c}`).one();return{before:a.c,total:M.c}},Or=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:$,op:y}of r.get(g)??[]){if($===s||Zt(n,$,y))return!0;c.has($)||(c.add($),u.push($))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Zt(n,s,"delete")||o(s)).map(([s])=>s))},Gr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},wt=new WeakMap,jr=(n,r)=>{let o=wt.get(r.tables);if(!wt.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Hr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,$=lo(u);typeof g!="string"?r.recordReadBytes($):o===void 0?r.recordDocumentRead(`${g}\0${String($)}`,$):r.recordDocumentRead(`${o}\0${g}`,$)}}},Kr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),$=g.one.bind(g),y=g[Symbol.iterator].bind(g),a=o===void 0?void 0:jr(c,o);let M=!1;const T=v=>{Hr(v,r,a)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})T([x]),v.push(x);return v},g.one=()=>{M=!0;try{const v=$();return T([v]),v}finally{M=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})M||T([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===no?c:Reflect.get(c,u,c)})},Nr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Qr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=ao(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},ze=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Dn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Qr.get(c);return(...$)=>{const y=Reflect.apply(u,s,$);return g!==void 0?Promise.resolve(y).then(a=>(ze(a,g,r,o),a)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Dn(y,r,o):y}}}),Vr=new Set(["findFirst","findFirstOrThrow","findMany"]),Jr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>gt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:u(g.page)}:u([g])[0]}},pn=256,gn=4096,zr=1024*1024,Yr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,$=pn,y=0;for(;;){const a=await n([r[0],{...c,cursor:g,limit:$},...r.slice(2)]);if(Array.isArray(a))return ze(a,"rows",o,s),[...u,...a];const M=s.headroom().readBytes;if(ze(a,"page",o,s),u.push(...a.page),a.isDone||typeof a.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=a.continueCursor,y+=s.headroom().readBytes-M,$=y>0?Math.min(gn,Math.max(pn,Math.floor(zr*u.length/y))):gn}},Xr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),r);const u=Nr.get(s);return u===void 0?c:async(...g)=>{const $=Vr.has(s)?Jr(g):void 0,y=$?.args??g,a=String(g[0]);if(s==="findMany"&&typeof y[1]?.limit!="number"){const v=await Yr(x=>Reflect.apply(c,o,x),y,a,r);return $===void 0?v:$.project(v,u)}const T=await Reflect.apply(c,o,y);return ze(T,u,a,r),$===void 0?T:$.project(T,u)}}}),yn=new WeakMap,En=new WeakMap,Zr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=yn.get(n)??{value:void 0},u=En.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};yn.set(e,c),En.set(e,u),g=Zr(e)}return g},y=Kr(n.sql,s,n.schema),{schema:a}=n,M=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(a.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Lo(a),x=new Map;for(const e of v){const t=i=>(a.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,d`SELECT 1 FROM ${d.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},P=qo(a,n.inTransaction),B=Or(a),U=Gr(a),j=()=>n.inTransaction?.()===!0,ee=e=>a.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=Xn(y)),{[Zn]:c.value}),N=(e,...t)=>{const i=a.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(xo(w))),l.push(...bo(i,Co(i,p,Ce))));return l.length>0?l:void 0},R=n.onRead??(()=>{}),C=e=>{Ot(a.tables[e])&&R(Jt,Jt)},L=n.onReadRange??(e=>{R(e.table,G)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==G&&s?.recordRead(1),C(e),R(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,$e=n.clock??(()=>Date.now()),vt=n.idGenerator??(()=>crypto.randomUUID()),_t=n.scheduler??jn,me=Xr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,et=_t,kn=Ho({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,i,l)=>{Tt&&!Ot(a.tables[e])&&zn(y,$e(),e,t,i,l)},At=(e,t,i,l)=>{const w=a.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Yn(y,e,t,p);if(f===void 0)return!1;const h=Eo(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Ut(Ht(f,E))!==Ut(Ht(l,E)))},ae=e=>a.tables[e]?.shardMode?.kind==="global",It=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},tt=e=>It(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},xt=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return M({key:p,op:"insert",row:{...i,_id:p},table:t}),p},nt=(e,t)=>It(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),nt(e,t)),Ln=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:a,tableName:t}),kt=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),Oo((m,q)=>w.count(m,q),e,t,i,l);const p=a.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),_=await De(E,e,void 0),b=Z(_,ue),A=fe(t);let I=d`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${d.identifier(e)}`;b&&(I=d`${I} WHERE ${b}`),I=d`${I} GROUP BY ${A}`;const D=K(y,I).toArray();return new Map(D.map(m=>[m.__fk__,m.count]))},Lt=new Set;for(const[e,t]of Object.entries(a.tables))for(const i of Object.values(t.triggerMap??{}))Lt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>Lt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>rn)throw u.value-=1,new se(`trigger recursion exceeded ${String(rn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Ko({ctx:qn,event:i,op:t,schema:a,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Ft,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=eo({broadcast:M,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:a,sql:y,verified:n.companionMemo?.verified}),Bt=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.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})},Wt=e=>Object.entries(a.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?me:void 0,it=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let l=0;l<i.length;l+=sn){const w=i.slice(l,l+sn),[p]=he(y,Er(w),...$r(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},qt={assertRankPartitionLocal:Bt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:a,sql:y},Fn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,d`SELECT 1 FROM ${d.identifier(e)} WHERE ${d.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Bn=(e,t,i,l)=>At(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Wn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Fn(e,t,i.where)||Bn(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},Pt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Ln:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:a,tableName:e}),E=Mt?kr(l):Xe,_=Z(h,E,Ye),b=An(e,_,In(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:kn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);if(Pe(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 S("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const m=Qn(l.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const q=ct(m.index.by??[],m.key),Y=st(e,m.index.name),X=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return at(t.op,X)}}dn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),_=Pe(t.op),b=fe(t.field);let A=d`SELECT ${d.raw(_)}(${b}) AS value FROM ${d.identifier(e)}`;E&&(A=d`${A} WHERE ${E}`);const D=K(y,A).toArray()[0]?.value;return D??null},asId(e,t){const i=ln(a,e,t);if(i===null)throw new S("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=Hn(t);if(w.restrictsCounts)throw new dt(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const I=Nn(l.aggregateIndexes,w.where);if(I){ot(e,I.index);const D=ct(I.index.by??[],I.key),m=st(e,I.index.name),q=K(y,d`SELECT ${Ue} AS value FROM ${d.identifier(m)} WHERE ${Oe} = ${D}`).toArray();return q[0]===void 0?0:q[0].value??0}}const _=Z(h,ue);let b=d`SELECT COUNT(*) AS count FROM ${d.identifier(e)}`;return _&&(b=d`${b} WHERE ${_}`),K(y,b).one().count},async delete(e,t,i){T(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const I=Te(e);I&&await it(I,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=a.tables[f],E=i?.hard===!0,_=!E&&h?.softDeleteMode?h:void 0,b=_?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Uo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,D,m,q)=>(await tt(I).findMany(I,{...q,includeDeleted:E,where:{[D]:m}})).page,onCascade:(I,D)=>tt(I).delete(I,D,i),onRestrict:I=>{throw new se(I,"restrict")},onSetNull:(I,D,m)=>tt(I).patch(I,D,{[m]:null}),schema:a,tableName:f}),Re(f),ve(f),_&&b){const I={[b]:$e()},D={...p,...ee(f),...I,_id:t};ht(_,I,D,ce),Ne(y,f,nn(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const m=N(f,p,D);Ee?.invalidate(f,t,m),Se(f,t,"update",D),M({indexKeys:m,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,pr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const A=N(f,p);Ee?.invalidate(f,t,A),Se(f,t,"delete"),M({indexKeys:A,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??vn),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):it(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){T(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await cn(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return it(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new po(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),i.findMany(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await Pt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const _=[];for(const D of E){const m=xe(D);m&&(_.push(m),!w&&typeof m._id=="string"&&k(e,m._id))}if(p===void 0)return t.with&&await Yt({groupedCounter:kt,fetcher:nt,parents:_,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:gt(_,t.select,t.with)};const b=_.length>p,A=b?_.slice(0,p):_,I=A.at(-1);return t.with&&await Yt({fetcher:nt,groupedCounter:kt,parents:A,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:b&&I&&t.omitContinueCursor!==!0?Qe(I,f):null,isDone:!b,page:gt(A,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await Pt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(C(e),R(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Wt(t))C(l),R(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const m=Kn(l.aggregateIndexes,w.op,w.field,t.by,t.where),q=m===void 0?0:Object.keys(m.partial).length,Y=m?.index.by?.length??0;if(m&&(q===0||q===Y)){ot(e,m.index);const X=st(e,m.index.name),V=Object.keys(m.partial),de=[];if(V.length===(m.index.by??[]).length&&V.length>0){const Be=ct(m.index.by??[],m.partial),We=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...m.partial},value:at(w.op,We[0])}),de}const Pn=K(y,d`SELECT ${Oe} AS key, ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)}`).toArray();for(const Be of Pn){const We=Gn(JSON.parse(Be.key));de.push({key:We,value:at(w.op,Be)})}return de}}for(const m of[...t.by,w.field]){if(m===void 0)continue;const q=m===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(l,m,q)}const _=Z(h,ue),b=t.by.map(m=>d`${fe(m)} AS ${d.identifier(m)}`);if(w.op==="count")b.push(d`COUNT(*) AS value`);else{const{field:m}=w;if(m===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(d`${d.raw(Pe(w.op))}(${fe(m)}) AS value`)}let A=d`SELECT ${d.join(b,d`, `)} FROM ${d.identifier(e)}`;_&&(A=d`${A} WHERE ${_}`),A=d`${A} GROUP BY ${d.join(t.by.map(m=>fe(m)),d`, `)}`;const I=K(y,A).toArray(),D=[];for(const m of I){const q={};for(const X of t.by)q[X]=oo(l.shape[X],m[X]??null);const{value:Y}=m;D.push({key:q,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return xt(l,e,t,i,!0);const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,yt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Sr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=vt();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:$e(),_={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{..._},id:h,op:"insert",table:e}),p||W(e,_),Re(e),ve(e),mt(y,e,hr(e),[h,E,le(_)]),Ft(e,h,_),ne(e,"after","insert")&&await oe("after","insert",{doc:_,id:h,op:"insert",table:e}),await ye({doc:_,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];Rr(a.tables[e],t,i?.allowExplicitId,ce);for(const _ of t)J(_);for(const _ of t){const b=await l.insert(e,_,{allowExplicitId:i?.allowExplicitId});M({key:b,op:"insert",row:{..._,_id:b},table:e}),E.push(b)}return E}const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((E,_)=>{const b=yt(w,E,ce),A=f===void 0?b:Ge(f,b,{supplied:E}),I=i?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const D=I??vt(),m=i?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:$e(),q={...A,...p[Math.floor(_/je)],_creationTime:m,_id:D};return{creationTime:m,document:q,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const _=d.join(h.slice(E,E+je).map(A=>d`(${A.id}, ${A.creationTime}, ${le(A.document)})`),d`, `),b=mn("sqlite",d`INSERT INTO ${d.identifier(e)} (id, _creationTime, ${d.identifier(ie)}) VALUES ${_}`);mt(y,e,b.sql,b.params)}for(const{document:E,id:_}of h)Ft(e,_,E),await ge({doc:E,id:_,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?xt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return ln(a,e,t)},async patch(e,t,i,l){T(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),fn("patch",i),At(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const _=go(E,i,f),b={...f,...Ke(_),...ee(h),_id:t};ht(E,_,b,ce);const A=Ge(E,b,{only:new Set(Object.keys(_)),previous:()=>f,tolerateStoredNull:!0});yo(l,f,A),ne(h,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:f,table:h}),W(h,A,f),Re(h),ve(h),Ne(y,h,nn(h),[le(A),t,p]),Fe(h,t,A,f),Le(h,t,A),ke(h,f,A),_e(h,t,f,A);const I=N(h,f,A);Ee?.invalidate(h,t,I),Se(h,t,"update",A),M({indexKeys:I,key:t,op:"update",row:A,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:f,table:h}),await ye({doc:A,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=un;w+=1){const p=await Wn(e,t,i,w<un,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){T(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await cn(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Fo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(y,a,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Bt(e,w,p),i.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Qt(e,p.name),E=p.sortBy.map((V,de)=>Vt(de)),_=E.map(V=>Me(V)).join(", "),b=K(y,d`SELECT ${d.identifier("__partition__")}, ${d.raw(_)} FROM ${d.identifier(h)} WHERE ${d.identifier("__id__")} = ${f}`).toArray(),[A]=b;if(A===void 0)return null;let I=A.__partition__;const D=Q(i.baseWhere,i.where);ut(D,a,e,"rank");const m=_o(p,D);if(m){const V=To(p.partitionBy??[],m);if(V!==I)return null;I=V}const q=E.map(V=>A[V]),{before:Y,total:X}=wn(y,h,E,p.sortBy,I,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new dt(e);k(e,G),rt(e,w);const p=Qt(e,w.name),f=w.sortBy.map((E,_)=>Vt(_)),h=w.sortBy.map((E,_)=>Ce(i.sortValues[_]??null));return wn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Gt(qt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Gt(qt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const l=a.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new S("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){T(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=Te(e);if(q){J(i),await q.replace(e,t,i,l);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);fn("replace",i);const _=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,A=_??b??$e(),I={...i,...ee(h),_creationTime:A,_id:t};ht(E,i,I,ce);const D=l?.allowExplicitId===!0,m=Ge(E,I,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:f,table:h}),D||W(h,m,f),Re(h),ve(h),Ne(y,h,wr(h),[A,le(m),t,p]),Fe(h,t,m,f),Le(h,t,m),ke(h,f,m),_e(h,t,f,m),Ee?.invalidate(h,t,N(h,f,m)),Se(h,t,"update",m),M({indexKeys:N(h,f,m),key:t,op:"update",row:m,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:f,table:h}),await ye({doc:m,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(a.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!a.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},qn={db:O,scheduler:_t};return n.enforceRls===!0?Go(O,a,(e,t)=>re(e,t)?.tableName,v):O};export{Ki as CDC_LOG_TABLE,hs as IDEMPOTENCY_TABLE,Lr as NotUniqueError,ds as advanceClientWatermark,Ni as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Sr as assertValidClientId,Oi as backfillAggregateIndexes,Gi as backfillRankIndexes,ji as backfillSearchIndexes,Qi as bumpCdcEpoch,Vi as cdcCanVouchFor,Ji as cdcForkedError,zi as cdcSeqLeavingRows,Yi as cdcTouchesTables,Xi as cdcTrimmedError,Zi as compactCdcDocs,Zr as createShardCtxDb,es as cursorBelowRetainedFloor,Kr as meterReadBytes,ls as migrateClientWatermark,ts as minCdcReplayableSeq,ns as minCdcSeq,ln as normalizeIdStructurally,os as readCdcChangeKeys,rs as readCdcChanges,is as readCdcCursor,ss as readCdcEpoch,us as readClientWatermark,ws as readIdempotent,Es as runShardMigrations,ms as selectShapeMembers,Ss as selectShapeRows,Ke as stripReservedPatchFields,cs as trimCdcChanges,ps as trimIdempotent,gs as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableWireKey as y}from"@lunora/wire";import{stableStringify as M,stableWireKey as T}from"@lunora/wire";import{depKey as l,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-C-C35VXL.mjs";import{isPointRange as x,keysTouchRanges as v}from"./buildIndexRange-BTChxh3k.mjs";const f=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},E=1e3,B=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??E,this.maxBytes=t.maxBytes??B,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,a=await s();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const b=i().filter(n=>!x(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),a}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,p),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)v([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const D=(o,t,e)=>`${e??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,M as stableStringify,T as stableWireKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
|