@lunora/shard-engine 1.0.0-alpha.31 → 1.0.0-alpha.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-B0Ofch97.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DQpXOGPE.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1301,8 +1301,11 @@ interface TablesIndexesResult {
1301
1301
  indexesByTable: Record<string, TableIndexInfo[]>;
1302
1302
  }
1303
1303
  interface ColumnMeta {
1304
+ bucket?: string;
1305
+ enumValues?: string[];
1304
1306
  isStorage?: boolean;
1305
1307
  name: string;
1308
+ nullable?: boolean;
1306
1309
  optional: boolean;
1307
1310
  pk?: boolean;
1308
1311
  ref?: string;
package/dist/index.d.ts CHANGED
@@ -1301,8 +1301,11 @@ interface TablesIndexesResult {
1301
1301
  indexesByTable: Record<string, TableIndexInfo[]>;
1302
1302
  }
1303
1303
  interface ColumnMeta {
1304
+ bucket?: string;
1305
+ enumValues?: string[];
1304
1306
  isStorage?: boolean;
1305
1307
  name: string;
1308
+ nullable?: boolean;
1306
1309
  optional: boolean;
1307
1310
  pk?: boolean;
1308
1311
  ref?: string;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BixDiv4O.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as j,migrateCdcLog as Y,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{c as le}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as De,deleteShapePokeCursor as Oe,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as je}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as $e,a as er,b as rr,D as or,c as ar,d as tr,g as nr,i as sr,j as ir,e as lr,q as mr,f as pr,r as dr,t as cr,h as Sr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Dr,decideDurableAttach as Or}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-D5tgL1mR.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as jr}from"./packem_shared/isSoftDeleted-DR79pnU-.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Do}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as jo,encodePartitionKey as Yo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as Da,OwnerRelay as Oa,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ya,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-Cs-1HHP6.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ot,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-Crppyq1f.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Da as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Ot as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Dr as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Oa as OwnerRelay,qo as QUEUE_TABLE,jo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,Ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,De as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,j as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Or as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Oe as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,Yo as encodePartitionKey,it as encodeRowsPatch,D as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,Y as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,jr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,jt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,O as readAuditLog,Do as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,je as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DmGPlvxO.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as j,migrateCdcLog as Y,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{c as le}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as De,deleteShapePokeCursor as Oe,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as je}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as $e,a as er,b as rr,D as or,c as ar,d as tr,g as nr,i as sr,j as ir,e as lr,q as mr,f as pr,r as dr,t as cr,h as Sr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Dr,decideDurableAttach as Or}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-D5tgL1mR.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as jr}from"./packem_shared/isSoftDeleted-DR79pnU-.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Do}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as jo,encodePartitionKey as Yo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as Da,OwnerRelay as Oa,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ya,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-Cs-1HHP6.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ot,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-Crppyq1f.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Da as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Ot as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Dr as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Oa as OwnerRelay,qo as QUEUE_TABLE,jo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,Ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,De as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,j as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Or as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Oe as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,Yo as encodePartitionKey,it as encodeRowsPatch,D as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,Y as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,jr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,jt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,O as readAuditLog,Do as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,je as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as u}from"@lunora/errors";const l="x",g={'"':'"',"'":"'","[":"]","`":"`"},h=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
