@lunora/shard-engine 1.0.0-alpha.37 → 1.0.0-alpha.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +97 -7
- package/dist/index.d.ts +97 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-DZ5yKTXx.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-VfPoURHu.mjs +15 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs +1 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-C4DEsHec.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs +7 -0
- package/dist/packem_shared/ShapeDiffCache-mE7ZzdPr.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-CeaR5jj8.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DDgDYJcc.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BhYUbqzO.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-umdBNFzJ.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-DZZxDW5c.mjs +7 -0
- package/dist/packem_shared/ctx-db-relay-shapes-Jf5xpD1r.mjs +17 -0
- package/dist/packem_shared/{defineEngineContractSuite-iK4MwBOl.mjs → defineEngineContractSuite-C6NKOjJn.mjs} +1 -1
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-DR79pnU-.mjs → isSoftDeleted-CZirzdQL.mjs} +1 -1
- package/dist/packem_shared/materializeExternalRows-DYE0rlxi.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-C6JwX3Ie.mjs +5 -0
- package/dist/packem_shared/selectShapeMembers-GfRzwoVo.mjs +1 -0
- package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-2mZJ-FQW.mjs +0 -1
- package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +0 -8
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-THUZXy3C.mjs +0 -1
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +0 -7
- package/dist/packem_shared/awaitWsDrain-Cs-1HHP6.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +0 -7
- package/dist/packem_shared/materializeExternalRows-D5tgL1mR.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DtIbA812.mjs +0 -5
- package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +0 -1
- package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +0 -1
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 c,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as E,foldAggregateTally as A,readAggregateValue as R}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as h,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 y,appendAuditEntry as N,ensureAuditTable as O,readAuditLog as D}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-THUZXy3C.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,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 Q,migrateCdcLog as j,migrateCdcMeta as Y,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{COMMIT_SEQ_FIELD as le,COMMIT_SEQ_TABLE as me,allocateCommitSeq as pe,migrateCommitSeq as ce,readCommitSeq as de}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ue}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as fe,deleteGlobalShapeSnapshot as Te,deleteGlobalShapeSnapshotsForConnection as Ee,migrateGlobalShapeSnapshot as Ae,readGlobalShapeSnapshot as Re,writeGlobalShapeSnapshot as ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ce,migrateIdempotency as _e,readIdempotent as Ie,trimIdempotent as Le,writeIdempotent as be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as ye,isMemoryTable as Ne,memoryTableNames as Oe}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as Fe,hydrateDocsById as Pe}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Be,migrateSearchState as Ge,readSearchBackfillState as Ue,writeSearchBackfillState as qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ke,deleteShapePokeCursor as We,deleteShapePokeCursorsForConnection as ve,migrateShapePokeCursor as ze,readShapePokeCursor as He,writeShapePokeCursor as Xe}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Qe,selectShapeRows as je}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as Je,readMigrationStatus as Ze,runDataMigration as $e}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as rr,createDependencyTracker as or,depKey as ar,tableFromDepKey as tr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as sr,runSql as ir}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as mr,a as pr,b as cr,D as dr,c as Sr,d as ur,g as xr,i as fr,j as Tr,e as Er,q as Ar,f as Rr,r as gr,t as hr,h as Cr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as Ir,renderSql as Lr,sqliteInList as br,unionAll as Mr}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Nr,claimStreamRun as Or,deleteStreamRun as Dr,finishStreamRun as Fr,migrateDurableStreams as Pr,readStreamChunks as kr,readStreamRun as Br,trimStreamRuns as Gr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as qr,MAX_DURABLE_STREAM_BYTES as wr,MAX_DURABLE_STREAM_CHUNKS as Kr,decideDurableAttach as Wr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{diffExternalSource as zr}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as Xr,normalizeSourceDocument as Vr,normalizeSourceValue as Qr}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Yr,materializeExternalRowsIncremental as Jr,readExternalSourceBaseline as Zr,runExternalSourceTick as $r}from"./packem_shared/materializeExternalRows-D5tgL1mR.mjs";import{isSoftDeleted as ro,isSourceDue as oo,pullExternalSourceIncrementalTick as ao,pullExternalSourceTick as to}from"./packem_shared/isSoftDeleted-DR79pnU-.mjs";import{GEO_DEFAULT_PRECISION as so,boundingBoxCenter as io,boundingBoxGeohashes as lo,coveringGeohashes as mo,encodeGeohash as po,haversineMeters as co,pointInBoundingBox as So}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as xo,ADMIN_FUNCTION_PREFIX as fo,DEFAULT_FANOUT_TOPIC_LIMIT as To,FLAGS_FUNCTION_PREFIX as Eo,MAX_PAGE_SIZE as Ao,RELATION_FUNCTION_PREFIX as Ro,createFanoutCounters as go,facetColumn as ho,findStorageReferences as Co,listTables as _o,readTablePage as Io,recordFanoutPass as Lo,selectMatchingIds as bo,summarizeFanoutTopics as Mo,summarizeSubscriptions as yo}from"./packem_shared/ADMIN_FUNCTIONS-2mZJ-FQW.mjs";import{MAIL_RETENTION as Oo,MAIL_TABLE as Do,clearCapturedMail as Fo,ensureMailTable as Po,readCapturedMail as ko,recordCapturedMail as Bo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Uo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as wo,readBookmark as Ko}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as vo,buildSeekBeforeWhere as zo,buildSeekWhere as Ho,decodeCursor as Xo,encodeCursor as Vo,normalizeOrderKeys as Qo,softDeleteScope as jo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as Jo,clearQueueMessages as Zo,isLossyBody as $o,readQueueMessageById as ea,readQueueMessages as ra,recordQueueMessages as oa}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ta,encodePartitionKey as na,matchesRankStaticWhere as sa,rankKeyFromDoc as ia,rankTableName as la,resolveRankPartition as ma,sortColumnName as pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as da,reactiveCacheKey as Sa}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as xa,listReactorStates as fa,migrateReactorState as Ta,reactorNeedsRun as Ea,readReactorState as Aa,writeReactorState as Ra}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{createReadFootprint as ha}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as _a,indexKeysForRow as Ia,keysTouchRanges as La}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ma,assertFlatPredicate as ya,assertShapeShardable as Na,containsRelationPredicate as Oa,isRelationPredicate as Da,resolveRelationPredicates as Fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ka,distinctValues as Ba,fanOutScalarCounts as Ga,relationHooks as Ua,resolveWith as qa,runRowValidators as wa}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Wa,clampPromotionThresholds as va,nextPromotionState as za,relayCountFor as Ha,shapeRoutingKey as Xa}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as Qa,OwnerRelay as ja,RelayMember as Ya,createRelayLink as Ja}from"./packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{createReplicaLink as $a,gateReplicaDispatch as et,handleReplicaControl as rt}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as at,countLegacyRows as tt,reprojectableFields as nt,reprojectionTables as st}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as lt,RlsRequiredError as mt,guardWriter as pt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as dt,readSchemaHistory as St,readSchemaVersion as ut,recordSchemaVersion as xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Tt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as At,isDevEnvironment as Rt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as ht,diffGlobalMembership as Ct,encodeRowsPatch as _t,projectColumns as It}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as bt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as yt}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ot,assertReadonly as Dt,lintReadonlySql as Ft,runReadonlySql as Pt}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Bt,subscriptionFrames as Gt,subscriptionListDeltas as Ut,trySendFrame as qt}from"./packem_shared/awaitWsDrain-Cs-1HHP6.mjs";import{mergeChangedKeys as Kt,recordChangedKeys as Wt,writeTouchesMemo as vt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Ht}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Vt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as jt,TransactionHeadroomTracker as Yt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Zt,runTriggers as $t}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as rn}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as an,literalInList as tn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as sn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as mn,reprojectionMigrationId as pn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as dn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as un}from"./packem_shared/runShardMigrations-DtIbA812.mjs";import{stableStringify as fn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as En}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{xo as ADMIN_FUNCTIONS,fo as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,mr as AGG_COUNT,pr as AGG_KEY,cr as AGG_VALUE,y as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,le as COMMIT_SEQ_FIELD,me as COMMIT_SEQ_TABLE,Vt as ConflictError,h as CountRlsUnsupportedError,Je as DATA_MIGRATION_STATE_TABLE,To as DEFAULT_FANOUT_TOPIC_LIMIT,Ma as DEFAULT_MAX_RELATION_KEYS,Qa as DEFAULT_MAX_RELAYS,Wa as DEFAULT_PROMOTION_THRESHOLDS,jt as DEFAULT_TRANSACTION_LIMITS,dr as DOC_COLUMN,qr as DurableStreamRunner,Eo as FLAGS_FUNCTION_PREFIX,so as GEO_DEFAULT_PRECISION,fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ce as IDEMPOTENCY_TABLE,Oo as MAIL_RETENTION,Do as MAIL_TABLE,wr as MAX_DURABLE_STREAM_BYTES,Kr as MAX_DURABLE_STREAM_CHUNKS,Ao as MAX_PAGE_SIZE,Ot as MAX_SQL_ROWS,Uo as NotFoundError,P as NotUniqueError,ja as OwnerRelay,Jo as QUEUE_TABLE,ta as RANK_TIEBREAK,xa as REACTOR_STATE_TABLE,sn as RELATION_EXISTS_KEY,Ro as RELATION_FUNCTION_PREFIX,mn as REPROJECTION_MIGRATION_PREFIX,lt as RLS_UNWRAP_SYMBOL,da as ReactiveCache,Ya as RelayMember,mt as RlsRequiredError,rr as SCAN_DEP,dt as SCHEMA_HISTORY_MAX_VERSIONS,Be as SEARCH_STATE_TABLE,Ke as SHAPE_POKE_CURSOR_TABLE,bt as ShardRunner,Yt as TransactionHeadroomTracker,te as advanceClientWatermark,Sr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,pe as allocateCommitSeq,N as appendAuditEntry,X as appendCdcChange,Nr as appendStreamChunk,V as applyCdcChanges,ka as applyOnDelete,vo as applySelect,wo as armRestore,ya as assertFlatPredicate,Dt as assertReadonly,Na as assertShapeShardable,k as assertValidClientId,Bt as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,io as boundingBoxCenter,lo as boundingBoxGeohashes,_a as buildIndexRange,ht as buildPokeFrames,at as buildReprojectionMigration,zo as buildSeekBeforeWhere,Ho as buildSeekWhere,At as buildSettings,Q as bumpCdcEpoch,Or as claimStreamRun,va as clampPromotionThresholds,Fo as clearCapturedMail,ye as clearMemoryTables,Zo as clearQueueMessages,T as coerceAggregateNumber,an as compileWhereSql,Fe as computeRankPage,Oa as containsRelationPredicate,tt as countLegacyRows,mo as coveringGeohashes,ue as createCompanionSync,or as createDependencyTracker,go as createFanoutCounters,ur as createIndexSql,ha as createReadFootprint,Ja as createRelayLink,$a as createReplicaLink,B as createShardCtxDb,Ht as createSystemReader,Wr as decideDurableAttach,Xo as decodeCursor,Te as deleteGlobalShapeSnapshot,Ee as deleteGlobalShapeSnapshotsForConnection,We as deleteShapePokeCursor,ve as deleteShapePokeCursorsForConnection,Dr as deleteStreamRun,ar as depKey,zr as diffExternalSource,Ct as diffGlobalMembership,Ba as distinctValues,E as encodeAggregateKey,Vo as encodeCursor,po as encodeGeohash,na as encodePartitionKey,_t as encodeRowsPatch,O as ensureAuditTable,Po as ensureMailTable,o as exportShardRows,a as exportShardTable,ho as facetColumn,Ga as fanOutScalarCounts,Co as findStorageReferences,Fr as finishStreamRun,A as foldAggregateTally,et as gateReplicaDispatch,xr as geoTableName,pt as guardWriter,rt as handleReplicaControl,Zt as hasTrigger,co as haversineMeters,Pe as hydrateDocsById,t as importShardRows,Ia as indexKeysForRow,Rt as isDevEnvironment,fr as isFtsAvailable,$o as isLossyBody,Ne as isMemoryTable,Da as isRelationPredicate,ro as isSoftDeleted,oo as isSourceDue,Tr as jsonPath,Er as jsonPathSql,La as keysTouchRanges,Xr as liftSourceId,Ft as lintReadonlySql,fa as listReactorStates,_o as listTables,tn as literalInList,sa as matchesRankStaticWhere,d as matchesStaticWhere,Yr as materializeExternalRows,Jr as materializeExternalRowsIncremental,Oe as memoryTableNames,Kt as mergeChangedKeys,C as mergeWhere,j as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,ce as migrateCommitSeq,Pr as migrateDurableStreams,Ae as migrateGlobalShapeSnapshot,_e as migrateIdempotency,Ta as migrateReactorState,Ge as migrateSearchState,ze as migrateShapePokeCursor,J as minCdcSeq,za as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Qo as normalizeOrderKeys,Vr as normalizeSourceDocument,Qr as normalizeSourceValue,Ir as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,So as pointInBoundingBox,It as projectColumns,ao as pullExternalSourceIncrementalTick,to as pullExternalSourceTick,Ar as qualifiedJsonPath,Rr as qualifiedJsonPathSql,dn as quoteIdentifier,ia as rankKeyFromDoc,la as rankTableName,Sa as reactiveCacheKey,Ea as reactorNeedsRun,R as readAggregateValue,D as readAuditLog,Ko as readBookmark,ko as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,de as readCommitSeq,Zr as readExternalSourceBaseline,Re as readGlobalShapeSnapshot,Ie as readIdempotent,Ze as readMigrationStatus,ea as readQueueMessageById,ra as readQueueMessages,Aa as readReactorState,St as readSchemaHistory,ut as readSchemaVersion,Ue as readSearchBackfillState,He as readShapePokeCursor,kr as readStreamChunks,Br as readStreamRun,Io as readTablePage,Bo as recordCapturedMail,Wt as recordChangedKeys,Lo as recordFanoutPass,oa as recordQueueMessages,xt as recordSchemaVersion,Ua as relationHooks,Ha as relayCountFor,Lr as renderSql,nt as reprojectableFields,pn as reprojectionMigrationId,st as reprojectionTables,ma as resolveRankPartition,Fa as resolveRelationPredicates,qa as resolveWith,gr as rowToDocument,$e as runDataMigration,sr as runDrizzle,$r as runExternalSourceTick,Pt as runReadonlySql,wa as runRowValidators,un as runShardMigrations,yt as runSocketPool,ir as runSql,$t as runTriggers,rn as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,bo as selectMatchingIds,Qe as selectShapeMemberIds,je as selectShapeRows,Tt as serializeSqlValue,Xa as shapeRoutingKey,jo as softDeleteScope,pa as sortColumnName,br as sqliteInList,fn as stableStringify,En as stableWireKey,Gt as subscriptionFrames,Ut as subscriptionListDeltas,Mo as summarizeFanoutTopics,yo as summarizeSubscriptions,hr as tableColumns,tr as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Le as trimIdempotent,Gr as trimStreamRuns,Cr as tryRowToDocument,qt as trySendFrame,Mr as unionAll,l as validateImportRow,ge as writeGlobalShapeSnapshot,be as writeIdempotent,Ra as writeReactorState,qe as writeSearchBackfillState,Xe as writeShapePokeCursor,vt as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C4DEsHec.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-DDgDYJcc.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-VfPoURHu.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as Te,COMMIT_SEQ_TABLE as he,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Me,readGlobalShapeSnapshot as Pe,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as Fe,trimIdempotent as ke,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{selectShapeMembers as tr,selectShapeRows as nr}from"./packem_shared/selectShapeMembers-GfRzwoVo.mjs";import{DATA_MIGRATION_STATE_TABLE as sr,readMigrationStatus as ir,runDataMigration as mr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as pr,createDependencyTracker as dr,depKey as Sr,tableFromDepKey as ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as xr,runSql as Tr}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as Er,a as Cr,b as Rr,D as Ar,c as gr,d as _r,g as Ir,i as br,j as Lr,e as Mr,q as Pr,f as Dr,r as yr,t as Nr,h as Or}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as kr,renderSql as Br,sqliteInList as Gr,unionAll as Ur}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as wr,claimStreamRun as Kr,deleteStreamRun as vr,finishStreamRun as Wr,migrateDurableStreams as Hr,readStreamChunks as Xr,readStreamRun as zr,trimStreamRuns as Vr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as jr,MAX_DURABLE_STREAM_BYTES as Yr,MAX_DURABLE_STREAM_CHUNKS as Jr,decideDurableAttach as Zr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{envOptionalPositiveInt as eo,envPositiveInt as ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as ao}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as no,normalizeSourceDocument as lo,normalizeSourceValue as so}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as mo,materializeExternalRowsIncremental as co,readExternalSourceBaseline as po,runExternalSourceTick as So}from"./packem_shared/materializeExternalRows-DYE0rlxi.mjs";import{isSoftDeleted as fo,isSourceDue as xo,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as ho}from"./packem_shared/isSoftDeleted-CZirzdQL.mjs";import{GEO_DEFAULT_PRECISION as Co,boundingBoxCenter as Ro,boundingBoxGeohashes as Ao,coveringGeohashes as go,encodeGeohash as _o,haversineMeters as Io,pointInBoundingBox as bo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Do,ADMIN_FUNCTION_PREFIX as yo,DEFAULT_FANOUT_TOPIC_LIMIT as No,FLAGS_FUNCTION_PREFIX as Oo,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as ko,createFanoutCounters as Bo,createGlobalPollCounters as Go,createShapeProbeCounters as Uo,facetColumn as qo,findStorageReferences as wo,listTables as Ko,readTablePage as vo,recordFanoutPass as Wo,recordGlobalPollPass as Ho,recordShapeProbePass as Xo,selectMatchingIds as zo,summarizeFanoutTopics as Vo,summarizeSubscriptions as Qo}from"./packem_shared/ADMIN_FUNCTIONS-DZ5yKTXx.mjs";import{MAIL_RETENTION as Yo,MAIL_TABLE as Jo,clearCapturedMail as Zo,ensureMailTable as $o,readCapturedMail as ea,recordCapturedMail as ra}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as na,readBookmark as la}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ia,buildSeekBeforeWhere as ma,buildSeekWhere as ca,decodeCursor as pa,encodeCursor as da,normalizeOrderKeys as Sa,softDeleteScope as ua}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as xa,clearQueueMessages as Ta,isLossyBody as ha,readQueueMessageById as Ea,readQueueMessages as Ca,recordQueueMessages as Ra}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ga,encodePartitionKey as _a,matchesRankStaticWhere as Ia,rankKeyFromDoc as ba,rankTableName as La,resolveRankPartition as Ma,sortColumnName as Pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as ya,reactiveCacheKey as Na}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as ka,migrateReactorState as Ba,reactorNeedsRun as Ga,readReactorState as Ua,writeReactorState as qa}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{UNVOUCHABLE_DEP as Ka,createReadFootprint as va,markUnvouchableReads as Wa}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Xa,indexKeysForRow as za,keysTouchRanges as Va}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as ja,assertFlatPredicate as Ya,assertShapeShardable as Ja,containsRelationPredicate as Za,isRelationPredicate as $a,resolveRelationPredicates as et}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ot,distinctValues as at,fanOutScalarCounts as tt,relationHooks as nt,resolveWith as lt,runRowValidators as st}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as mt,clampPromotionThresholds as ct,nextPromotionState as pt,relayCountFor as dt,shapeRoutingKey as St}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as ft,OwnerRelay as xt,RelayMember as Tt,createRelayLink as ht}from"./packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{createReplicaLink as Ct,gateReplicaDispatch as Rt,handleReplicaControl as At}from"./packem_shared/createReplicaLink-DZZxDW5c.mjs";import{buildReprojectionMigration as _t,countLegacyRows as It,reprojectableFields as bt,reprojectionTables as Lt}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Pt,RlsRequiredError as Dt,guardWriter as yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ot,readSchemaHistory as Ft,readSchemaVersion as kt,recordSchemaVersion as Bt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Ut}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as wt,isDevEnvironment as Kt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Wt}from"./packem_shared/buildShapeDiff-umdBNFzJ.mjs";import{ShapeDiffCache as Xt,createShapeDiffCache as zt,globalShapeReadKey as Vt}from"./packem_shared/ShapeDiffCache-mE7ZzdPr.mjs";import{buildPokeFrames as jt,diffGlobalMembership as Yt,encodeRowsPatch as Jt,projectColumns as Zt}from"./packem_shared/buildPokeFrames-BhYUbqzO.mjs";import{ShardRunner as en}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as on}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as tn,assertReadonly as nn,lintReadonlySql as ln,runReadonlySql as sn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as cn,subscriptionFrames as pn,subscriptionListDeltas as dn,trySendFrame as Sn}from"./packem_shared/awaitWsDrain-CeaR5jj8.mjs";import{mergeChangedKeys as fn,recordChangedKeys as xn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as gn,TransactionHeadroomTracker as _n}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as bn,runTriggers as Ln}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Pn}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as yn,literalInList as Nn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as qn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Kn}from"./packem_shared/runShardMigrations-C6JwX3Ie.mjs";import{stableStringify as Wn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{Do as ADMIN_FUNCTIONS,yo as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Er as AGG_COUNT,Cr as AGG_KEY,Rr as AGG_VALUE,P as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,Te as COMMIT_SEQ_FIELD,he as COMMIT_SEQ_TABLE,Rn as ConflictError,A as CountRlsUnsupportedError,sr as DATA_MIGRATION_STATE_TABLE,No as DEFAULT_FANOUT_TOPIC_LIMIT,ja as DEFAULT_MAX_RELATION_KEYS,ft as DEFAULT_MAX_RELAYS,mt as DEFAULT_PROMOTION_THRESHOLDS,gn as DEFAULT_TRANSACTION_LIMITS,Ar as DOC_COLUMN,jr as DurableStreamRunner,Oo as FLAGS_FUNCTION_PREFIX,Co as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Yo as MAIL_RETENTION,Jo as MAIL_TABLE,Yr as MAX_DURABLE_STREAM_BYTES,Jr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,tn as MAX_SQL_ROWS,aa as NotFoundError,F as NotUniqueError,xt as OwnerRelay,xa as QUEUE_TABLE,ga as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,ko as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Pt as RLS_UNWRAP_SYMBOL,ya as ReactiveCache,Tt as RelayMember,Dt as RlsRequiredError,pr as SCAN_DEP,Ot as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,Xt as ShapeDiffCache,en as ShardRunner,_n as TransactionHeadroomTracker,Ka as UNVOUCHABLE_DEP,Se as advanceClientWatermark,gr as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,wr as appendStreamChunk,Q as applyCdcChanges,ot as applyOnDelete,ia as applySelect,na as armRestore,Ya as assertFlatPredicate,nn as assertReadonly,Ja as assertShapeShardable,k as assertValidClientId,cn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ro as boundingBoxCenter,Ao as boundingBoxGeohashes,Xa as buildIndexRange,jt as buildPokeFrames,_t as buildReprojectionMigration,ma as buildSeekBeforeWhere,ca as buildSeekWhere,wt as buildSettings,Wt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Kr as claimStreamRun,ct as clampPromotionThresholds,Zo as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,yn as compileWhereSql,ve as computeRankPage,Za as containsRelationPredicate,It as countLegacyRows,go as coveringGeohashes,ge as createCompanionSync,dr as createDependencyTracker,Bo as createFanoutCounters,Go as createGlobalPollCounters,_r as createIndexSql,va as createReadFootprint,ht as createRelayLink,Ct as createReplicaLink,zt as createShapeDiffCache,Uo as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,re as cursorBelowRetainedFloor,Zr as decideDurableAttach,pa as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,vr as deleteStreamRun,Sr as depKey,ao as diffExternalSource,Yt as diffGlobalMembership,at as distinctValues,h as encodeAggregateKey,da as encodeCursor,_o as encodeGeohash,_a as encodePartitionKey,Jt as encodeRowsPatch,y as ensureAuditTable,$o as ensureMailTable,eo as envOptionalPositiveInt,ro as envPositiveInt,o as exportShardRows,a as exportShardTable,qo as facetColumn,tt as fanOutScalarCounts,wo as findStorageReferences,Wr as finishStreamRun,E as foldAggregateTally,Rt as gateReplicaDispatch,Ir as geoTableName,Vt as globalShapeReadKey,yt as guardWriter,At as handleReplicaControl,bn as hasTrigger,Io as haversineMeters,We as hydrateDocsById,t as importShardRows,za as indexKeysForRow,Kt as isDevEnvironment,br as isFtsAvailable,ha as isLossyBody,qe as isMemoryTable,$a as isRelationPredicate,fo as isSoftDeleted,xo as isSourceDue,Lr as jsonPath,Mr as jsonPathSql,Va as keysTouchRanges,no as liftSourceId,ln as lintReadonlySql,ka as listReactorStates,Ko as listTables,Nn as literalInList,Wa as markUnvouchableReads,Ia as matchesRankStaticWhere,d as matchesStaticWhere,mo as materializeExternalRows,co as materializeExternalRowsIncremental,we as memoryTableNames,fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Hr as migrateDurableStreams,Me as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ba as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,pt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Sa as normalizeOrderKeys,lo as normalizeSourceDocument,so as normalizeSourceValue,kr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,bo as pointInBoundingBox,Zt as projectColumns,To as pullExternalSourceIncrementalTick,ho as pullExternalSourceTick,Pr as qualifiedJsonPath,Dr as qualifiedJsonPathSql,qn as quoteIdentifier,ba as rankKeyFromDoc,La as rankTableName,Na as reactiveCacheKey,Ga as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,la as readBookmark,ea as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,po as readExternalSourceBaseline,Pe as readGlobalShapeSnapshot,Fe as readIdempotent,ir as readMigrationStatus,Ea as readQueueMessageById,Ca as readQueueMessages,Ua as readReactorState,Ft as readSchemaHistory,kt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,Xr as readStreamChunks,zr as readStreamRun,vo as readTablePage,ra as recordCapturedMail,xn as recordChangedKeys,Wo as recordFanoutPass,Ho as recordGlobalPollPass,Ra as recordQueueMessages,Bt as recordSchemaVersion,Xo as recordShapeProbePass,nt as relationHooks,dt as relayCountFor,Br as renderSql,bt as reprojectableFields,Gn as reprojectionMigrationId,Lt as reprojectionTables,Ma as resolveRankPartition,et as resolveRelationPredicates,lt as resolveWith,yr as rowToDocument,mr as runDataMigration,xr as runDrizzle,So as runExternalSourceTick,sn as runReadonlySql,st as runRowValidators,Kn as runShardMigrations,on as runSocketPool,Tr as runSql,Ln as runTriggers,Pn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,zo as selectMatchingIds,tr as selectShapeMembers,nr as selectShapeRows,Ut as serializeSqlValue,St as shapeRoutingKey,ua as softDeleteScope,Pa as sortColumnName,Gr as sqliteInList,Wn as stableStringify,Xn as stableWireKey,pn as subscriptionFrames,dn as subscriptionListDeltas,Vo as summarizeFanoutTopics,Qo as summarizeSubscriptions,Nr as tableColumns,ur as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,ke as trimIdempotent,Vr as trimStreamRuns,Or as tryRowToDocument,Sn as trySendFrame,Ur as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,qa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,Tn as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:x(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as m,l as A}from"./do-sql-Dk_DJxn4.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",q="__cdc_log_table_seq",_=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(q)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},w=(e,o,r,i,s,d)=>{const E=d===void 0?null:m(d);n(e,t`INSERT INTO ${t.identifier(c)} (ts, ${t.identifier("table")}, id, op, doc) VALUES (${o}, ${r}, ${i}, ${s}, ${E})`)},C=90,S=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,F=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=S(o.tables),E=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const f={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?f:{...f,doc:A(a.doc)}});return{changes:E,cursor:E.at(-1)?.seq??r}},b=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=C){const d=new Set(i.slice(s,s+C));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${S(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),y=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},g=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq FROM ${t.identifier(c)}
|
|
9
|
+
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
|
+
GROUP BY id
|
|
11
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>({id:d.id,op:d.op,seq:d.maxSeq})),U=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
|
|
12
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
|
+
)`)},X=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
|
|
14
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
+
)`)},B=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},H=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},v=(e,o)=>e!==void 0&&e>o+1,x=(e,o,r)=>new u("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,W=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},Y=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},G=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},I=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof p))throw i;const s={...r};delete s._id,await e.replace(o.id,s,void 0,{allowExplicitId:!0})}},K=async(e,o)=>{for(const r of o)await I(e,r)};export{c as CDC_LOG_TABLE,q as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,w as appendCdcChange,K as applyCdcChanges,G as bumpCdcEpoch,y as cdcCanVouchFor,B as cdcSeqLeavingRows,b as cdcTouchesTables,x as cdcTrimmedError,X as compactCdcDocs,v as cursorBelowRetainedFloor,_ as migrateCdcLog,L as migrateCdcMeta,W as minCdcReplayableSeq,$ as minCdcSeq,g as readCdcChangeKeys,F as readCdcChanges,H as readCdcCursor,Y as readCdcEpoch,U as trimCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-BU9T2xJ7.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-BhYUbqzO.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CeaR5jj8.mjs";import{stableWireKey as f}from"./stableWireKey-DSCJB6E7.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class n{changedTables;reads=new Map;resync=!1;skippedCount=0;constructor(e){this.changedTables=e}get readCount(){return this.reads.size}get resyncRequested(){return this.resync}get skipped(){return this.skippedCount}requestResync(){this.resync=!0}async rows(e,s){if(e===void 0)return s();const t=this.reads.get(e)??s();return this.reads.set(e,t),t}shouldRead(e){return this.changedTables===void 0||this.changedTables.has(e)?!0:(this.skippedCount+=1,!1)}}export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{s as Ht,c as Nt,j as Je,a as jt,y as Ae,h as Kt}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Ot}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Qt,aggregateSqlFunction as ve,normalizeCountArgument as zt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as qe,encodeAggregateKey as Be,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Jt,selectIndexForCount as Vt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Xt}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{backfillAggregateIndexes as Kr,backfillRankIndexes as Or,backfillSearchIndexes as Qr}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{appendCdcChange as Zt}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{CDC_LOG_TABLE as Jr,applyCdcChanges as Vr,bumpCdcEpoch as Yr,cdcCanVouchFor as Xr,cdcSeqLeavingRows as Zr,cdcTouchesTables as eo,cdcTrimmedError as to,compactCdcDocs as no,cursorBelowRetainedFloor as ro,minCdcReplayableSeq as oo,minCdcSeq as io,readCdcChangeKeys as so,readCdcChanges as co,readCdcCursor as ao,readCdcEpoch as lo,trimCdcChanges as uo}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{allocateCommitSeq as en,COMMIT_SEQ_FIELD as tn}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as nn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as B}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as rn,h as Ct,g as on}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as sn}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as cn,boundingBoxGeohashes as an,haversineMeters as dn,pointInBoundingBox as ln}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as un}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as fn,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as hn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as wn,encodePartitionKey as pn,RANK_TIEBREAK as gn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as $n,buildIndexRange as yn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as En,fanOutScalarCounts as mn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as Sn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as _n}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as ho,advanceClientWatermark as wo,migrateClientWatermark as po,readClientWatermark as go}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as yo,deleteGlobalShapeSnapshot as Eo,deleteGlobalShapeSnapshotsForConnection as mo,migrateGlobalShapeSnapshot as So,readGlobalShapeSnapshot as _o,writeGlobalShapeSnapshot as Ro}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ao,readIdempotent as vo,trimIdempotent as Io,writeIdempotent as Co}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as Mo}from"./runShardMigrations-C6JwX3Ie.mjs";import{SEARCH_STATE_TABLE as Do}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMembers as Lo,selectShapeRows as Fo}from"./selectShapeMembers-GfRzwoVo.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as An}from"./quoteIdentifier-CObIFRhb.mjs";const vn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},In=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Cn=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),xn=(o,i,t)=>{const a=Ht(o,t);if(a.length===0)return 0;let f=0;for(const[p,E]of i.entries()){const R=p===i.length-1;let S=0;for(const $ of a)(R?$.startsWith(E):$===E)&&(S+=1);if(S===0)return 0;f+=S}return f},Mn=(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)}},bn=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const R=Ve(p,t).length;if(R>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(R)})`);return E.field=f,E.query=p,E.hasQuery=!0,a}};return a},Dn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},kn=o=>Math.min(o.offset+o.numItems+1,X),Ln=o=>vn(`search:${String(o)}`),Fn=o=>{let i;try{i=In(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Wn=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Fn(o.cursor):0;if(t===void 0)throw Cn();if(t+i>=X)throw new y("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}},qn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Ln(t):null,isDone:!a,page:o.slice(i.offset,t)}},Bn=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 y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Un=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pn=o=>{if(!Un.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Gn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Hn=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},Nn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},jn=(o,i,t,a,f)=>{const p=Ve(t.query,Je(t.definition.language));if(p.length===0)return[];const E=jt(i,t.indexName),R=`${E}__vocab`,S=p.length-1,$=p.map((W,M)=>{const N=Mn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(R)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=p.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),T=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let _=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${T}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(_=r`${_} WHERE ${r.join(v,r` AND `)}`),_=r`${_} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of B(o,_)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},Kn=(o,i,t,a,f)=>{const p=Je(t.definition.language),E=Ve(t.query,p);if(E.length===0)return[];const R=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Nn(a)))}`;const $=B(o,S).toArray(),L=[];for(const T of $){const v=Ct(T);if(!v)continue;const _=xn(Kt(v,t.definition),E,p);_>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return L.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),L.slice(0,a).map(T=>({document:T.doc,score:T.score}))},je=(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 y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new y("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 y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("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 y("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},Qn=(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},zn=(o,i)=>{const t=Qn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=dn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return ln(t,i.within)?{creationTime:a,distance:0}:void 0},Jn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?cn(t.near.point,t.near.radiusMeters):an(t.within),p=on(i,t.indexName),E=f.map(T=>r`(g.${r.identifier("__geohash__")} >= ${T} AND g.${r.identifier("__geohash__")} < ${`${T}{`})`),R=[r`(${r.join(E,r` OR `)})`];a&&R.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(R,r` AND `)}`,$=B(o,S).toArray(),L=[];for(const T of $){const v=de(T),_=v?zn(v,t):void 0;v&&_&&L.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return L.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(E=>E(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},Vn=(o,i,t,a,f,p=()=>{})=>{const E=t.within!==void 0,R=Jn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return p(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},Lt=(o,i,t,a,f,p=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Vn(o,i,E,R?void 0:f,a,p);return R?kt(S,t.inMemoryFilters,f,$=>$.document):S},Yn=(o,i,t,a,f,p=()=>{})=>Lt(o,i,t,a,f,p).map(E=>E.document),Xn=(o,i,t,a,f,p,E=()=>{})=>{const R=[];for(const T of t.sqlConditions)R.push(r`${V(T.field)} ${r.raw(T.comparator)} ${oe(T.value)}`);a&&R.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,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 $=B(o,S).toArray();E($.length);const L=[];for(const T of $){const v=de(T);if(v&&t.inMemoryFilters.every(_=>_(v))&&(L.push(v),typeof p=="number"&&L.length>=p))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&_n(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("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`)},Zn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:E,parentTable:R,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??R;i+=1,o(S.table,H);const T=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,_=r`${lt($,v)} = ${lt(L,T)}`;t.push($);const F=te(p,a);t.pop();const W=F?r`${_} AND ${F}`:_,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=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`, `)},er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},tr=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},nr=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[er[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(hn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},rr=(o,i,t)=>{const a=[];for(const f of o){const p=de(f);if(p&&i.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},or=(o,i,t,a,f,p=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),R=tr(t),S=typeof a.endCursor=="string",$=te(nr(t,R,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let T=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(T=r`${T} WHERE ${L}`),T=r`${T} ORDER BY ${Wt(R)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(T=r`${T} LIMIT ${r.raw(String(E+1))}`);const _=B(o,T).toArray();p(_.length);const F=rr(_,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,R):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,R):null,isDone:!W,page:M}};class ir extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const sr=/\s/u,cr=String.fromCodePoint(0),_t=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||sr.test(t)||t.includes(cr)?null:t},ar=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const R=ae(E.softDeleteMode,void 0),S=R?te(R,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const T=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Xt(o,t,E);const k=$.inMemoryFilters.length>0,C=Bn(k?void 0:m),O=rn(o)?jn(o,t,b,C,S):Kn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&Dn(O),O)},v=m=>T(m).map(b=>b.document),_=m=>{const b=Wn(m);return qn(v(kn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(yn(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Yn(o,t,$,S,m,C=>{b=C}):Xn(o,t,$,S,F(),m,C=>{b=C})})();return p(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=T(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return p(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Gn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=_(m);return p(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=or(o,t,$,m,S,C=>{b=C});return p(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new ir(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(On(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Hn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(bn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Rt=(o,i,t)=>{const a={...i};for(const[f,p]of It(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},Tt=(o,i,t,a)=>{const f=t;for(const[p,E]of It(o)){if(E.serverDefault){p in i&&(f[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in i)&&(f[p]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dr=/unique constraint failed/i,lr=o=>o instanceof Error&&dr.test(o.message),ze=(o,i,t)=>{try{B(o,t)}catch(a){throw lr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),B(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")},vt=(o,i,t,a,f,p,E)=>{const R=[];for(let T=0;T<t.length+1;T+=1){const v=[];for(let M=0;M<T;M+=1)v.push(r`${r.identifier(t[M])} IS ${p[M]}`);const _=t[T],F=a[T];if(_!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(_)} ${r.raw(M)} ${p[T]}`)}else v.push(r`${r.identifier(gn)} < ${E}`);const[W]=v;R.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(R,r` OR `),$=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Hr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!p())&&(f=en(i)),{[tn]:f}),R=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...$n(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},T=o.onRead??(()=>{}),v=o.onReadRange??(e=>{T(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),T(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Qt,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,qt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!nn(t.tables[e])&&Zt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&_(e,H),Le(e,n)),Bt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return _(e,H),mn((q,I)=>h.count(q,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),g=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${x}`;const P=B(i,D).toArray();return new Map(P.map(q=>[q.__fk__,q.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Nt({broadcast:a,indexKeysFor:(e,n)=>R(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,R(e,s)),recordCdc:le,schema:t,sql:i}),st=(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})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(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(K)} FROM ${r.identifier(g)} WHERE id = ${e}`),[l]=B(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=sn(r`${r.identifier("id")}`,s,!1,d),A=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of B(i,Ke(A))){const{id:x,__t__:D}=g;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:_,rowToDocument:de,schema:t,sql:i},U={system:qt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("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 y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const q=Yt(u.aggregateIndexes,n.op,n.field,n.where);if(q){Fe(e,q.index);const I=Be(q.index.by??[],q.key),Q=qe(e,q.index.name),Y=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),g=V(n.field);let x=r`SELECT ${r.raw(A)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=B(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=_t(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=zt(n);if(h.restrictsCounts)throw new Pe(e);_(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Vt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=Be(D.index.by??[],D.key),q=qe(e,D.index.name),I=B(i,r`SELECT ${Ie} AS value FROM ${r.identifier(q)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(g=r`${g} WHERE ${A}`),B(i,g).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const g=n===void 0?C:void 0;g&&(M(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await En({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,x,D)=>(await ke(g).findMany(g,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(g,x)=>ke(g).delete(x,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,x,D)=>ke(g).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const g={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,g,l),Ee(c,e,void 0),ye(c,l,g),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l,g)),le(c,e,"update",g),a({indexKeys:R(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l)),le(c,e,"delete"),a({indexKeys:R(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(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 l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,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 un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=fn(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?Bt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Zn(_):re,A=te(d,w);let g=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(g=r`${g} WHERE ${A}`),g=r`${g} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(g=r`${g} LIMIT ${r.raw(String(x+1))}`);const D=B(i,g).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const q=P.length>x,I=q?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q?Qe(Q,l):null,isDone:!q,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ne(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=Jt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=qe(e,I.index.name),Se=Object.keys(I.partial),_e=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Re=Be(I.index.by??[],I.partial),Te=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...I.partial},value:Ue(h.op,Te[0])}),_e}const Gt=B(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of Gt){const Te=Ot(JSON.parse(Re.key));_e.push({key:Te,value:Ue(h.op,Re)})}return _e}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const g=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=B(i,D).toArray(),q=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;q.push({key:Q,value:Y==null?null:Number(Y)})}return q},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Rt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Pn(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Rt(h,d,O),g=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:g};return{creationTime:x,document:D,id:g}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return _t(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};Tt(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,R(c,l,w)),le(c,e,"update",w),a({indexKeys:R(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(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 l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(_(e,H),n.query(e)):ar(i,t,e,F,s=>{s?v(s):_(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return _(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);_(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>An(G)).join(", "),g=B(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=g;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const q=wn(l,P);if(q){const G=pn(l.partitionBy??[],q);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);_(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("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=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),g={...n,...E(d),_creationTime:A,_id:e};Tt(w,n,g,O),Ne(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,g,c),Ee(d,e,g),ye(d,c,g),he(d,e,c,g),j?.invalidate(d,e,R(d,c,g)),le(d,e,"update",g),a({indexKeys:R(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await N({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?Sn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{Jr as CDC_LOG_TABLE,ho as CLIENT_WATERMARK_TABLE,yo as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ao as IDEMPOTENCY_TABLE,ir as NotUniqueError,Do as SEARCH_STATE_TABLE,wo as advanceClientWatermark,Vr as applyCdcChanges,Pn as assertValidClientId,Kr as backfillAggregateIndexes,Or as backfillRankIndexes,Qr as backfillSearchIndexes,Yr as bumpCdcEpoch,Xr as cdcCanVouchFor,Zr as cdcSeqLeavingRows,eo as cdcTouchesTables,to as cdcTrimmedError,no as compactCdcDocs,Hr as createShardCtxDb,ro as cursorBelowRetainedFloor,Eo as deleteGlobalShapeSnapshot,mo as deleteGlobalShapeSnapshotsForConnection,po as migrateClientWatermark,So as migrateGlobalShapeSnapshot,oo as minCdcReplayableSeq,io as minCdcSeq,_t as normalizeIdStructurally,so as readCdcChangeKeys,co as readCdcChanges,ao as readCdcCursor,lo as readCdcEpoch,go as readClientWatermark,_o as readGlobalShapeSnapshot,vo as readIdempotent,Mo as runShardMigrations,Lo as selectShapeMembers,Fo as selectShapeRows,uo as trimCdcChanges,Io as trimIdempotent,Ro as writeGlobalShapeSnapshot,Co as writeIdempotent};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-it6rL9bR.mjs";const n="__shape_poke_cursor",u=r=>{i(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(n)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},d=(r,e,s)=>i(r,o`SELECT cursor FROM ${o.identifier(n)} WHERE connection_id = ${e} AND sub_id = ${s} LIMIT 1`).toArray()[0]?.cursor,T=(r,e,s,c)=>{i(r,o`INSERT INTO ${o.identifier(n)} (connection_id, sub_id, cursor) VALUES (${e}, ${s}, ${c})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=r=>i(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(n)}`).toArray()[0]?.cursor??void 0,S=(r,e,s)=>{i(r,o`DELETE FROM ${o.identifier(n)} WHERE connection_id = ${e} AND sub_id = ${s}`)},L=(r,e)=>{i(r,o`DELETE FROM ${o.identifier(n)} WHERE connection_id = ${e}`)};export{n as SHAPE_POKE_CURSOR_TABLE,S as deleteShapePokeCursor,L as deleteShapePokeCursorsForConnection,u as migrateShapePokeCursor,_ as minShapePokeCursor,d as readShapePokeCursor,T as writeShapePokeCursor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as o}from"./stableWireKey-DSCJB6E7.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=()=>{const n=new Set,t=new Map,s=new Set;return{onRead(e){n.add(e),s.add(e)},onReadRange(e){n.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of s)t.delete(e);return t.size>0?t:void 0},tables:n}},u="!unvouchable",i=(n,t,s)=>{if(!t)return n;const e=new Set(s);return new Proxy(n,{get(o,a,r){const c=Reflect.get(o,a,r);return typeof c!="function"||typeof a!="string"||!e.has(a)?c:(...l)=>(t(u),Reflect.apply(c,o,l))}})};export{u as UNVOUCHABLE_DEP,d as createReadFootprint,i as markUnvouchableReads};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as m}from"./stableStringify-G9OF5wcs.mjs";import{i as A,e as w}from"./wire-codec-BU9T2xJ7.mjs";const D="_id",p="_creationTime",y="page",J=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},_=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=J(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},F="__lunora__",L=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=L(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},E=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},R=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(w(i)),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},P=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},T=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(_(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=P(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?F:s,d=JSON.stringify(a),c=[...E(r,i,a,d),...R(r,i,a,d)];return T(r,i,c)?c:void 0},B=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},W=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{W as awaitWsDrain,K as subscriptionFrames,B as subscriptionListDeltas,C as trySendFrame};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as R,i as k,a as A,j as O,y as h,S as $,h as C}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as x,foldAggregateTally as N}from"./aggregateTableName-Cy5e03oz.mjs";import{migrateSearchState as _,readSearchBackfillState as F,writeSearchBackfillState as y}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{runDrizzle as l}from"./runDrizzle-it6rL9bR.mjs";import{i as E,r as T,a as D,b as v,A as B,D as S,h as G}from"./do-sql-Dk_DJxn4.mjs";import{isLiveForCompanion as U}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as P,matchesRankStaticWhere as W}from"./RANK_TIEBREAK-ci3MaM65.mjs";const j=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(n)}`).one().count>0,p=(e,n)=>l(e,t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)}`).toArray(),H=(e,n,r,o)=>{const i=M(n,r.name);if(b(e,i))return;const a=r.by??[],s=new Map,c=p(e,n);for(const d of c){const f=T(d);if(!f||!U(f,o)||r.where&&!L(f,r.where))continue;const g=x(a,f);N(s,g,r,f)}for(const[d,f]of s)l(e,t`INSERT INTO ${t.identifier(i)} (${D}, ${v}, ${B}) VALUES (${d}, ${f.value}, ${f.count})`)},ne=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const i of o.aggregateIndexes)H(e,r,i,o.softDeleteMode?.field)},V=(e,n,r)=>{const o=P(n,r.name);if(b(e,o))return;const i=R(r),a=p(e,n);for(const s of a){const c=T(s);!c||r.where&&!W(c,r.where)||k(e,o,r,i,c._id,c)}},re=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const i of o.rankIndexes)V(e,r,i)},m=500,w=(e,n,r)=>{const o=A(n,r.name),{profile:i}=O(r.language),a=j(F(e,o),i);if(a.finished)return{done:!0,rows:0};a.wipe&&l(e,t`DELETE FROM ${t.identifier(o)}`);const{cursor:s}=a,c=l(e,s===void 0?t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} WHERE id > ${s} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=s;for(const g of c){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(o)} WHERE ${t.identifier(h)} = ${u}`);const I=G(g);I&&l(e,t`INSERT INTO ${t.identifier(o)} (${t.identifier($)}, ${t.identifier(h)}) VALUES (${C(I,r)}, ${u})`)}const f=c.length<m;return y(e,o,d,f,i),{done:f,rows:c.length}},te=(e,n,r)=>{if(E(e))for(const o of r.searchIndexes??[])o.staged||w(e,n,o)},Y=(e,n,r,o)=>{let i=0;for(;;){if(i>=o)return{done:!1,pages:i};const a=w(e,n,r);if(a.rows>0&&(i+=1),a.done)return{done:!0,pages:i}}},ie=(e,n,r={})=>{if(!E(e))return{done:!0,pages:0};_(e);const o=r.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[a,s]of Object.entries(n.tables))if(!(s.shardMode?.kind==="global"||!s.searchIndexes))for(const c of s.searchIndexes){const d=Y(e,a,c,o-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ne as backfillAggregateIndexes,re as backfillRankIndexes,ie as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as h}from"./wire-codec-BU9T2xJ7.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-GfRzwoVo.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-mE7ZzdPr.mjs";import{projectColumns as g}from"./buildPokeFrames-BhYUbqzO.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
epoch TEXT NOT NULL,
|
|
4
|
+
applied_seq INTEGER NOT NULL,
|
|
5
|
+
synced_at REAL NOT NULL
|
|
6
|
+
)`),u.add(s))},a=s=>(E(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${c} WHERE id = 1`).toArray()[0]),l=(s,e)=>{E(s),s.exec(`INSERT INTO ${c} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
+
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},C=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(v(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},F=async(s,e)=>{if(s.rowCount()>m(s.env()))return Response.json({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return Response.json({cursor:t,epoch:e,rows:r})},U=(s,e,t)=>{const r=s.ownerFloor();if(w(r,t))return Response.json({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:o,cursor:n}=s.readChanges(t,g);return Response.json({changes:o,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},D=async(s,e)=>{const t=C(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await _(s.env(),e.headers.get(f),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return F(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return U(s,r,i)}return new Response("unknown replica frame",{status:400})};class q{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return a(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=a(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=a(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<b;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<g;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=await e.json();if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=h(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",O)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:await t.json()}async request(e){const t=this.host.shardBinding(),r=S(this.host.env(),t,this.ownerKey);if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=v(this.host.env());i!==void 0&&(n[f]=await y(i,o));try{const d=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return d.ok?d:void 0}catch{return}}}const B=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new q(s,t.ownerKey,t.region)},j=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(L(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{B as createReplicaLink,j as gateReplicaDispatch,D as handleReplicaControl};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as o,d as l}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as d}from"./runDrizzle-it6rL9bR.mjs";const a="__lunora_relay_shapes",t=null,u=e=>{d(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
relay_idx INTEGER,
|
|
4
|
+
connection_id TEXT,
|
|
5
|
+
name TEXT NOT NULL,
|
|
6
|
+
args TEXT NOT NULL,
|
|
7
|
+
identity TEXT NOT NULL,
|
|
8
|
+
cursor INTEGER NOT NULL
|
|
9
|
+
)`)},s=e=>JSON.stringify(o(e)),c=e=>l(JSON.parse(e)),m=e=>d(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(a)}`).toArray().map(r=>({args:c(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:c(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),_=(e,n)=>{d(e,i`INSERT INTO ${i.identifier(a)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
+
VALUES (${n.key}, ${n.relayIndex??t}, ${n.connectionId??t}, ${n.name}, ${s(n.args)}, ${s(n.identity??{})}, ${n.cursor})
|
|
11
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
12
|
+
relay_idx = excluded.relay_idx,
|
|
13
|
+
connection_id = excluded.connection_id,
|
|
14
|
+
name = excluded.name,
|
|
15
|
+
args = excluded.args,
|
|
16
|
+
identity = excluded.identity,
|
|
17
|
+
cursor = excluded.cursor`)},N=(e,n,r)=>{d(e,i`UPDATE ${i.identifier(a)} SET cursor = ${r} WHERE key = ${n}`)},L=(e,n)=>{d(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n}`)},R=e=>{d(e,i`DELETE FROM ${i.identifier(a)}`)};export{_ as a,R as b,L as d,u as m,m as r,N as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as S}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-C4DEsHec.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-C6JwX3Ie.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",reset:!0,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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=/^\d+$/,r=(e,n)=>{const t=e?.[n];let i=Number.NaN;return typeof t=="string"&&o.test(t.trim())?i=Number(t.trim()):typeof t=="number"&&(i=t),Number.isSafeInteger(i)&&i>0?i:void 0},s=(e,n,t)=>r(e,n)??t,N=(e,n)=>r(e,n);export{N as envOptionalPositiveInt,s as envPositiveInt};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DYE0rlxi.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{selectShapeRows as m}from"./selectShapeMembers-GfRzwoVo.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DbHrcoZK.mjs";import{stableStringify as d}from"./stableStringify-G9OF5wcs.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as S,S as L,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as u}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{migrateCdcLog as h,migrateCdcMeta as R}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{migrateClientWatermark as x}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{m as U}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{migrateSearchState as l}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as X,e as T,d,t as G,i as D,g as B,a as M,b as k,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as Y,sortColumnName as P}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const v=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of G(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},K=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!D(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}u(r,n,o)}},V=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=B(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},w=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=p(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${M} TEXT PRIMARY KEY, ${k} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},z=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=Y(n,i.name),m=i.sortBy.map((f,_)=>P(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},_e=(r,n,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),l(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
+
)`),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t),z(r,i,t));o.cdc&&(h(r),R(r),x(r),$(r),U(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),j(r),b(r),O(r),F(r)};export{_e as runShardMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as d,e as h}from"./do-sql-Dk_DJxn4.mjs";import{sqliteInList as w}from"./param-Ib8WHnrF.mjs";import{compileWhereSql as S}from"./compileWhereSql-JBpSfQm9.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-DbI1VQYM.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),n=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of n){const s=d(l),{id:c}=l;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},z=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,g(t)),l=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of l){const c=d(s),{id:m}=s;c!==void 0&&typeof m=="string"&&n.set(m,c)}return n};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(n,t)=>{const o=Math.max(n.length,t.length);let e=n.length^t.length;for(let r=0;r<o;r+=1){const i=r<n.length?n.charCodeAt(r):0,s=r<t.length?t.charCodeAt(r):0;e|=i^s}return e===0},c="LUNORA_RELAY_SECRET",u="x-lunora-relay-sig",l=n=>{const t=n?.[c];return typeof t=="string"&&t.length>0?t:void 0},g=async(n,t)=>{const o=new TextEncoder,e=await crypto.subtle.importKey("raw",o.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",e,o.encode(t));return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")},f=async(n,t,o)=>{const e=l(n);return e===void 0?!0:t===null?!1:a(t,await g(e,o))},d=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},y=(n,t,o)=>{if(t===void 0)return;const e=d(n?.[t]);if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))};export{u as R,l as a,g as b,y as s,f as v};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.39",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.24",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.18",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{m as L,n as O}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as P}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",ne="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,g=500,U=30,W=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[O]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...n}:{...n,...P(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const n=[];for(const s of t){const a=s[m],i=typeof a=="string"?k(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));n.push({...c,...j(i)})}const r=e.filter(s=>s!==m),o=[],_=new Set(r);for(const s of n)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...r,...o],rows:n}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,n)=>Math.min(Math.max(e,t),n),x=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:x(e,d(r))});return n},N=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!N(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",S=(e,t)=>{const n=t.includes(e),r=t.includes(m);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},B=(e,t)=>{const n=S(e.column,t);if(n===void 0)return;const{expression:r,params:o}=n;return e.operator==="contains"?{params:[...o,H(e.value)],sql:F(r)}:{params:[...o,e.value],sql:`${r} ${q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const _=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(n,(r??1)-1,o+1):r===void 0?s=Date.UTC(n+1,0,1):s=Date.UTC(n,r,1),{from:_,to:s}},A=(e,t,n)=>{const r=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);r.push(`(${_.join(" OR ")})`)}for(const _ of n??[]){const s=B(_,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const n=S(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},ae=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(n),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const y=t.refs[w];y!==void 0&&(T[w]=y)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,r,o).toArray();return i({...Q(s,$),total:R})},_e=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??g),1,g),o=d(n),_=M(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,r+1).toArray(),c=i.length>r,u=i.slice(0,r).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,n)=>{const r=new Set(n.filter(_=>_!==m));if(!n.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?k(_):void 0;if(s!==void 0)for(const a of Object.keys(s))r.add(a)}return r},ie=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),_=M(e,o);if(!Y(e,o,_).has(n))throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=S(n,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,n)=>{const r={},o=n.slice(0,g);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!N(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=S(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)r[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:r,storageColumns:t}},ue=e=>{const t=e.map((r,o)=>{const _=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:_}}),n=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=V)=>{const n=new Map,r=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";n.set(i,(n.get(i)??0)+1)}for(const a of s.whispers??[])r.set(a,(r.get(a)??0)+1)}const o=[...[...n].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...r].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,ne as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as p,l as f}from"./do-sql-Dk_DJxn4.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",$=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`)},u=(t,o,i,r,d,T)=>{const E=T===void 0?null:p(T);n(t,e`INSERT INTO ${e.identifier(s)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${o}, ${i}, ${r}, ${d}, ${E})`)},S=(t,o={})=>{const i=o.sinceSeq??0,r=Math.max(1,Math.min(o.limit??1e3,1e4)),d=o.tables&&o.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...o.tables].map(c=>e`${c}`),e`, `)})`:e``,E=n(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(s)} WHERE seq > ${i}${d} ORDER BY seq ASC LIMIT ${r}`).toArray().map(c=>{const l={id:c.id,op:c.op,seq:c.seq,table:c.table,ts:c.ts};return c.doc===null?l:{...l,doc:f(c.doc)}});return{changes:E,cursor:E.at(-1)?.seq??i}},O=(t,o)=>{n(t,e`DELETE FROM ${e.identifier(s)} WHERE seq <= ${o}`)},q=t=>{const i=n(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof i=="number"?i:n(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??0},h=t=>n(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??void 0,a="__cdc_meta",C=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},M=t=>{C(t);const i=n(t,e`SELECT epoch FROM ${e.identifier(a)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${r})`),r},b=t=>{C(t);const o=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},m=async(t,o)=>{if(o.op==="delete"){await t.delete(o.id,o.table);return}const i=o.doc??{};try{await t.insert(o.table,i,{allowExplicitId:!0})}catch(r){if(!(r instanceof L))throw r;const d={...i};delete d._id,await t.replace(o.id,d,void 0,{allowExplicitId:!0})}},y=async(t,o)=>{for(const i of o)await m(t,i)};export{s as CDC_LOG_TABLE,a as CDC_META_TABLE,u as appendCdcChange,y as applyCdcChanges,b as bumpCdcEpoch,$ as migrateCdcLog,C as migrateCdcMeta,h as minCdcSeq,S as readCdcChanges,q as readCdcCursor,M as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as P,LunoraError as x}from"@lunora/errors";import{e as v,d as b}from"./wire-codec-BU9T2xJ7.mjs";import{e as S,v as L,R as I,s as M,a as T,b as D}from"./sibling-channel-BRZpLiDA.mjs";import{relayName as u,DEFAULT_PROMOTION_THRESHOLDS as w,nextPromotionState as O,shapeRoutingKey as R,parseRelayName as k,clampPromotionThresholds as N}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{encodeRowsPatch as C,buildPokeFrames as E}from"./buildPokeFrames-BXejpiII.mjs";import{awaitWsDrain as F,trySendFrame as _}from"./awaitWsDrain-Cs-1HHP6.mjs";import{stableWireKey as m}from"./stableWireKey-DSCJB6E7.mjs";const U=2,W=8,g={},K=l=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(l)}`)},Y=l=>Response.json(l,{headers:{"content-type":"application/json"}}),f=()=>new Response(null,{status:204});class A{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await L(this.host.env(),e.headers.get(I),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),f();case"relay_detach":return this.onDetach(s.relayIndex),f();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),f();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:b(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),f()}case"relay_shape_subscribe":return Y(this.onShapeSubscribe({...s,args:b(s.args)}));default:return K(s)}}maxRelays(){return S(this.host.env(),"LUNORA_MAX_RELAYS",W)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return M(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=T(this.host.env());a!==void 0&&(o[I]=await D(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class H extends A{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(u(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=S(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=S(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=O(this.promotionState,e,N(t,s)),this.promotionState==="owned")return 0;const r=S(this.host.env(),"LUNORA_RELAY_FAN",U);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(u(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,c=n.cursor,i=this.host.buildShapeDiff(a,c,r);if(i.length!==0)return n.cursor=r,{args:v(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:C(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of this.relayShapeRegistry.values()){const n=this.buildShapePoke(a,g,e,t,r);if(n)for(const c of s)o.push(this.postRelayMessage(u(this.roleId.ownerKey,c),n))}await Promise.all(o)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const o of this.relayShapeProxies.values()){const a=this.buildShapePoke(o,o.identity,e,t,s);a&&r.push(this.postRelayMessage(u(this.roleId.ownerKey,o.relayIndex),{...a,targetConnectionId:o.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:d}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:d.code,message:d.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let c=o;if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let d=this.relayShapeRegistry.get(h);d===void 0&&(d={args:e.args,cursor:o,name:e.name},this.relayShapeRegistry.set(h,d)),c=d.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:o,epoch:a,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const i=E([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:o,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:a,frames:i}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=m(s.effectiveWhere),o=m(s.columns);let a=!1;const n=i=>{const h={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(h,{get:(y,p)=>typeof p=="symbol"||p in y?Reflect.get(y,p):`${i}:${p}`,getOwnPropertyDescriptor:(y,p)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,p)),has:(y,p)=>typeof p=="symbol"?Reflect.has(y,p):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,n("a"),n("b")].every(i=>{let h;try{h=this.host.resolveShape(e,t,i)}catch{return!1}return h!==void 0&&h.global!==!0&&h.table===s.table&&m(h.effectiveWhere)===r&&m(h.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class $ extends A{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:v(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await F(e);for(const c of n.frames)_(e,c);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[c,i]of Object.entries(a)){const h=n.get(c);if(h?.cursor!==e.fromCursor||h.epoch!==e.epoch||R(i.name,i.args)!==t)continue;const d=E([{rowsPatch:e.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of d)_(r,y);n.set(c,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const Q=l=>{const e=l.doName();if(e===void 0)return;const t=k(e);return t===void 0?new H(l,e):new $(l,t.ownerKey,t.relayIndex)};export{W as DEFAULT_MAX_RELAYS,H as OwnerRelay,$ as RelayMember,Q as createRelayLink};
|