2
+ `;)e+=1;return e},m=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},E=n=>{const t=n.split("");let e=0;for(;e<n.length;){const s=n[e]??"",c=g[s];if(s==="-"&&n[e+1]==="-"){const o=h(n,e);t.fill(l,e,o),e=o}else if(s==="/"&&n[e+1]==="*"){const o=m(n,e);if(o===-1)return;t.fill(l,e,o),e=o}else if(c!==void 0){let o=e+1;for(;o<n.length;)if(n[o]!==c)o+=1;else if(c!=="]"&&n[o+1]===c)o+=2;else break;if(o>=n.length)return;t.fill(l,e,o+1),e=o+1}else e+=1}for(let s=0;s<n.length;s+=1)n[s]===`
3
+ `&&(t[s]=`
4
+ `);return t.join("")},L=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,S=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,p=/^\w+/u,A=/;\s*$/u,x=/\s/u,N=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
5
+ `;)e+=1;return e},y=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},O=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&x.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=N(n,t);else if(e==="/"&&n[t+1]==="*"){const s=y(n,t);if(s===-1)break;t=s}else break}return t},f=n=>{const t=O(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=e.replace(A,""),c=(E(s)??s).indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+c};const o="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!L.test(s))return{code:"SQL_NOT_READONLY",length:p.exec(s)?.[0].length??1,message:o,offset:t};const r=S.exec(s);if(r!==null)return{code:"SQL_NOT_READONLY",length:r[0].length,message:`${o} (\`${r[0].toUpperCase()}\` is not allowed)`,offset:t+r.index}},d=1e3,T=n=>{const t=f(n);if(t!==void 0)throw new u(t.code,t.message,{status:400})},b=(n,t)=>{T(t);const e=n.exec(t).toArray(),s=e.length>d?e.slice(0,d):e;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:e.length,rows:s,truncated:e.length>d}},_=/near "([^"]*)": syntax error/iu,R=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,w=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},v=(n,t)=>{const e=f(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:i}=r;return typeof i=="string"?i:""}).filter(r=>r!=="")}catch(r){const i=r instanceof Error?r.message:String(r),a=_.exec(i);return{diagnostics:[{...a?w(t,a[1]??""):{},message:i,severity:"error",source:"syntax"}],plan:[]}}const c=[],o=new Set;for(const r of s){const i=R.exec(r);if(i){const a=i[1]??"";o.has(a)||(o.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{d as MAX_SQL_ROWS,T as assertReadonly,v as lintReadonlySql,b as runReadonlySql};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{s as Ut,c as Pt,j as Oe,a as Gt,y as Ae,h as Ht}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Nt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as jt,aggregateSqlFunction as ve,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Le,encodeAggregateKey as Fe,readAggregateValue as We}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Be,selectIndexForGroupBy as Ot,selectIndexForCount as Qt,selectIndexForAggregate as zt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Jt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Br,backfillRankIndexes as qr,backfillSearchIndexes as Ur}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Vt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Gr,applyCdcChanges as Hr,bumpCdcEpoch as Nr,minCdcSeq as jr,readCdcChanges as Kr,readCdcCursor as Or,readCdcEpoch as Qr,trimCdcChanges as zr}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{computeRankPage as st}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as N,k as ce,r as le,b as Ie,A as qe,a as Ce,e as V,t as At,f as ct,i as Yt,h as vt,g as Xt}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as It,unionAll as He,sqliteInList as Zt}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,haversineMeters as nn,pointInBoundingBox as rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as sn,buildSeekWhere as Ct,decodeCursor as Ne,applySelect as at,encodeCursor as je,buildSeekBeforeWhere as cn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as dt,sortColumnName as lt,resolveRankPartition as an,encodePartitionKey as dn,RANK_TIEBREAK as ln}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ue,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Pe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as wn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as gn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as pn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as $n}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as ge}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as yn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as Yr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as so}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as lo,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as wo}from"./runShardMigrations-Crppyq1f.mjs";import{SEARCH_STATE_TABLE as po}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as yo,selectShapeRows as Eo}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as En}from"./quoteIdentifier-CObIFRhb.mjs";const mn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},Sn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},_n=()=>new $("BAD_REQUEST","invalid cursor"),wt=16,gt=8,X=1024,Qe=(o,i)=>i.query(o),Rn=(o,i,t)=>{const a=Ut(o,t);if(a.length===0)return 0;let f=0;for(const[g,m]of i.entries()){const v=g===i.length-1;let S=0;for(const y of a)(v?y.startsWith(m):y===m)&&(S+=1);if(S===0)return 0;f+=S}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},An=(o,i,t)=>{const a={eq:(f,g)=>{if(!o.definition.filterFields?.includes(f))throw new $("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=gt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(gt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:g}),a},search:(f,g)=>{const m=o;if(f!==m.definition.field)throw new $("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${f}"`);const v=Qe(g,t).length;if(v>wt)throw new $("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(wt)} search terms are supported (got ${String(v)})`);return m.field=f,m.query=g,m.hasQuery=!0,a}};return a},vn=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},In=o=>Math.min(o.offset+o.numItems+1,X),Cn=o=>mn(`search:${String(o)}`),xn=o=>{let i;try{i=Sn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Mn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?xn(o.cursor):0;if(t===void 0)throw _n();if(t+i>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Cn(t):null,isDone:!a,page:o.slice(i.offset,t)}},Dn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ln=o=>{if(!kn.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},pt=50,xt=500,$t=Math.floor(It.boundParams/3),we=It.boundParams,Fn=128,ae=(o,i,t)=>{const a=i??xt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Wn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Bn=o=>Math.max(o,X),Mt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${ie(a.value)}`);return i&&t.push(i),t},qn=(o,i,t,a,f)=>{const g=Qe(t.query,Oe(t.definition.language));if(g.length===0)return[];const m=Gt(i,t.indexName),v=`${m}__vocab`,S=g.length-1,y=g.map((F,k)=>{const j=Tn(F,k===S),K=j.exact?r`${r.identifier("term")} = ${j.lower}`:r`${r.identifier("term")} >= ${j.lower} AND ${r.identifier("term")} < ${j.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(k))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(v)} WHERE ${K} GROUP BY ${r.identifier("doc")}`}),_=g.map((F,k)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(k))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),R=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(_,r` + `)} AS ${r.identifier("__score__")} FROM (${He(y)}) u JOIN ${r.identifier(m)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(_.map(F=>r`${F} > 0`),r` AND `)}`,T=Mt(t,f);let x=r`SELECT m.id, m._creationTime, m.${r.identifier(N)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${R}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;T.length>0&&(x=r`${x} WHERE ${r.join(T,r` AND `)}`),x=r`${x} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const W=[];for(const F of q(o,x)){const k=vt(F);if(k){const j=F.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Un=(o,i,t,a,f)=>{const g=Oe(t.definition.language),m=Qe(t.query,g);if(m.length===0)return[];const v=Mt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Bn(a)))}`;const y=q(o,S).toArray(),_=[];for(const R of y){const T=vt(R);if(!T)continue;const x=Rn(Ht(T,t.definition),m,g);x>0&&_.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return _.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),_.slice(0,a).map(R=>({document:R.doc,score:R.score}))},Ge=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Pn=(o,i)=>{const t=o,a={near:(f,g)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f,".near() point",i,t.indexName),!Number.isFinite(g)||g<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(g)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:g},a},within:f=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f.sw,".within() sw corner",i,t.indexName),Ge(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Gn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Hn=(o,i)=>{const t=Gn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=nn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return rn(t,i.within)?{creationTime:a,distance:0}:void 0},Nn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),g=Xt(i,t.indexName),m=f.map(R=>r`(g.${r.identifier("__geohash__")} >= ${R} AND g.${r.identifier("__geohash__")} < ${`${R}{`})`),v=[r`(${r.join(m,r` OR `)})`];a&&v.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(N)} FROM ${r.identifier(g)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(v,r` AND `)}`,y=q(o,S).toArray(),_=[];for(const R of y){const T=le(R),x=T?Hn(T,t):void 0;T&&x&&_.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return _.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),_},bt=(o,i,t,a)=>{const f=[];for(const g of o)if(i.every(m=>m(a(g)))&&(f.push(g),typeof t=="number"&&f.length>=t))break;return f},jn=(o,i,t,a,f,g=()=>{})=>{const m=t.within!==void 0,v=Nn(o,i,t,f).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return g(v.length),typeof a=="number"?v.slice(0,Math.max(0,Math.floor(a))):v},Dt=(o,i,t,a,f,g=()=>{})=>{const{geo:m}=t;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const v=t.inMemoryFilters.length>0,S=jn(o,i,m,v?void 0:f,a,g);return v?bt(S,t.inMemoryFilters,f,y=>y.document):S},Kn=(o,i,t,a,f,g=()=>{})=>Dt(o,i,t,a,f,g).map(m=>m.document),On=(o,i,t,a,f,g,m=()=>{})=>{const v=[];for(const R of t.sqlConditions)v.push(r`${V(R.field)} ${r.raw(R.comparator)} ${ie(R.value)}`);a&&v.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof g=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(g))))}`);const y=q(o,S).toArray();m(y.length);const _=[];for(const R of y){const T=le(R);if(T&&t.inMemoryFilters.every(x=>x(T))&&(_.push(T),typeof g=="number"&&_.length>=g))break}return _},oe={fieldRef:V,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&pn(t)},yt=(o,i)=>i.some(t=>kt(o,t)),Et=(o,i,t)=>{if(kt(o,i))throw new $("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Qn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:g,negated:m,parentTable:v,relation:S}=f,y=`__rel_${String(i)}`,_=t.at(-1)??v;i+=1,o(S.table,H);const R=S.kind==="one"?S.field:S.references,T=S.kind==="one"?S.references:S.field,x=r`${ct(y,T)} = ${ct(_,R)}`;t.push(y);const W=te(g,a);t.pop();const F=W?r`${x} AND ${W}`:x,k=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier(y)} WHERE ${F})`;return m?r`NOT ${k}`:k},serialize:ie};return a},Lt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Jn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Vn=(o,i,t,a)=>{const f=o.sqlConditions.map(g=>({[g.field]:{[zn[g.comparator]??"eq"]:g.value}}));if(t&&f.push(Ct(i,Ne(t))),a&&f.push(cn(i,Ne(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},Yn=(o,i,t)=>{const a=[];for(const f of o){const g=le(f);if(g&&i.every(m=>m(g))&&(a.push(g),t!==void 0&&a.length>t))break}return a},Xn=(o,i,t,a,f,g=()=>{})=>{const m=Math.max(0,Math.floor(a.numItems)),v=Jn(t),S=typeof a.endCursor=="string",y=te(Vn(t,v,a.cursor,a.endCursor),oe),_=f&&y?r`${y} AND ${f}`:f??y;let R=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;_&&(R=r`${R} WHERE ${_}`),R=r`${R} ORDER BY ${Lt(v)}`;const T=t.inMemoryFilters.length>0;!T&&!S&&(R=r`${R} LIMIT ${r.raw(String(m+1))}`);const x=q(o,R).toArray();g(x.length);const W=Yn(x,t.inMemoryFilters,T||S?void 0:m);if(S){const K=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:W,splitCursor:K?je(K,v):null}}const F=W.length>m,k=F?W.slice(0,m):W,j=k.at(-1);return{continueCursor:F&&j?je(j,v):null,isDone:!F,page:k}};class Zn extends ${constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),mt=(o,i,t)=>{if(!o.tables[i])throw new $("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,a=()=>{},f=()=>{},g=()=>{})=>{const m=i.tables[t];if(!m)throw new $("INTERNAL",`unknown table: ${t}`);const v=de(m.softDeleteMode,void 0),S=v?te(v,oe):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let _=0;const R=E=>{const{search:I}=y;if(!I)throw new $("INTERNAL","runSearchFetch called without a staged search");Jt(o,t,m);const b=y.inMemoryFilters.length>0,L=Dn(b?void 0:E),J=Yt(o)?qn(o,t,I,L,S):Un(o,t,I,L,S);return b?(_=J.length,bt(J,y.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&vn(J),J)},T=E=>R(E).map(I=>I.document),x=E=>{const I=Mn(E);return bn(T(In(I)),I)},W=()=>{const E=y.indexFields.length>0?y.indexFields:["_creationTime"],I=y.order==="desc"?"DESC":"ASC";return r.join(E.map(b=>r`${V(b)} ${r.raw(I)}`),r`, `)},F=()=>{if(y.search||y.geo||y.indexName===void 0){f(void 0);return}f(fn(t,y.indexName,y.indexFields,y.sqlConditions,ie))},k=E=>{F();let I=0;const b=(()=>{if(y.search){const L=T(E);return I=_,L}return y.geo?Kn(o,t,y,S,E,L=>{I=L}):On(o,t,y,S,W(),E,L=>{I=L})})();return g(Math.max(I,b.length)),b},j=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let E=0;const I=(()=>{if(y.search){const b=R(void 0);return E=_,b}return Dt(o,t,y,S,void 0,b=>{E=b})})();return g(Math.max(E,I.length)),I},K={async*[Symbol.asyncIterator](){const E=[...y.inMemoryFilters];let I;y.inMemoryFilters=[];try{for(;;){const b=await K.paginate({cursor:I??null,numItems:Fn});for(const L of b.page)E.every(J=>J(L))&&(yield L);if(b.isDone||b.continueCursor===null)return;I=b.continueCursor}}finally{y.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(E){return y.inMemoryFilters.push(E),K},async first(){return k(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return y.order=E==="desc"?"desc":"asc",K},async paginate(E){let I=0;if(F(),y.search){const L=x(E);return g(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Xn(o,t,y,E,S,L=>{I=L});return g(Math.max(I,b.page.length)),b},async take(E){return k(E)},async unique(){const E=k(y.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const b=(m.geoIndexes??[]).find(J=>J.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${t}"`);a(t,E,"geo");const L={definition:b,indexName:E};if(y.geo=L,I(Pn(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(E,I){const b=m.indexes.find(L=>L.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${t}"`);return a(t,E,"index"),y.indexName=E,y.indexFields=b.fields,I&&I(Wn(y)),K},withSearchIndex(E,I){const b=(m.searchIndexes??[]).find(J=>J.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${t}"`);a(t,E,"search");const L={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(y.search=L,I(An(L,t,Oe(b.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return K}};return K},St=(o,i,t)=>{const a={...i};for(const[f,g]of At(o)){if(g.serverDefault){a[f]=g.serverDefault({auth:t});continue}a[f]===void 0&&(g.defaultFn?a[f]=g.defaultFn():"defaultValue"in g&&(a[f]=g.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[g,m]of At(o)){if(m.serverDefault){g in i&&(f[g]=m.serverDefault({auth:a}));continue}m.onUpdateFn&&!(g in i)&&(f[g]=m.onUpdateFn())}},Rt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),Ke=(o,i,t)=>{try{q(o,t)}catch(a){throw or(a)?new ge(`unique constraint violation on "${i}"`,"unique"):a}},xe=(o,i,t)=>{if(Ke(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new ge(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,a,f,g,m)=>{const v=[];for(let R=0;R<t.length+1;R+=1){const T=[];for(let k=0;k<R;k+=1)T.push(r`${r.identifier(t[k])} IS ${g[k]}`);const x=t[R],W=a[R];if(x!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";T.push(r`${r.identifier(x)} ${r.raw(k)} ${g[R]}`)}else T.push(r`${r.identifier(ln)} < ${m}`);const[F]=T;v.push(T.length===1&&F!==void 0?F:r`(${r.join(T,r` AND `)})`)}const S=r.join(v,r` OR `),y=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),_=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:y.c,total:_.c}},Lr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{}),f=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...un(s,h,ie));return u.length>0?u:void 0},{headroom:g}=o;let m=!1;const v=async e=>{const n=m;m=!0;try{return await e()}finally{m=n}},S=o.onRead??(()=>{}),y=o.onReadRange??(e=>{S(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!m&&g?.recordRead(1),S(e,n)},R=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),x=e=>{m||g?.recordWrite(e)},W=async e=>{x(e.doc),await T(e)},{cache:F}=o,k=o.clock??(()=>Date.now()),j=o.idGenerator??(()=>crypto.randomUUID()),K=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},b=o.cdc??!1,L=K,J=$n({scheduler:typeof L.list=="function"&&typeof L.get=="function"?L:void 0,storage:o.storage}),ne=(e,n,s,u)=>{b&&Vt(i,k(),e,n,s,u)},se=e=>t.tables[e]?.shardMode?.kind==="global",ze=(e,n)=>{if(se(e)){if(!E)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return U},Me=e=>ze(e,"cascade"),Q=(e,n)=>{if(se(e)){if(!E)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},Je=async(e,n,s,u,h)=>{h&&x(s);const d=await e.insert(n,s,u);return a({key:d,op:"insert",row:{...s,_id:d},table:n}),d},be=(e,n)=>ze(e,"relation load").findMany(e,n),Ve=(e,n)=>(se(e)&&_(e,H),be(e,n)),Ft=e=>!se(e.table),Ye=o.relationExistsPushDown??"auto",Xe=Ye!=="never",{maxRelationKeys:Ze}=o,pe=(e,n,s)=>ut(e,{fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:s,schema:t,tableName:n}),et=async(e,n,s,u)=>{const h=Q(e,"relation grouped count");if(h)return _(e,H),wn((B,A)=>h.count(B,A),e,n,s,u);const d=t.tables[e];if(!d)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const c=de(d.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,u),c),C=await pe(w,e,void 0),p=te(C,oe),M=V(n);let D=r`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${M}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))tt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>tt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>pt)throw $e-=1,new ge(`trigger recursion exceeded ${String(pt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Bt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:De,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:nt,syncGeo:Ee,syncRanks:he,syncSearch:me}=Pt({broadcast:a,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,s)=>F?.invalidate(e,n,f(e,s)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=ot(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(p)} WHERE id = ${e}`),[d]=q(i,r`${He(h)} LIMIT 1`).toArray();if(!d)continue;const c=d.__t__,l=le(d);if(typeof c!="string"||!l)return;const w=d[N];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},Wt=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ot(n);for(let d=0;d<h.length;d+=we){const c=h.slice(d,d+we),l=Math.floor(we/c.length),w=Zt(r`${r.identifier("id")}`,s,!1,l),C=c.map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(p)} WHERE ${w}`);for(const p of q(i,He(C))){const{id:M,__t__:D}=p;typeof D=="string"&&typeof M=="string"&&u.set(M,D)}}return u},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:_,rowToDocument:le,schema:t,sql:i},U={system:J,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=de(u.softDeleteMode,void 0),d=z(z(n.baseWhere,n.where),h),c=await pe(d,e,n.relationBaseWhere),l=c!==d;if(u.aggregateIndexes&&!n.baseWhere&&!l&&(!h||yt(u,[n.field]))){const B=zt(u.aggregateIndexes,n.op,n.field,n.where);if(B){De(e,B.index);const A=Fe(B.index.by??[],B.key),O=Le(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(O)} WHERE ${Ce} = ${A}`).toArray()[0];return We(n.op,Y)}}Et(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,oe),C=ve(n.op),p=V(n.field);let M=r`SELECT ${r.raw(C)}(${p}) AS value FROM ${r.identifier(e)}`;w&&(M=r`${M} WHERE ${w}`);const P=q(i,M).toArray()[0]?.value;return P??null},asId(e,n){const s=mt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=Kt(n);if(h.restrictsCounts)throw new Be(e);_(e,H);const d=de(u.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),d),l=await pe(c,e,h.relationBaseWhere),w=l!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!d){const D=Qt(u.aggregateIndexes,h.where);if(D){De(e,D.index);const P=Fe(D.index.by??[],D.key),B=Le(e,D.index.name),A=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const C=te(l,oe);let p=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return C&&(p=r`${p} WHERE ${C}`),q(i,p).one().count},async delete(e,n,s){const u=re(e,n);if(!u){const p=n===void 0?E:void 0;p&&(x(void 0),await p.delete(e,void 0,s));return}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c],w=s?.hard===!0,C=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(C&&d[C]!==null&&d[C]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:d,table:c}),await hn({deletedId:e,deletedReference:p=>d[p],findHolders:async(p,M,D)=>(await Me(p).findMany(p,{includeDeleted:w,where:{[M]:D}})).page,onCascade:(p,M)=>Me(p).delete(M,void 0,s),onRestrict:p=>{throw new ge(p,"restrict")},onSetNull:(p,M,D)=>Me(p).patch(M,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),C){const p={...d,[C]:k(),_id:e};xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(p)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,p,d),Ee(c,e,void 0),ye(c,d,p),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d,p)),ne(c,e,"update",p),a({indexKeys:f(c,d,p),key:e,op:"update",row:p,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c});return}xe(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,d,void 0),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d)),ne(c,e,"delete"),a({indexKeys:f(c,d),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??xt),u=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let d=0;return await v(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,u),d+=1;if(l.length<s)break}}),{deleted:d}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const d=(await(Q(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(d.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(d,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const d=sn(n.orderBy),c=n.cursor?Ct(d,Ne(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(u.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Ft:void 0,existsPushMode:Ye==="always"?"always":"auto",fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=Xe?Qn(_):oe,C=te(l,w);let p=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(e)}`;C&&(p=r`${p} WHERE ${C}`),p=r`${p} ORDER BY ${Lt(d)}`;const M=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;M!==void 0&&(p=r`${p} LIMIT ${r.raw(String(M+1))}`);const D=q(i,p).toArray();h&&!m&&g?.recordRead(D.length);const P=[];for(const Y of D){const G=le(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(M===void 0)return n.with&&await ft({groupedCounter:et,fetcher:be,parents:P,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:at(P,n.select,n.with)};const B=P.length>M,A=B?P.slice(0,M):P,O=A.at(-1);return n.with&&await ft({fetcher:be,groupedCounter:et,parents:A,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&O?je(O,d):null,isDone:!B,page:at(A,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const u=n===void 0?E:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const d=de(u.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),d),l=await pe(c,e,n.relationBaseWhere),w=l!==c,C=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!d||yt(u,C))){const A=Ot(u.aggregateIndexes,h.op,h.field,n.by,n.where),O=A===void 0?0:Object.keys(A.partial).length,Y=A?.index.by?.length??0;if(A&&(O===0||O===Y)){De(e,A.index);const G=Le(e,A.index.name),Se=Object.keys(A.partial),_e=[];if(Se.length===(A.index.by??[]).length&&Se.length>0){const Re=Fe(A.index.by??[],A.partial),Te=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...A.partial},value:We(h.op,Te[0])}),_e}const qt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of qt){const Te=Nt(JSON.parse(Re.key));_e.push({key:Te,value:We(h.op,Re)})}return _e}}for(const A of C){if(A===void 0)continue;const O=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Et(u,A,O)}const p=te(l,oe),M=n.by.map(A=>r`${V(A)} AS ${r.identifier(A)}`);if(h.op==="count")M.push(r`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(r`${r.raw(ve(h.op))}(${V(A)}) AS value`)}let D=r`SELECT ${r.join(M,r`, `)} FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${r.join(n.by.map(A=>V(A)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const A of P){const O={};for(const G of n.by)O[G]=A[G]??null;const{value:Y}=A;B.push({key:O,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=Q(e,"insert");if(u)return Je(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const d=St(h,n,I);Pe(h,d);let c;s?.clientId!==void 0?(Ln(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof d._id=="string"?c=d._id:c=j();const l=s?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:k(),w={...d,_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES (${c}, ${l}, ${ce(w)})`),nt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await W({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const l of n)x(l);for(const l of n){const w=await u.insert(e,l,{allowExplicitId:s?.allowExplicitId});a({key:w,op:"insert",row:{...l,_id:w},table:e}),c.push(w)}return c}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const d=n.map(c=>{const l=St(h,c,I),w=s?.allowExplicitId===!0&&typeof l._id=="string"?l._id:j(),C=s?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:k();return{creationTime:C,document:{...l,_creationTime:C,_id:w},id:w}});for(const c of d)x(c.document);for(let c=0;c<d.length;c+=$t){const l=r.join(d.slice(c,c+$t).map(w=>r`(${w.id}, ${w.creationTime}, ${ce(w.document)})`),r`, `);Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES ${l}`)}for(const{document:c,id:l}of d)nt(e,l,c),await T({doc:c,id:l,op:"insert",table:e});return d.map(c=>c.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],d=Q(e,"insert");if(d)for(const l of n)x(l);const c=async l=>d?Je(d,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(u&&w instanceof ge&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return mt(t,e,n)},async patch(e,n,s){const u=re(e,s);if(!u){const C=s===void 0?E:void 0;if(C){x(n),await C.patch(e,n);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Rt("patch",n);const w={...d,...n,_id:e};_t(l,n,w,I),Pe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:d,table:c}),ue(c),fe(c),xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(w)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,w,d),Ee(c,e,w),ye(c,d,w),he(c,e,d,w),F?.invalidate(c,e,f(c,d,w)),ne(c,e,"update",w),a({indexKeys:f(c,d,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:d,table:c}),await W({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const d=(await(Q(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(d.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(d,s),{patched:d.length}},query(e){const n=Q(e,"query");return n?(_(e,H),n.query(e)):nr(i,t,e,R,s=>{s?y(s):_(e,H)},s=>{m||g?.recordRead(s)})},async rank(e,n,s){const u=Q(e,"rank");if(u)return _(e,H),u.rank(e,n,s);R(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const d=h.rankIndexes?.find(G=>G.name===n);if(!d)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,d),s.restrictsCounts)throw new Be(e);_(e,H),ke(e,d);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=dt(e,d.name),w=d.sortBy.map((G,Se)=>lt(Se)),C=w.map(G=>En(G)).join(", "),p=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(C)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[M]=p;if(M===void 0)return null;let D=M.__partition__;const P=z(s.baseWhere,s.where);Ue(P,t,e,"rank");const B=an(d,P);if(B){const G=dn(d.partitionBy??[],B);if(G!==D)return null;D=G}const A=w.map(G=>M[G]),{before:O,total:Y}=Tt(i,l,w,d.sortBy,D,A,c);return{position:O+1,total:Y}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Be(e);_(e,H),ke(e,h);const d=dt(e,h.name),c=h.sortBy.map((w,C)=>lt(C)),l=h.sortBy.map((w,C)=>ie(s.sortValues[C]??null));return Tt(i,d,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);R(e,n,"rank");const{continueCursor:h,hasMore:d,rows:c}=st(it,e,n,s);return{continueCursor:h,isDone:!d,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage"),R(e,n,"rank");const{directions:u,hasMore:h,rows:d}=st(it,e,n,s);return{directions:u,hasMore:h,rows:d}},async restore(e,n){const s=re(e,n);if(!s){const d=n===void 0?E:void 0;if(d?.restore){await d.restore(e);return}throw new $("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=re(e,s);if(!h){const M=s===void 0?E:void 0;if(M){x(n),await M.replace(e,n,void 0,u);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Rt("replace",n);const C=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:k(),p={...n,_creationTime:C,_id:e};_t(w,n,p,I),Pe(w,p),Z(l,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:c,table:l}),ue(l),fe(l),xe(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${C}, ${r.identifier(N)} = ${ce(p)} WHERE id = ${e} AND ${r.identifier(N)} = ${d}`),me(l,e,p,c),Ee(l,e,p),ye(l,c,p),he(l,e,c,p),F?.invalidate(l,e,f(l,c,p)),ne(l,e,"update",p),a({indexKeys:f(l,c,p),key:e,op:"update",row:p,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:c,table:l}),await W({doc:p,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let d=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,d+=w.deleted}return{deleted:d,tables:h}}},Bt={db:U,scheduler:K};return o.enforceRls===!0?gn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Wt(e,n)):U};export{Gr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Zn as NotUniqueError,po as SEARCH_STATE_TABLE,Yr as advanceClientWatermark,Hr as applyCdcChanges,Ln as assertValidClientId,Br as backfillAggregateIndexes,qr as backfillRankIndexes,Ur as backfillSearchIndexes,Nr as bumpCdcEpoch,Lr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,jr as minCdcSeq,mt as normalizeIdStructurally,Kr as readCdcChanges,Or as readCdcCursor,Qr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,lo as readIdempotent,wo as runShardMigrations,yo as selectShapeMemberIds,Eo as selectShapeRows,zr as trimCdcChanges,uo as trimIdempotent,so as writeGlobalShapeSnapshot,fo as writeIdempotent};
@@ -1 +1 @@
1
- import{createShardCtxDb as S}from"./NotUniqueError-BixDiv4O.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-Crppyq1f.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as S}from"./NotUniqueError-DmGPlvxO.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-Crppyq1f.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.31",
3
+ "version": "1.0.0-alpha.33",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,2 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";const g=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,f=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,m=/;\s*$/u,E=/\s/u,L=(n,e)=>{let t=e+2;for(;t<n.length&&n[t]!==`
2
- `;)t+=1;return t},S=(n,e)=>{const t=n.indexOf("*/",e+2);return t===-1?-1:t+2},p=n=>{let e=0;for(;e<n.length;){const t=n[e];if(t!==void 0&&E.test(t))e+=1;else if(t==="-"&&n[e+1]==="-")e=L(n,e);else if(t==="/"&&n[e+1]==="*"){const s=S(n,e);if(s===-1)break;e=s}else break}return e},d=n=>{const e=p(n),t=n.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=t.replace(m,""),c=s.indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+c};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!g.test(s))return{code:"SQL_NOT_READONLY",length:h.exec(s)?.[0].length??1,message:i,offset:e};const o=f.exec(s);if(o!==null)return{code:"SQL_NOT_READONLY",length:o[0].length,message:`${i} (\`${o[0].toUpperCase()}\` is not allowed)`,offset:e+o.index}},l=1e3,A=n=>{const e=d(n);if(e!==void 0)throw new u(e.code,e.message,{status:400})},O=(n,e)=>{A(e);const t=n.exec(e).toArray(),s=t.length>l?t.slice(0,l):t;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:t.length,rows:s,truncated:t.length>l}},y=/near "([^"]*)": syntax error/iu,N=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,x=(n,e)=>{if(e==="")return{};const t=n.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},_=(n,e)=>{const t=d(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=n.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(o=>{const{detail:r}=o;return typeof r=="string"?r:""}).filter(o=>o!=="")}catch(o){const r=o instanceof Error?o.message:String(o),a=y.exec(r);return{diagnostics:[{...a?x(e,a[1]??""):{},message:r,severity:"error",source:"syntax"}],plan:[]}}const c=[],i=new Set;for(const o of s){const r=N.exec(o);if(r){const a=r[1]??"";i.has(a)||(i.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{l as MAX_SQL_ROWS,A as assertReadonly,_ as lintReadonlySql,O as runReadonlySql};
@@ -1 +0,0 @@
1
- import{LunoraError as E}from"@lunora/errors";import{s as Ut,c as Pt,j as Oe,a as Gt,y as Ae,h as Ht}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Nt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as jt,aggregateSqlFunction as ve,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Le,encodeAggregateKey as Fe,readAggregateValue as We}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Be,selectIndexForGroupBy as Ot,selectIndexForCount as Qt,selectIndexForAggregate as zt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Jt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Br,backfillRankIndexes as qr,backfillSearchIndexes as Ur}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Vt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Gr,applyCdcChanges as Hr,bumpCdcEpoch as Nr,minCdcSeq as jr,readCdcChanges as Kr,readCdcCursor as Or,readCdcEpoch as Qr,trimCdcChanges as zr}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{computeRankPage as st}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as N,k as ce,r as le,b as Ie,A as qe,a as Ce,e as V,t as At,f as ct,i as Yt,h as vt,g as Xt}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as It,unionAll as He,sqliteInList as Zt}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,haversineMeters as nn,pointInBoundingBox as rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as sn,buildSeekWhere as Ct,decodeCursor as Ne,applySelect as at,encodeCursor as je,buildSeekBeforeWhere as cn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as dt,sortColumnName as lt,resolveRankPartition as an,encodePartitionKey as dn,RANK_TIEBREAK as ln}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ue,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Pe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as wn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as gn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as $n}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as yn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as Yr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as so}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as lo,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as wo}from"./runShardMigrations-Crppyq1f.mjs";import{SEARCH_STATE_TABLE as go}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as yo,selectShapeRows as Eo}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as En}from"./quoteIdentifier-CObIFRhb.mjs";const mn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},Sn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},_n=()=>new E("BAD_REQUEST","invalid cursor"),wt=16,pt=8,X=1024,Qe=(o,i)=>i.query(o),Rn=(o,i,t)=>{const a=Ut(o,t);if(a.length===0)return 0;let f=0;for(const[p,m]of i.entries()){const v=p===i.length-1;let S=0;for(const $ of a)(v?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;f+=S}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},An=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new E("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new E("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const m=o;if(f!==m.definition.field)throw new E("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${f}"`);const v=Qe(p,t).length;if(v>wt)throw new E("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(wt)} search terms are supported (got ${String(v)})`);return m.field=f,m.query=p,m.hasQuery=!0,a}};return a},vn=o=>{if(o.length>X)throw new E("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},In=o=>Math.min(o.offset+o.numItems+1,X),Cn=o=>mn(`search:${String(o)}`),xn=o=>{let i;try{i=Sn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Mn=o=>{if(typeof o.endCursor=="string")throw new E("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?xn(o.cursor):0;if(t===void 0)throw _n();if(t+i>X)throw new E("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Cn(t):null,isDone:!a,page:o.slice(i.offset,t)}},Dn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new E("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ln=o=>{if(!kn.test(o))throw new E("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},gt=50,xt=500,$t=Math.floor(It.boundParams/3),we=It.boundParams,Fn=128,ae=(o,i,t)=>{const a=i??xt;if(o>a)throw new E("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Wn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Bn=o=>Math.max(o,X),Mt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${ie(a.value)}`);return i&&t.push(i),t},qn=(o,i,t,a,f)=>{const p=Qe(t.query,Oe(t.definition.language));if(p.length===0)return[];const m=Gt(i,t.indexName),v=`${m}__vocab`,S=p.length-1,$=p.map((F,k)=>{const j=Tn(F,k===S),K=j.exact?r`${r.identifier("term")} = ${j.lower}`:r`${r.identifier("term")} >= ${j.lower} AND ${r.identifier("term")} < ${j.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(k))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(v)} WHERE ${K} GROUP BY ${r.identifier("doc")}`}),_=p.map((F,k)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(k))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),R=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(_,r` + `)} AS ${r.identifier("__score__")} FROM (${He($)}) u JOIN ${r.identifier(m)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(_.map(F=>r`${F} > 0`),r` AND `)}`,T=Mt(t,f);let x=r`SELECT m.id, m._creationTime, m.${r.identifier(N)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${R}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;T.length>0&&(x=r`${x} WHERE ${r.join(T,r` AND `)}`),x=r`${x} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const W=[];for(const F of q(o,x)){const k=vt(F);if(k){const j=F.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Un=(o,i,t,a,f)=>{const p=Oe(t.definition.language),m=Qe(t.query,p);if(m.length===0)return[];const v=Mt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Bn(a)))}`;const $=q(o,S).toArray(),_=[];for(const R of $){const T=vt(R);if(!T)continue;const x=Rn(Ht(T,t.definition),m,p);x>0&&_.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return _.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),_.slice(0,a).map(R=>({document:R.doc,score:R.score}))},Ge=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new E("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Pn=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f.sw,".within() sw corner",i,t.indexName),Ge(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Gn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Hn=(o,i)=>{const t=Gn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=nn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return rn(t,i.within)?{creationTime:a,distance:0}:void 0},Nn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),p=Xt(i,t.indexName),m=f.map(R=>r`(g.${r.identifier("__geohash__")} >= ${R} AND g.${r.identifier("__geohash__")} < ${`${R}{`})`),v=[r`(${r.join(m,r` OR `)})`];a&&v.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(N)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(v,r` AND `)}`,$=q(o,S).toArray(),_=[];for(const R of $){const T=le(R),x=T?Hn(T,t):void 0;T&&x&&_.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return _.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),_},bt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(m=>m(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},jn=(o,i,t,a,f,p=()=>{})=>{const m=t.within!==void 0,v=Nn(o,i,t,f).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(v.length),typeof a=="number"?v.slice(0,Math.max(0,Math.floor(a))):v},Dt=(o,i,t,a,f,p=()=>{})=>{const{geo:m}=t;if(!m)throw new E("INTERNAL","runGeoTerminalScored called without a staged geo query");const v=t.inMemoryFilters.length>0,S=jn(o,i,m,v?void 0:f,a,p);return v?bt(S,t.inMemoryFilters,f,$=>$.document):S},Kn=(o,i,t,a,f,p=()=>{})=>Dt(o,i,t,a,f,p).map(m=>m.document),On=(o,i,t,a,f,p,m=()=>{})=>{const v=[];for(const R of t.sqlConditions)v.push(r`${V(R.field)} ${r.raw(R.comparator)} ${ie(R.value)}`);a&&v.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();m($.length);const _=[];for(const R of $){const T=le(R);if(T&&t.inMemoryFilters.every(x=>x(T))&&(_.push(T),typeof p=="number"&&_.length>=p))break}return _},oe={fieldRef:V,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&gn(t)},yt=(o,i)=>i.some(t=>kt(o,t)),Et=(o,i,t)=>{if(kt(o,i))throw new E("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Qn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:m,parentTable:v,relation:S}=f,$=`__rel_${String(i)}`,_=t.at(-1)??v;i+=1,o(S.table,H);const R=S.kind==="one"?S.field:S.references,T=S.kind==="one"?S.references:S.field,x=r`${ct($,T)} = ${ct(_,R)}`;t.push($);const W=te(p,a);t.pop();const F=W?r`${x} AND ${W}`:x,k=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${F})`;return m?r`NOT ${k}`:k},serialize:ie};return a},Lt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Jn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Vn=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[zn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Ct(i,Ne(t))),a&&f.push(cn(i,Ne(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},Yn=(o,i,t)=>{const a=[];for(const f of o){const p=le(f);if(p&&i.every(m=>m(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Xn=(o,i,t,a,f,p=()=>{})=>{const m=Math.max(0,Math.floor(a.numItems)),v=Jn(t),S=typeof a.endCursor=="string",$=te(Vn(t,v,a.cursor,a.endCursor),oe),_=f&&$?r`${$} AND ${f}`:f??$;let R=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;_&&(R=r`${R} WHERE ${_}`),R=r`${R} ORDER BY ${Lt(v)}`;const T=t.inMemoryFilters.length>0;!T&&!S&&(R=r`${R} LIMIT ${r.raw(String(m+1))}`);const x=q(o,R).toArray();p(x.length);const W=Yn(x,t.inMemoryFilters,T||S?void 0:m);if(S){const K=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:W,splitCursor:K?je(K,v):null}}const F=W.length>m,k=F?W.slice(0,m):W,j=k.at(-1);return{continueCursor:F&&j?je(j,v):null,isDone:!F,page:k}};class Zn extends E{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),mt=(o,i,t)=>{if(!o.tables[i])throw new E("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const m=i.tables[t];if(!m)throw new E("INTERNAL",`unknown table: ${t}`);const v=de(m.softDeleteMode,void 0),S=v?te(v,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let _=0;const R=y=>{const{search:I}=$;if(!I)throw new E("INTERNAL","runSearchFetch called without a staged search");Jt(o,t,m);const b=$.inMemoryFilters.length>0,L=Dn(b?void 0:y),J=Yt(o)?qn(o,t,I,L,S):Un(o,t,I,L,S);return b?(_=J.length,bt(J,$.inMemoryFilters,y,ne=>ne.document)):(y===void 0&&vn(J),J)},T=y=>R(y).map(I=>I.document),x=y=>{const I=Mn(y);return bn(T(In(I)),I)},W=()=>{const y=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return r.join(y.map(b=>r`${V(b)} ${r.raw(I)}`),r`, `)},F=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(fn(t,$.indexName,$.indexFields,$.sqlConditions,ie))},k=y=>{F();let I=0;const b=(()=>{if($.search){const L=T(y);return I=_,L}return $.geo?Kn(o,t,$,S,y,L=>{I=L}):On(o,t,$,S,W(),y,L=>{I=L})})();return p(Math.max(I,b.length)),b},j=()=>{if(!$.search&&!$.geo)throw new E("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let y=0;const I=(()=>{if($.search){const b=R(void 0);return y=_,b}return Dt(o,t,$,S,void 0,b=>{y=b})})();return p(Math.max(y,I.length)),I},K={async*[Symbol.asyncIterator](){const y=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const b=await K.paginate({cursor:I??null,numItems:Fn});for(const L of b.page)y.every(J=>J(L))&&(yield L);if(b.isDone||b.continueCursor===null)return;I=b.continueCursor}}finally{$.inMemoryFilters=y}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(y){return $.inMemoryFilters.push(y),K},async first(){return k($.inMemoryFilters.length>0?void 0:1)[0]??null},order(y){return $.order=y==="desc"?"desc":"asc",K},async paginate(y){let I=0;if(F(),$.search){const L=x(y);return p(L.page.length),L}if($.geo)throw new E("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Xn(o,t,$,y,S,L=>{I=L});return p(Math.max(I,b.page.length)),b},async take(y){return k(y)},async unique(){const y=k($.inMemoryFilters.length>0?void 0:2);if(y.length>1)throw new Zn(`unique() on table "${t}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const b=(m.geoIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown geo index "${y}" on table "${t}"`);a(t,y,"geo");const L={definition:b,indexName:y};if($.geo=L,I(Pn(L,t)),!L.near&&!L.within)throw new E("INTERNAL",`geo index "${y}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,I){const b=m.indexes.find(L=>L.name===y);if(!b)throw new E("INTERNAL",`unknown index "${y}" on table "${t}"`);return a(t,y,"index"),$.indexName=y,$.indexFields=b.fields,I&&I(Wn($)),K},withSearchIndex(y,I){const b=(m.searchIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown search index "${y}" on table "${t}"`);a(t,y,"search");const L={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:y,query:""};if($.search=L,I(An(L,t,Oe(b.language))),!L.hasQuery)throw new E("INTERNAL",`search index "${y}" on table "${t}" requires a .search(field, query) call`);return K}};return K},St=(o,i,t)=>{const a={...i};for(const[f,p]of At(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[p,m]of At(o)){if(m.serverDefault){p in i&&(f[p]=m.serverDefault({auth:a}));continue}m.onUpdateFn&&!(p in i)&&(f[p]=m.onUpdateFn())}},Rt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new E("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),Ke=(o,i,t)=>{try{q(o,t)}catch(a){throw or(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},xe=(o,i,t)=>{if(Ke(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,a,f,p,m)=>{const v=[];for(let R=0;R<t.length+1;R+=1){const T=[];for(let k=0;k<R;k+=1)T.push(r`${r.identifier(t[k])} IS ${p[k]}`);const x=t[R],W=a[R];if(x!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";T.push(r`${r.identifier(x)} ${r.raw(k)} ${p[R]}`)}else T.push(r`${r.identifier(ln)} < ${m}`);const[F]=T;v.push(T.length===1&&F!==void 0?F:r`(${r.join(T,r` AND `)})`)}const S=r.join(v,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),_=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:_.c}},Lr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{}),f=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...un(s,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let m=!1;const v=async e=>{const n=m;m=!0;try{return await e()}finally{m=n}},S=o.onRead??(()=>{}),$=o.onReadRange??(e=>{S(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!m&&p?.recordRead(1),S(e,n)},R=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),x=e=>{m||p?.recordWrite(e)},W=async e=>{x(e.doc),await T(e)},{cache:F}=o,k=o.clock??(()=>Date.now()),j=o.idGenerator??(()=>crypto.randomUUID()),K=o.scheduler??jt,{globalDb:y}=o,I=o.auth??{identity:null,userId:null},b=o.cdc??!1,L=K,J=$n({scheduler:typeof L.list=="function"&&typeof L.get=="function"?L:void 0,storage:o.storage}),ne=(e,n,s,u)=>{b&&Vt(i,k(),e,n,s,u)},se=e=>t.tables[e]?.shardMode?.kind==="global",ze=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}return U},Me=e=>ze(e,"cascade"),Q=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}},Je=async(e,n,s,u,h)=>{h&&x(s);const d=await e.insert(n,s,u);return a({key:d,op:"insert",row:{...s,_id:d},table:n}),d},be=(e,n)=>ze(e,"relation load").findMany(e,n),Ve=(e,n)=>(se(e)&&_(e,H),be(e,n)),Ft=e=>!se(e.table),Ye=o.relationExistsPushDown??"auto",Xe=Ye!=="never",{maxRelationKeys:Ze}=o,ge=(e,n,s)=>ut(e,{fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:s,schema:t,tableName:n}),et=async(e,n,s,u)=>{const h=Q(e,"relation grouped count");if(h)return _(e,H),wn((B,A)=>h.count(B,A),e,n,s,u);const d=t.tables[e];if(!d)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const c=de(d.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,u),c),C=await ge(w,e,void 0),g=te(C,oe),M=V(n);let D=r`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${M}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))tt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>tt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>gt)throw $e-=1,new pe(`trigger recursion exceeded ${String(gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Bt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:De,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:nt,syncGeo:Ee,syncRanks:he,syncSearch:me}=Pt({broadcast:a,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,s)=>F?.invalidate(e,n,f(e,s)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=ot(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(g)} WHERE id = ${e}`),[d]=q(i,r`${He(h)} LIMIT 1`).toArray();if(!d)continue;const c=d.__t__,l=le(d);if(typeof c!="string"||!l)return;const w=d[N];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},Wt=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ot(n);for(let d=0;d<h.length;d+=we){const c=h.slice(d,d+we),l=Math.floor(we/c.length),w=Zt(r`${r.identifier("id")}`,s,!1,l),C=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,He(C))){const{id:M,__t__:D}=g;typeof D=="string"&&typeof M=="string"&&u.set(M,D)}}return u},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:_,rowToDocument:le,schema:t,sql:i},U={system:J,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new E("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=de(u.softDeleteMode,void 0),d=z(z(n.baseWhere,n.where),h),c=await ge(d,e,n.relationBaseWhere),l=c!==d;if(u.aggregateIndexes&&!n.baseWhere&&!l&&(!h||yt(u,[n.field]))){const B=zt(u.aggregateIndexes,n.op,n.field,n.where);if(B){De(e,B.index);const A=Fe(B.index.by??[],B.key),O=Le(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(O)} WHERE ${Ce} = ${A}`).toArray()[0];return We(n.op,Y)}}Et(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,oe),C=ve(n.op),g=V(n.field);let M=r`SELECT ${r.raw(C)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(M=r`${M} WHERE ${w}`);const P=q(i,M).toArray()[0]?.value;return P??null},asId(e,n){const s=mt(t,e,n);if(s===null)throw new E("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=Kt(n);if(h.restrictsCounts)throw new Be(e);_(e,H);const d=de(u.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),d),l=await ge(c,e,h.relationBaseWhere),w=l!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!d){const D=Qt(u.aggregateIndexes,h.where);if(D){De(e,D.index);const P=Fe(D.index.by??[],D.key),B=Le(e,D.index.name),A=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const C=te(l,oe);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return C&&(g=r`${g} WHERE ${C}`),q(i,g).one().count},async delete(e,n,s){const u=re(e,n);if(!u){const g=n===void 0?y:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c],w=s?.hard===!0,C=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(C&&d[C]!==null&&d[C]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:d,table:c}),await hn({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,M,D)=>(await Me(g).findMany(g,{includeDeleted:w,where:{[M]:D}})).page,onCascade:(g,M)=>Me(g).delete(M,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,M,D)=>Me(g).patch(M,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),C){const g={...d,[C]:k(),_id:e};xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,g,d),Ee(c,e,void 0),ye(c,d,g),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d,g)),ne(c,e,"update",g),a({indexKeys:f(c,d,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c});return}xe(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,d,void 0),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d)),ne(c,e,"delete"),a({indexKeys:f(c,d),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new E("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??xt),u=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let d=0;return await v(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,u),d+=1;if(l.length<s)break}}),{deleted:d}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const d=(await(Q(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(d.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(d,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const d=sn(n.orderBy),c=n.cursor?Ct(d,Ne(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(u.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Ft:void 0,existsPushMode:Ye==="always"?"always":"auto",fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=Xe?Qn(_):oe,C=te(l,w);let g=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(e)}`;C&&(g=r`${g} WHERE ${C}`),g=r`${g} ORDER BY ${Lt(d)}`;const M=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;M!==void 0&&(g=r`${g} LIMIT ${r.raw(String(M+1))}`);const D=q(i,g).toArray();h&&!m&&p?.recordRead(D.length);const P=[];for(const Y of D){const G=le(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(M===void 0)return n.with&&await ft({groupedCounter:et,fetcher:be,parents:P,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:at(P,n.select,n.with)};const B=P.length>M,A=B?P.slice(0,M):P,O=A.at(-1);return n.with&&await ft({fetcher:be,groupedCounter:et,parents:A,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&O?je(O,d):null,isDone:!B,page:at(A,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const u=n===void 0?y:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const d=de(u.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),d),l=await ge(c,e,n.relationBaseWhere),w=l!==c,C=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!d||yt(u,C))){const A=Ot(u.aggregateIndexes,h.op,h.field,n.by,n.where),O=A===void 0?0:Object.keys(A.partial).length,Y=A?.index.by?.length??0;if(A&&(O===0||O===Y)){De(e,A.index);const G=Le(e,A.index.name),Se=Object.keys(A.partial),_e=[];if(Se.length===(A.index.by??[]).length&&Se.length>0){const Re=Fe(A.index.by??[],A.partial),Te=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...A.partial},value:We(h.op,Te[0])}),_e}const qt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of qt){const Te=Nt(JSON.parse(Re.key));_e.push({key:Te,value:We(h.op,Re)})}return _e}}for(const A of C){if(A===void 0)continue;const O=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Et(u,A,O)}const g=te(l,oe),M=n.by.map(A=>r`${V(A)} AS ${r.identifier(A)}`);if(h.op==="count")M.push(r`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(r`${r.raw(ve(h.op))}(${V(A)}) AS value`)}let D=r`SELECT ${r.join(M,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(A=>V(A)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const A of P){const O={};for(const G of n.by)O[G]=A[G]??null;const{value:Y}=A;B.push({key:O,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=Q(e,"insert");if(u)return Je(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=St(h,n,I);Pe(h,d);let c;s?.clientId!==void 0?(Ln(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof d._id=="string"?c=d._id:c=j();const l=s?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:k(),w={...d,_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES (${c}, ${l}, ${ce(w)})`),nt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await W({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const l of n)x(l);for(const l of n){const w=await u.insert(e,l,{allowExplicitId:s?.allowExplicitId});a({key:w,op:"insert",row:{...l,_id:w},table:e}),c.push(w)}return c}const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const d=n.map(c=>{const l=St(h,c,I),w=s?.allowExplicitId===!0&&typeof l._id=="string"?l._id:j(),C=s?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:k();return{creationTime:C,document:{...l,_creationTime:C,_id:w},id:w}});for(const c of d)x(c.document);for(let c=0;c<d.length;c+=$t){const l=r.join(d.slice(c,c+$t).map(w=>r`(${w.id}, ${w.creationTime}, ${ce(w.document)})`),r`, `);Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES ${l}`)}for(const{document:c,id:l}of d)nt(e,l,c),await T({doc:c,id:l,op:"insert",table:e});return d.map(c=>c.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],d=Q(e,"insert");if(d)for(const l of n)x(l);const c=async l=>d?Je(d,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return mt(t,e,n)},async patch(e,n,s){const u=re(e,s);if(!u){const C=s===void 0?y:void 0;if(C){x(n),await C.patch(e,n);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c];if(!l)throw new E("INTERNAL",`unknown table: ${c}`);_(c,e),Rt("patch",n);const w={...d,...n,_id:e};_t(l,n,w,I),Pe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:d,table:c}),ue(c),fe(c),xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(w)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,w,d),Ee(c,e,w),ye(c,d,w),he(c,e,d,w),F?.invalidate(c,e,f(c,d,w)),ne(c,e,"update",w),a({indexKeys:f(c,d,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:d,table:c}),await W({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const d=(await(Q(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(d.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(d,s),{patched:d.length}},query(e){const n=Q(e,"query");return n?(_(e,H),n.query(e)):nr(i,t,e,R,s=>{s?$(s):_(e,H)},s=>{m||p?.recordRead(s)})},async rank(e,n,s){const u=Q(e,"rank");if(u)return _(e,H),u.rank(e,n,s);R(e,n,"rank");const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=h.rankIndexes?.find(G=>G.name===n);if(!d)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,d),s.restrictsCounts)throw new Be(e);_(e,H),ke(e,d);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=dt(e,d.name),w=d.sortBy.map((G,Se)=>lt(Se)),C=w.map(G=>En(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(C)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let D=M.__partition__;const P=z(s.baseWhere,s.where);Ue(P,t,e,"rank");const B=an(d,P);if(B){const G=dn(d.partitionBy??[],B);if(G!==D)return null;D=G}const A=w.map(G=>M[G]),{before:O,total:Y}=Tt(i,l,w,d.sortBy,D,A,c);return{position:O+1,total:Y}},async rankBefore(e,n,s){if(se(e))throw new E("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Be(e);_(e,H),ke(e,h);const d=dt(e,h.name),c=h.sortBy.map((w,C)=>lt(C)),l=h.sortBy.map((w,C)=>ie(s.sortValues[C]??null));return Tt(i,d,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);R(e,n,"rank");const{continueCursor:h,hasMore:d,rows:c}=st(it,e,n,s);return{continueCursor:h,isDone:!d,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage"),R(e,n,"rank");const{directions:u,hasMore:h,rows:d}=st(it,e,n,s);return{directions:u,hasMore:h,rows:d}},async restore(e,n){const s=re(e,n);if(!s){const d=n===void 0?y:void 0;if(d?.restore){await d.restore(e);return}throw new E("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new E("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=re(e,s);if(!h){const M=s===void 0?y:void 0;if(M){x(n),await M.replace(e,n,void 0,u);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new E("INTERNAL",`unknown table: ${l}`);Rt("replace",n);const C=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:k(),g={...n,_creationTime:C,_id:e};_t(w,n,g,I),Pe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),ue(l),fe(l),xe(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${C}, ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${d}`),me(l,e,g,c),Ee(l,e,g),ye(l,c,g),he(l,e,c,g),F?.invalidate(l,e,f(l,c,g)),ne(l,e,"update",g),a({indexKeys:f(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await W({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new E("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let d=0;const{deleteAll:c}=U;if(c===void 0)throw new E("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,d+=w.deleted}return{deleted:d,tables:h}}},Bt={db:U,scheduler:K};return o.enforceRls===!0?pn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Wt(e,n)):U};export{Gr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Zn as NotUniqueError,go as SEARCH_STATE_TABLE,Yr as advanceClientWatermark,Hr as applyCdcChanges,Ln as assertValidClientId,Br as backfillAggregateIndexes,qr as backfillRankIndexes,Ur as backfillSearchIndexes,Nr as bumpCdcEpoch,Lr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,jr as minCdcSeq,mt as normalizeIdStructurally,Kr as readCdcChanges,Or as readCdcCursor,Qr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,lo as readIdempotent,wo as runShardMigrations,yo as selectShapeMemberIds,Eo as selectShapeRows,zr as trimCdcChanges,uo as trimIdempotent,so as writeGlobalShapeSnapshot,fo as writeIdempotent};