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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +1 -1
  3. package/dist/conformance/index.mjs +1 -1
  4. package/dist/index.d.mts +1101 -221
  5. package/dist/index.d.ts +1101 -221
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/ADMIN_FUNCTIONS-olXwJWFQ.mjs +14 -0
  8. package/dist/packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs +1 -0
  9. package/dist/packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs +1 -0
  10. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
  11. package/dist/packem_shared/AGG_COUNT-BaMXGlVQ.mjs +1 -0
  12. package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
  13. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  14. package/dist/packem_shared/CDC_LOG_TABLE-fCPCjSE4.mjs +18 -0
  15. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
  16. package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
  17. package/dist/packem_shared/CURSOR_PREFIX-rOdoinP8.mjs +1 -0
  18. package/dist/packem_shared/CompanionMemo-jmlDbPlr.mjs +1 -0
  19. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  20. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs +31 -0
  21. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DrcbZM0t.mjs +1 -0
  22. package/dist/packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs +8 -0
  23. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-VU44O5kq.mjs +1 -0
  24. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs +1 -0
  25. package/dist/packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs +1 -0
  26. package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
  27. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  28. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
  29. package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
  30. package/dist/packem_shared/IDEMPOTENCY_TABLE-BVosXEq_.mjs +7 -0
  31. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +1 -0
  32. package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
  33. package/dist/packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs +5 -0
  34. package/dist/packem_shared/MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs +1 -0
  35. package/dist/packem_shared/NotUniqueError-CDB9Ooq4.mjs +1 -0
  36. package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
  37. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
  38. package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
  39. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs +1 -0
  40. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  41. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs +1 -0
  42. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  43. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs +1 -0
  44. package/dist/packem_shared/ReactiveCache-BG9z3FE9.mjs +1 -0
  45. package/dist/packem_shared/SCAN_DEP-B4Uu4g7l.mjs +1 -0
  46. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs +18 -0
  47. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
  48. package/dist/packem_shared/SEARCH_STATE_TABLE-D7w8mRsm.mjs +1 -0
  49. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
  50. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  51. package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
  52. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs +1 -0
  53. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
  54. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  55. package/dist/packem_shared/adminTokenExists-CQ0qedmu.mjs +8 -0
  56. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  57. package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
  58. package/dist/packem_shared/applyInsertDefaults-CYSHgpFD.mjs +1 -0
  59. package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
  60. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  61. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  62. package/dist/packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs +1 -0
  63. package/dist/packem_shared/buildIndexRange-BTChxh3k.mjs +1 -0
  64. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  65. package/dist/packem_shared/buildReprojectionMigration-wSas3lLT.mjs +1 -0
  66. package/dist/packem_shared/buildSettings-CFkvTaHx.mjs +1 -0
  67. package/dist/packem_shared/buildShapeDiff-DrXTkXKH.mjs +1 -0
  68. package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
  69. package/dist/packem_shared/compileWhereSql--dIcrS0b.mjs +1 -0
  70. package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +1 -0
  71. package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
  72. package/dist/packem_shared/createCompanionSync-DmciS_rv.mjs +1 -0
  73. package/dist/packem_shared/createReplicaLink-BapaAUfm.mjs +7 -0
  74. package/dist/packem_shared/createSystemReader-BSCxr8Qs.mjs +1 -0
  75. package/dist/packem_shared/ctx-db-relay-shapes-DBobAek2.mjs +17 -0
  76. package/dist/packem_shared/ctx-db-search-state-CPKPy8N6.mjs +1 -0
  77. package/dist/packem_shared/defineEngineContractSuite-B_CuudJA.mjs +1 -0
  78. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  79. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  80. package/dist/packem_shared/do-sql-Cf2rnuLV.mjs +1 -0
  81. package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
  82. package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
  83. package/dist/packem_shared/estimate-bytes-C-C35VXL.mjs +1 -0
  84. package/dist/packem_shared/exportShardRows-BEzRTBwD.mjs +1 -0
  85. package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +1 -0
  86. package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +1 -0
  87. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  88. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  89. package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
  90. package/dist/packem_shared/isSoftDeleted-By7iuPdW.mjs +9 -0
  91. package/dist/packem_shared/isTtlExpired-Bymg2-13.mjs +1 -0
  92. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  93. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  94. package/dist/packem_shared/materializeExternalRows-gZqs4Rsj.mjs +1 -0
  95. package/dist/packem_shared/mergeChangedKeys-DPKhen6e.mjs +1 -0
  96. package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
  97. package/dist/packem_shared/relay-CKEdfUjH.mjs +1 -0
  98. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
  99. package/dist/packem_shared/runShardMigrations-4_ene2xR.mjs +5 -0
  100. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  101. package/dist/packem_shared/selectShapeMembers-Ce6pOHKe.mjs +1 -0
  102. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  103. package/dist/packem_shared/stubByName-DQSivmvb.mjs +1 -0
  104. package/dist/packem_shared/where-sql-Cb_dSAMj.mjs +1 -0
  105. package/package.json +6 -5
  106. package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +0 -1
  107. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  108. package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +0 -1
  109. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
  110. package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +0 -8
  111. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
  112. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  113. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
  114. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs +0 -1
  115. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs +0 -1
  116. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs +0 -1
  117. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs +0 -1
  118. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  119. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
  120. package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
  121. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
  122. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  123. package/dist/packem_shared/NotUniqueError-CVHdtVw6.mjs +0 -1
  124. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
  125. package/dist/packem_shared/RANK_TIEBREAK-DDtST3gN.mjs +0 -1
  126. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  127. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
  128. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  129. package/dist/packem_shared/ReactiveCache-Cu8IfE1M.mjs +0 -1
  130. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  131. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
  132. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
  133. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  134. package/dist/packem_shared/aggregateTableName-DgYMC5tr.mjs +0 -1
  135. package/dist/packem_shared/applyOnDelete-By23GK-k.mjs +0 -1
  136. package/dist/packem_shared/applySelect-UY-o13Ia.mjs +0 -1
  137. package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
  138. package/dist/packem_shared/backfillAggregateIndexes-DmqOHg0U.mjs +0 -1
  139. package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
  140. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  141. package/dist/packem_shared/buildPokeFrames-CqxaN8_H.mjs +0 -1
  142. package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +0 -1
  143. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  144. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  145. package/dist/packem_shared/computeRankPage-QK8SeTZ-.mjs +0 -1
  146. package/dist/packem_shared/createCompanionSync-COw1Uy6a.mjs +0 -1
  147. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  148. package/dist/packem_shared/createReplicaLink-BMNW0SX6.mjs +0 -7
  149. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  150. package/dist/packem_shared/ctx-db-companions-BTi8DLUl.mjs +0 -1
  151. package/dist/packem_shared/defineEngineContractSuite-B6nrsKSE.mjs +0 -1
  152. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  153. package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +0 -1
  154. package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
  155. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  156. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  157. package/dist/packem_shared/isSoftDeleted-Bo-y3DOe.mjs +0 -9
  158. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  159. package/dist/packem_shared/materializeExternalRows-DcCENzpV.mjs +0 -1
  160. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  161. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  162. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
  163. package/dist/packem_shared/runShardMigrations-BqO6HPtX.mjs +0 -5
  164. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  165. package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +0 -1
  166. package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +0 -1
  167. package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
  168. package/dist/packem_shared/sibling-channel-bg9FBL5s.mjs +0 -1
  169. package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
  170. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  171. package/dist/packem_shared/stableWireKey-l3cjIt-9.mjs +0 -1
  172. package/dist/packem_shared/wire-codec-Dsy70M3Q.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 l,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as h}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as I,mergeWhere as R,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-CVHdtVw6.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DmqOHg0U.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{w as ie}from"./packem_shared/ctx-db-companions-BTi8DLUl.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as me,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as he,writeIdempotent as Ae}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Re,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-QK8SeTZ-.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-BdBcbrUP.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-B6rnz3so.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as sr}from"./packem_shared/do-sql-1Yi1_Yq0.mjs";import{param as ir,renderSql as pr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as dr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as Er,runExternalSourceTick as hr}from"./packem_shared/materializeExternalRows-DcCENzpV.mjs";import{isSoftDeleted as Ir,isSourceDue as Rr,pullExternalSourceIncrementalTick as Cr,pullExternalSourceTick as _r}from"./packem_shared/isSoftDeleted-Bo-y3DOe.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Or,haversineMeters as Fr,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as kr,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Br,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Hr,recordFanoutPass as Vr,selectMatchingIds as Xr,summarizeFanoutTopics as jr,summarizeSubscriptions as Qr}from"./packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as so,readBookmark as lo}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as mo,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as go,clearQueueMessages as Eo,isLossyBody as ho,readQueueMessageById as Ao,readQueueMessages as Io,recordQueueMessages as Ro}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as _o,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as Do,reactiveCacheKey as Po}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Ho,isRelationPredicate as Vo,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as Qo,distinctValues as Yo,fanOutScalarCounts as Jo,relationHooks as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as sa}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ia,OwnerRelay as pa,RelayMember as ma,createRelayLink as da}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as Sa,gateReplicaDispatch as ua,handleReplicaControl as xa}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ta,countLegacyRows as ga,reprojectableFields as Ea,reprojectionTables as ha}from"./packem_shared/buildReprojectionMigration-Ctl4r84d.mjs";import{RLS_UNWRAP_SYMBOL as Ia,RlsRequiredError as Ra,guardWriter as Ca}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as La,readSchemaHistory as ba,readSchemaVersion as ya,recordSchemaVersion as Na}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Oa}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as Da,isDevEnvironment as Pa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Ga,diffGlobalMembership as Ba,encodeRowsPatch as Ua,projectColumns as wa}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as qa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as va}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ha,assertReadonly as Va,lintReadonlySql as Xa,runReadonlySql as ja}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Ya,sendDeltaFrames as Ja,subscriptionListDeltas as Za,trySendFrame as $a}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as rt,recordChangedKeys as ot,writeTouchesMemo as at}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as nt}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as lt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as pt,TransactionHeadroomTracker as mt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs";import{hasTrigger as ct,runTriggers as St}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as xt}from"./packem_shared/selectExpiredIds-C6nQK7E2.mjs";import{compileWhereSql as Tt}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as Et}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as At,reprojectionMigrationId as It}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as Ct}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Lt}from"./packem_shared/runShardMigrations-BqO6HPtX.mjs";import{stableStringify as yt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Mt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{kr as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,lt as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Br as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,ia as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,pt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ha as MAX_SQL_ROWS,to as NotFoundError,P as NotUniqueError,pa as OwnerRelay,go as QUEUE_TABLE,_o as RANK_TIEBREAK,Et as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,At as REPROJECTION_MIGRATION_PREFIX,Ia as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,ma as RelayMember,Ra as RlsRequiredError,Ue as SCAN_DEP,La as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,qa as ShardRunner,mt as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Qo as applyOnDelete,po as applySelect,so as armRestore,vo as assertFlatPredicate,Va as assertReadonly,zo as assertShapeShardable,k as assertValidClientId,Ya as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,Ga as buildPokeFrames,Ta as buildReprojectionMigration,mo as buildSeekBeforeWhere,co as buildSeekWhere,Da as buildSettings,j as bumpCdcEpoch,aa as clampPromotionThresholds,$r as clearCapturedMail,Eo as clearQueueMessages,T as coerceAggregateNumber,Tt as compileWhereSql,Re as computeRankPage,Ho as containsRelationPredicate,ga as countLegacyRows,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,da as createRelayLink,Sa as createReplicaLink,G as createShardCtxDb,nt as createSystemReader,So as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,dr as diffExternalSource,Ba as diffGlobalMembership,Yo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Or as encodeGeohash,Lo as encodePartitionKey,Ua as encodeRowsPatch,O as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,E as foldAggregateTally,ua as gateReplicaDispatch,Ze as geoTableName,Ca as guardWriter,xa as handleReplicaControl,ct as hasTrigger,Fr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,Pa as isDevEnvironment,$e as isFtsAvailable,ho as isLossyBody,Vo as isRelationPredicate,Ir as isSoftDeleted,Rr as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Xa as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,rt as mergeChangedKeys,R as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,s as parseImportShardArgs,C as planAggregateLookup,Dr as pointInBoundingBox,wa as projectColumns,Cr as pullExternalSourceIncrementalTick,_r as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,Ct as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,Po as reactiveCacheKey,h as readAggregateValue,F as readAuditLog,lo as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Er as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,Ao as readQueueMessageById,Io as readQueueMessages,ba as readSchemaHistory,ya as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,oo as recordCapturedMail,ot as recordChangedKeys,Vr as recordFanoutPass,Ro as recordQueueMessages,Na as recordSchemaVersion,Zo as relationHooks,na as relayCountFor,pr as renderSql,Ea as reprojectableFields,It as reprojectionMigrationId,ha as reprojectionTables,Mo as resolveRankPartition,Xo as resolveRelationPredicates,$o as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,hr as runExternalSourceTick,ja as runReadonlySql,ea as runRowValidators,Lt as runShardMigrations,va as runSocketPool,ze as runSql,St as runTriggers,xt as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,Ja as sendDeltaFrames,Oa as serializeSqlValue,sa as shapeRoutingKey,fo as softDeleteScope,Oo as sortColumnName,yt as stableStringify,Mt as stableWireKey,Za as subscriptionListDeltas,jr as summarizeFanoutTopics,Qr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,sr as tryRowToDocument,$a as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ae as writeIdempotent,Ne as writeSearchBackfillState,at as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-CDB9Ooq4.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-fCPCjSE4.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-jmlDbPlr.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-DmciS_rv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Ce6pOHKe.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-Cf2rnuLV.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-gZqs4Rsj.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-By7iuPdW.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-olXwJWFQ.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DrcbZM0t.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-CYSHgpFD.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-BapaAUfm.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-wSas3lLT.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-DrXTkXKH.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-Bymg2-13.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-Cb_dSAMj.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-4_ene2xR.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
@@ -0,0 +1,14 @@
1
+ import{LunoraError as m}from"@lunora/errors";import{decodeWire as G,WIRE_TAG as F,needsWireEncoding as J,encodeWire as X}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as $}from"./isInternalTableName-BoljO2tP.mjs";import{n as y,o as V}from"./do-sql-Cf2rnuLV.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as Y,sqliteInList as Z}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Fe="__lunora_admin__:",xe="__lunora_relation__:",qe="__lunora_flags__:",Ue={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiCronExpression:"__lunora_admin__:aiCronExpression",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiNameQuery:"__lunora_admin__:aiNameQuery",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createAdminToken:"__lunora_admin__:createAdminToken",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",dropOutboxEntry:"__lunora_admin__:dropOutboxEntry",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",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",getScheduleOutbox:"__lunora_admin__:getScheduleOutbox",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",importAbort:"__lunora_admin__:importAbort",importCommit:"__lunora_admin__:importCommit",importManifest:"__lunora_admin__:importManifest",importShard:"__lunora_admin__:importShard",importStage:"__lunora_admin__:importStage",importStagedRows:"__lunora_admin__:importStagedRows",listAdminTokens:"__lunora_admin__:listAdminTokens",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordImportAudit:"__lunora_admin__:recordImportAudit",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",retryOutboxEntry:"__lunora_admin__:retryOutboxEntry",resolveIssue:"__lunora_admin__:resolveIssue",revokeAdminToken:"__lunora_admin__:revokeAdminToken",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",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",verifyAdminToken:"__lunora_admin__:verifyAdminToken",writeRow:"__lunora_admin__:writeRow"},ee=50,N=500,te=30,ne=200,c="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},re=e=>{const{[y]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...n}:{...n,...G(t)}},oe=(e,t)=>{if(!e.includes(c))return{columns:e,rows:t};const n=[];for(const i of t){const s=i[c],_=typeof s=="string"?x(s):void 0;if(_===void 0)return{columns:e,rows:t};const l=Object.fromEntries(Object.entries(i).filter(([u])=>u!==c));n.push({...l,...re(_)})}const r=e.filter(i=>i!==c),o=[],a=new Set(r);for(const i of n)for(const s of Object.keys(i))a.has(s)||(a.add(s),o.push(s));return{columns:[...r,...o],rows:n}},g=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,O=(e,t,n)=>Math.min(Math.max(e,t),n),q=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},He=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)$(r)||n.push({name:r,rowCount:q(e,d(r))});return n},U=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if($(t)||!U(e,t))throw new m("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},j=100,M=(e,t)=>{if(t>j)throw new m("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(j)} — remove some filters or narrow the search`)},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",ae=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?H(e.value)==="":ae.has(e.operator)&&e.value==="",P=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new m("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},T=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(c);if(!(!r&&!o)){if(r){if(n.length>0)throw new m("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:d(e),params:[]}}return{expression:`json_extract(${d(c)}, ?)`,params:[P(e,n)]}}},ie=/^-?\d+$/u,R=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ie.test(r))throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new m("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},_e=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,le=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new m("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},ce=(e,t,n)=>{if(t.includes(e.column))throw new m("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(c))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new m("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=le(e.value),a=P(e.column,r),i=d(c),s=`SELECT 1 FROM json_each(${i}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${a}[0]`,a,...o.params,`${a}[1]`,`${a}[2]`,...o.params],sql:`CASE WHEN json_extract(${i}, ?) IS NOT '${F}' THEN EXISTS (${s}) WHEN json_extract(${i}, ?) IS 'arr' THEN EXISTS (${s}) ELSE 0 END`}},de=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return J(e)?JSON.stringify(X(e)):void 0}catch(t){throw new m("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",me=(e,t,n)=>{const r=de(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new m("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let a="'integer', 'real'";return typeof e.value=="string"?a="'text'":typeof e.value=="boolean"&&(a="'true', 'false'"),{params:[...n,...n,R(e,void 0)],sql:`(json_type(${d(c)}, ?) IN (${a}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const a=`json_type(${d(c)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,i=R(e,void 0);return o==="eq"?{params:[...n,...n,i],sql:`(${a})`}:{params:[...n,...n,...n,i],sql:`(${t} IS NOT NULL AND NOT (${a}))`}}},fe=/["\\\u0000-\u001F]/u,W=e=>fe.test(e)?"":e,B=(e,t,n,r)=>{const o=`'${F}'`,a=f=>`(instr(${f}, ${o}) > 0 OR instr(${f}, ${String.raw`'\u'`}) > 0)`,i=a(e),s=r.prefilter===void 0?[]:[r.prefilter],_=r.root===void 0?"":", ?",l=r.root===void 0?[]:[r.root],u=[...r.prefilter===void 0?[]:[g(e)],`EXISTS (SELECT 1 FROM json_tree(${e}${_}) AS j WHERE ${n.sql})`],p=[a(`t.${e}`),...r.prefilter===void 0?[]:[g(`t.${e}`)]],E=`(${u.join(" AND ")})`;return{params:[...s,...l,...n.params,...s,...l,...n.params],sql:`CASE WHEN ${i} THEN ${e} COLLATE BINARY IN (WITH RECURSIVE
2
+ __wf_framed AS MATERIALIZED (SELECT DISTINCT t.${e} COLLATE BINARY AS doc FROM ${t} AS t WHERE ${p.join(" AND ")}),
3
+ __wf_docs AS MATERIALIZED (SELECT doc, row_number() OVER () AS n FROM __wf_framed),
4
+ __wf_raw AS (SELECT d.n, j.id, j.parent, j.key, j.type, j.atom, j.value, j.fullkey FROM __wf_docs AS d, json_tree(d.doc${_}) AS j),
5
+ __wf_flags AS MATERIALIZED (SELECT n, parent AS id,
6
+ max(CASE WHEN typeof(key) = 'integer' AND key = 0 AND type = 'text' AND atom = ${o} THEN 1 ELSE 0 END) AS tagged,
7
+ count(CASE WHEN typeof(key) = 'integer' AND ((key = 0 AND atom = ${o}) OR (key = 1 AND atom = 'arr')) THEN 1 END) = 2 AS shaped
8
+ FROM __wf_raw WHERE parent IS NOT NULL GROUP BY n, parent),
9
+ __wf_tree AS MATERIALIZED (SELECT __wf_raw.*, coalesce(f.tagged, 0) AS tagged_parent, coalesce(f.shaped, 0) AS shaped_parent FROM __wf_raw LEFT JOIN __wf_flags AS f ON f.n = __wf_raw.n AND f.id = __wf_raw.parent),
10
+ __wf_steps AS MATERIALIZED (SELECT n, id, parent FROM __wf_tree WHERE typeof(key) = 'integer' AND key = 2 AND shaped_parent),
11
+ __wf_runs(n, id, k) AS MATERIALIZED (SELECT s.n, s.id, 1 FROM __wf_steps AS s LEFT JOIN __wf_steps AS p ON p.n = s.n AND p.id = s.parent WHERE p.id IS NULL UNION ALL SELECT c.n, c.id, r.k + 1 FROM __wf_runs AS r JOIN __wf_steps AS c ON c.n = r.n AND c.parent = r.id),
12
+ __wf_excluded AS MATERIALIZED (SELECT j.n, j.id FROM __wf_tree AS j LEFT JOIN __wf_runs AS p ON p.n = j.n AND p.id = j.parent WHERE typeof(j.key) = 'integer' AND j.key IN (0, 1) AND j.tagged_parent AND coalesce(p.k, 0) % 2 = 0),
13
+ __wf_framedMatches AS (SELECT d.doc FROM __wf_docs AS d JOIN (SELECT DISTINCT j.n FROM __wf_tree AS j LEFT JOIN __wf_excluded AS e ON e.n = j.n AND e.id = j.id WHERE ${n.sql} AND e.id IS NULL) AS m ON m.n = d.n)
14
+ SELECT doc FROM __wf_framedMatches) ELSE ${E} END`}},pe=(e,t,n,r)=>{const o={params:[r],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")}`},a=B(t,e,o,{prefilter:W(r),root:n});return{params:[n,n,r,n,n,r,n,...a.params],sql:`CASE WHEN json_type(${t}, ?) IN ('text', 'integer', 'real') THEN ${g(`json_extract(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('true', 'false') THEN ${g(`json_type(${t}, ?)`)} WHEN json_type(${t}, ?) IN ('array', 'object') THEN ${a.sql} ELSE 0 END`}},Ee=(e,{expression:t,kind:n,pathParameters:r,physical:o,table:a})=>{const i=e.path??[];if(n==="bigint")throw new m("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const s=H(e.value);return i.length===0&&o?{params:[s],sql:g(t)}:i.length===0?pe(a,d(c),r[0],s):{params:[...r,...r,s],sql:`(json_type(${d(c)}, ?) IN ('text', 'integer', 'real') AND ${g(t)})`}},Se=(e,t,n,r)=>{if(e.operator==="has")return ce(e,t,n);const o=e.path??[],a=T(e.column,t,o);if(a===void 0||se(e))return;const{expression:i,params:s}=a,_=t.includes(e.column)||o.length>0?void 0:n?.[e.column];if(e.operator==="contains")return Ee(e,{expression:i,kind:_,pathParameters:s,physical:t.includes(e.column),table:r});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:s,sql:`${i} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(o.length>0){const l=me(e,i,s);if(l!==void 0)return l}return{params:[...s,R(e,_)],sql:`${i} ${I[e.operator]} ?`}},ge=new Set(["date","timestamp"]),Ae=[`$.${y}`,`$."${y}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Ne=(e,t)=>{const n={params:[t],sql:`j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${g("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${Ae}`};return B(d(c),e,n,{prefilter:W(t)})},Te=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,he=e=>{const t=Te.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 a=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(a).getUTCDate()!==o)return;let i;return o!==void 0?i=Date.UTC(n,(r??1)-1,o+1):r===void 0?i=Date.UTC(n+1,0,1):i=Date.UTC(n,r,1),{from:a,to:i}},ye=(e,t,n)=>t.map(r=>r===c?Ne(e,n):{params:[n],sql:g(d(r))}),be=(e,t,n)=>{const r=e.map(a=>({params:[n.from,n.to],sql:`(${d(a)} >= ? AND ${d(a)} < ?)`})),o=Object.keys(t??{}).filter(a=>!e.includes(a)&&ge.has(t?.[a]??""));return o.length>0&&e.includes(c)&&r.push({params:[JSON.stringify(o),n.from,n.to],sql:`EXISTS (SELECT 1 FROM json_each(${d(c)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`}),r},v=(e,t,n,r,o)=>{const a=[],i=[];if(n!==""&&t.length>0){const s=ye(e,t,n),_=he(n);_!==void 0&&s.push(...be(t,o,_)),a.push(`(${s.map(l=>l.sql).join(" OR ")})`),i.push(...s.flatMap(l=>l.params))}for(const s of r??[]){const _=Se(s,t,o,e);_!==void 0&&(a.push(`(${_.sql})`),i.push(..._.params))}return a.length===0?void 0:{parameters:i,where:a.join(" AND ")}},we=(e,t)=>{if(e===void 0)return;const n=T(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Pe=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??ee),1,N),o=Math.max(0,Math.trunc(t.offset??0)),a=d(n),i=b(e,a),s=t.search?.trim()??"",_=h=>{if(t.refs===void 0)return h;const w={};for(const D of h.columns){const k=t.refs[D];k!==void 0&&(w[D]=k)}return Object.keys(w).length>0?{...h,refs:w}:h},l=v(a,i,s,t.filters,t.columnKinds),u=we(t.orderBy,i),p=l===void 0?"":` WHERE ${l.where}`,E=u===void 0?"":` ORDER BY ${u.sql}`,f=l?.parameters??[],A=u?.params??[];M(n,f.length+A.length+2);let S;t.skipCount||(S=l===void 0?q(e,a):Number(e.exec(`SELECT COUNT(*) AS c FROM ${a}${p}`,...f).one().c));const Q=e.exec(`SELECT * FROM ${a}${p}${E} LIMIT ? OFFSET ?`,...f,...A,r,o).toArray();return _({...oe(i,Q),sqlColumns:i,total:S})},We=(e,t)=>{const{table:n}=t;C(e,n);const r=O(Math.trunc(t.limit??N),1,N),o=d(n),a=b(e,o),i=t.search?.trim()??"";for(const S of t.filters??[])if(T(S.column,a,S.path??[])===void 0)throw new m("BAD_REQUEST",`unknown column: ${S.column}`);const s=v(o,a,i,t.filters,t.columnKinds);if(s===void 0&&(t.filters?.length??0)>0)throw new m("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],l=[];s!==void 0&&(_.push(s.where),l.push(...s.parameters)),t.after!==void 0&&(_.push("id > ?"),l.push(t.after));const u=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";M(n,l.length+1);const E=e.exec(`SELECT id FROM ${o}${u}${p} LIMIT ?`,...l,r+1).toArray(),f=E.length>r,A=E.slice(0,r).map(S=>S.id);return{hasMore:f,ids:A}},Ie=(e,t,n,r)=>{const o=new Set(n.filter(i=>i!==c));if(!n.includes(c))return o;for(const i of Object.keys(r??{}))o.add(i);const a=e.exec(`SELECT ${d(c)} AS doc FROM ${t} LIMIT ?`,N).toArray();for(const{doc:i}of a){const s=typeof i=="string"?x(i):void 0;if(s!==void 0)for(const _ of Object.keys(s))o.add(_)}return o},Be=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),a=b(e,o);if(!Ie(e,o,a,t.columnKinds).has(n))throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=T(n,a);if(i===void 0)throw new m("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=O(Math.trunc(t.limit??te),1,ne),_=t.search?.trim()??"",l=v(o,a,_,t.filters,t.columnKinds),u=l===void 0?"":` WHERE ${l.where}`,p=l?.parameters??[];M(r,i.params.length*2+p.length+1);const E=e.exec(`SELECT ${i.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${i.expression} ORDER BY count DESC LIMIT ?`,...i.params,...p,...i.params,s+1).toArray(),f=E.length>s,A=a.includes(n)?void 0:t.columnKinds?.[n];return{truncated:f,values:E.slice(0,s).map(S=>({count:Number(S.count),value:_e(S.value,A)}))}},Qe=(e,t,n)=>{const r={},o=n.slice(0,N);for(const a of o)r[a]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[a,i]of Object.entries(t)){if($(a)||!U(e,a))continue;const s=d(a),_=b(e,s);for(const l of i){const u=T(l,_);if(u===void 0)continue;const p=Y("sqlite",Z(K.raw(u.expression),o,!1)),E=e.exec(`SELECT id, ${u.expression} AS ref FROM ${s} WHERE ${p.sql}`,...u.params,...u.params,...p.params).toArray();for(const f of E)r[f.ref]?.push({column:l,id:f.id,table:a})}}return{references:r,storageColumns:t}},Ge=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,a)=>{const i=Object.values(o.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:o.admin===!0,id:a,subscriptions:i}}),r=n.reduce((o,a)=>o+a.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},Re=20,Je=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ke=()=>({drains:0,pairsSkipped:0}),Ve=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ye=(e,t,n)=>({run:e.run+t,served:e.served+n}),Ze=(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}),ze=(e,t=Re)=>{const n=new Map,r=new Map,o=e.filter(s=>s.authenticated!==!1);for(const s of o){for(const _ of Object.values(s.shapes??{})){const l=_.name??"(unknown shape)";n.set(l,(n.get(l)??0)+1)}for(const _ of s.whispers??[])r.set(_,(r.get(_)??0)+1)}const a=[...[...n].map(([s,_])=>({kind:"shape",subscribers:_,topic:s})),...[...r].map(([s,_])=>({kind:"whisper",subscribers:_,topic:s}))];return a.sort((s,_)=>_.subscribers-s.subscribers||s.topic.localeCompare(_.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:o.length}};export{Ue as ADMIN_FUNCTIONS,Fe as ADMIN_FUNCTION_PREFIX,Re as DEFAULT_FANOUT_TOPIC_LIMIT,qe as FLAGS_FUNCTION_PREFIX,N as MAX_PAGE_SIZE,xe as RELATION_FUNCTION_PREFIX,Je as createFanoutCounters,Ke as createGlobalPollCounters,Xe as createShapeProbeCounters,he as datePrefixRange,Be as facetColumn,Qe as findStorageReferences,$ as isInternalTableName,se as isVacuousFilterClause,He as listTables,Pe as readTablePage,Ze as recordFanoutPass,Ve as recordGlobalPollPass,Ye as recordShapeProbePass,We as selectMatchingIds,ze as summarizeFanoutTopics,Ge as summarizeSubscriptions};
@@ -0,0 +1 @@
1
+ const _="__lunora_admin_tokens__";export{_ as ADMIN_TOKEN_TABLE};
@@ -0,0 +1 @@
1
+ import{idRange as d}from"./buildIndexRange-BTChxh3k.mjs";const f=()=>{const o=new Set,n=new Map,s=new Set,r=e=>{o.add(e.table);const t=n.get(e.table);t?t.push(e):n.set(e.table,[e])};return{onRead(e,t,a){if(a===!0&&t!==void 0){r(d(e,t));return}o.add(e),s.add(e)},onReadRange:r,ranges(){for(const e of s)n.delete(e);return n.size>0?n:void 0},tables:o}},R="*",i="!unvouchable",b=(o,n,s)=>{if(!n)return o;const r=new Set(s);return new Proxy(o,{get(e,t,a){const c=Reflect.get(e,t,a);return typeof c!="function"||typeof t!="string"||!r.has(t)?c:(...u)=>(n(i),Reflect.apply(c,e,u))}})};export{R as ADMIN_WILDCARD,i as UNVOUCHABLE_DEP,f as createReadFootprint,b as markUnvouchableReads};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{r as f}from"./json-field-path-DeJW4U9z.mjs";const a=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},d=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=f(e,n)??null;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==(t.eq??null))return!1;continue}return!1}if(o!==t)return!1}return!0},y=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>a.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},A=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},w={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,A as aggregateSqlFunction,d as matchesStaticWhere,y as normalizeCountArgument,w as throwingScheduler};
@@ -0,0 +1 @@
1
+ import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-DeJW4U9z.mjs";import{A as l,a as n,b as i,D as d,n as p,W as u,c as m,d as q,l as S,s as G,m as c,k as A,g as D,i as f,j as _,e as h,p as P,v as T,q as g,f as j,r as y,t as C,h as O,u as b}from"./do-sql-Cf2rnuLV.mjs";import{quoteIdentifier as E}from"./quoteIdentifier-CObIFRhb.mjs";import"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-DeoBMpZ2.mjs";import"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";export{l as AGG_COUNT,n as AGG_KEY,i as AGG_VALUE,d as DOC_COLUMN,p as DOC_ORIGINALS_KEY,u as WRAPPED_SQL,m as aggUpsertSql,q as createIndexSql,S as decodeDocJson,G as decodeGroupKeyValue,c as doWhereSqlStrategy,A as encodeDocJson,D as geoTableName,f as isFtsAvailable,_ as jsonPath,h as jsonPathSql,P as jsonTypeGuard,T as jsonTypeGuardSql,g as qualifiedJsonPath,j as qualifiedJsonPathSql,E as quoteIdentifier,y as rowToDocument,J as serializeSqlValue,C as tableColumns,O as tryRowToDocument,b as unwrapSql};
@@ -0,0 +1,8 @@
1
+ import{runSql as T}from"./runDrizzle-RC09zZrh.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ op TEXT NOT NULL,
5
+ "table" TEXT,
6
+ id TEXT,
7
+ detail TEXT
8
+ )`)},R=(E,t)=>{s(E),T(E,`INSERT INTO "${i}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,t.ts,t.op,t.table??null,t.id??null,t.detail===void 0?null:JSON.stringify(t.detail)),T(E,`DELETE FROM "${i}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${i}")`,a)},o=(E,t={})=>{s(E);const d=t.sinceSeq??0,n=Math.max(1,Math.min(t.limit??a,1e4));return T(E,`SELECT seq, ts, op, "table", id, detail FROM "${i}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,n).toArray().map(e=>{const l={op:e.op,seq:e.seq,ts:e.ts};return e.table!==null&&(l.table=e.table),e.id!==null&&(l.id=e.id),e.detail!==null&&(l.detail=JSON.parse(e.detail)),l})};export{i as AUDIT_LOG_TABLE,R as appendAuditEntry,s as ensureAuditTable,o as readAuditLog};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{e as s}from"./effective-kind-BmG_zCAy.mjs";const o=t=>{let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(n)},i=39,f="0",c="1",a=t=>Array.from(t,n=>String(9-Number(n))).join(""),d=t=>{const n=t<0n,e=(n?-t:t).toString();if(e.length>i)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(e.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const r=e.padStart(i,"0");return n?f+a(r):c+r},l=/^\d+$/u,h=t=>{if(t.length!==i+1)return;const n=t.slice(0,1),e=t.slice(1);if(l.test(e))return n===c?BigInt(e):n===f?-BigInt(a(e)):void 0},u=/^[\da-f]{16}$/u,b=t=>{const n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t===0?0:t,!1);let e=n.getUint32(0,!1),r=n.getUint32(4,!1);return(e&2147483648)===0?e=(e^2147483648)>>>0:(e=~e>>>0,r=~r>>>0),e.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")},I=t=>{if(!u.test(t))return;let n=Number.parseInt(t.slice(0,8),16),e=Number.parseInt(t.slice(8),16);(n&2147483648)===0?(n=~n>>>0,e=~e>>>0):n=(n^2147483648)>>>0;const r=new DataView(new ArrayBuffer(8));return r.setUint32(0,n,!1),r.setUint32(4,e,!1),r.getFloat64(0,!1)},p=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,y=t=>{const n=s(t);return n==="bigint"||n==="bytes"},E=t=>{const n=s(t);return y(t)||n==="any"||n==="union"||n==="from"};export{i as BIGINT_KEY_DIGITS,d as bigintSqlKey,h as decodeBigintSqlKey,I as decodeFloat64SqlKey,b as float64SqlKey,y as isProjectedKind,E as mayHoldProjectedValue,p as sqlComparableProjection};
@@ -0,0 +1,18 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-Cf2rnuLV.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${C(c)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",O="__cdc_log_table_id_seq",u=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{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($)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(_)} ON ${t.identifier(c)} (seq) WHERE ${u}`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, id, seq)`)}catch{}},X=(e,o,i,r,s,a)=>{const d=a===void 0?null:m(a);I(e,N,o,i,r,s,d)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,v=(e,o={})=>{const i=o.sinceSeq??0,r=Math.max(1,Math.min(o.limit??1e3,1e4)),a=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${i} ORDER BY seq ASC LIMIT ${r}`).toArray().map(d=>{const T={id:d.id,op:d.op,seq:d.seq,table:d.table,ts:d.ts};return d.doc===null?T:{...T,doc:A(d.doc)}});return{changes:a,cursor:a.at(-1)?.seq??i}},B=(e,o,i)=>{if(i.size===0)return!1;const r=[...i];for(let s=0;s<r.length;s+=f){const a=new Set(r.slice(s,s+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${q(a)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),H=(e,o)=>{if(o.size===0)return!1;let i=l.get(e),r=!1;i===void 0&&(i=S(e),r=!0,l.set(e,i));for(const s of o)if(!i.has(s)&&(r||(i=S(e),r=!0,l.set(e,i),!i.has(s))))return!1;return!0},x=(e,o,i,r)=>{const a=n(e,t`SELECT doc FROM ${t.identifier(c)}
9
+ WHERE ${t.identifier("table")} = ${o} AND id = ${i} AND seq <= ${r}
10
+ ORDER BY seq DESC
11
+ LIMIT 1`).toArray()[0]?.doc;return a==null?void 0:A(a)},W=(e,o,i,r)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(c)}
12
+ WHERE ${t.identifier("table")} = ${o} AND seq > ${i} AND seq <= ${r}
13
+ GROUP BY id
14
+ ORDER BY maxSeq ASC`).toArray().map(a=>{const d=a.op;return{id:a.id,op:d==="insert"&&a.ops>1?"update":d,seq:a.maxSeq}}),Y=(e,o,i)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
15
+ SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${i}
16
+ )`)},P=(e,o,i)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
17
+ SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${i}
18
+ )`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const r=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return r===void 0?void 0:r-1},K=e=>{const i=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof i=="number"?i:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,i)=>new R("CDC_LOG_TRIMMED",`${i==="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}),z=(e,o,i,r)=>new R("CDC_TIMELINE_FORKED",`${i==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${i==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${r===void 0?"":` at epoch ${r}`}`,{data:{cursor:e,...r===void 0?{}:{epoch:r}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,Q=e=>{const i=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE ${u}`).toArray()[0]?.seq??void 0,r=D(e);return i===void 0?r:Math.max(i+1,r??0)},E="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},J=e=>{L(e);const i=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${r})`),r},j=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.table,o.id);return}const i=o.doc??{},r=async()=>{const s={...i};delete s._id,await e.replace(o.table,o.id,s,{allowExplicitId:!0})};if(o.id.includes("\0")&&await e.get(o.table,o.id)!==null){await r();return}try{await e.insert(o.table,i,{allowExplicitId:!0})}catch(s){if(!(s instanceof p))throw s;await r()}},Z=async(e,o)=>{for(const i of o)await h(e,i)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,L as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
@@ -0,0 +1,7 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-RC09zZrh.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
2
+ identity TEXT NOT NULL,
3
+ client_id TEXT NOT NULL,
4
+ last_mutation_id INTEGER NOT NULL,
5
+ PRIMARY KEY (identity, client_id)
6
+ )`)},E=(i,e,n)=>a(i,t`SELECT last_mutation_id FROM ${t.identifier(r)} WHERE identity = ${e} AND client_id = ${n} LIMIT 1`).toArray()[0]?.last_mutation_id??0,l=(i,e,n,d)=>{a(i,t`INSERT INTO ${t.identifier(r)} (identity, client_id, last_mutation_id) VALUES (${e}, ${n}, ${d})
7
+ ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{r as CLIENT_WATERMARK_TABLE,l as advanceClientWatermark,o as migrateClientWatermark,E as readClientWatermark};
@@ -0,0 +1,4 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-RC09zZrh.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
+ id INTEGER PRIMARY KEY CHECK (id = 0),
3
+ value INTEGER NOT NULL
4
+ )`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{decodeWire as O,encodeWire as p}from"@lunora/wire";import{v as _}from"./accepts-null-D1zmJbyR.mjs";import{r as A}from"./json-field-path-DeJW4U9z.mjs";import{SEEK_RANGE as E}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||_(n)},I=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(I.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},T=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",L=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},D=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!L(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=D(c,s,t),{direction:f}=u;l=f,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||T(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,C=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},v=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",z=(e,t)=>{const n=t.map(r=>A(e,r.field)??null);return n.push(e._id),a+C(JSON.stringify(p(n)))},d=()=>new S("INVALID_CURSOR","invalid cursor"),G=e=>{if(!e.startsWith(a))throw d();let t;try{t=O(JSON.parse(v(e.slice(a.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[E]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const f=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?f:{OR:[f,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],X=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},Y=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,$=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,X as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,v as fromBase64,$ as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,Y as softDeleteScope,h as tiebreakDirectionFor,C as toBase64,x as uniqueIndexFields};
@@ -0,0 +1 @@
1
+ import{sql as e}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as f}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as T}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",c=1,g=2,E=i=>i?f(Object.keys(i),i):"",O=(i,t)=>JSON.stringify([c,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),t??""]),$=(i,t)=>JSON.stringify([g,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),t??""]),s=i=>{r(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("signature")} TEXT NOT NULL)`)},u=(i,t)=>{s(i),r(i,t.length===0?e`DELETE FROM ${e.identifier(n)}`:e`DELETE FROM ${e.identifier(n)} WHERE ${T(e.raw('"companion"'),t,!0)}`)},R=(i,t)=>r(i,e`SELECT ${e.identifier("signature")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${t}`).toArray()[0]?.signature,A=(i,t,o)=>{r(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("signature")}) VALUES (${t}, ${o}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("signature")} = excluded.${e.identifier("signature")}`)},N=i=>{s(i),r(i,e`DELETE FROM ${e.identifier(n)}`)};class L{verified=new Set;invalidate(){this.verified.clear()}}export{L as CompanionMemo,O as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,$ as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";class g extends v{constructor(t){super("COUNT_RLS_UNSUPPORTED",t===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${t}" inside an RLS-restricted context`)}}const q=(e,t)=>e?t?{AND:[e,t]}:e:t,O=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),f=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length===1&&t[0]==="eq"?e.eq:d}return e},l=(e,t)=>{const o={};for(const[r,s]of Object.entries(e)){if(O.has(r)||!t(r))return;const n=f(s);if(n===d)return;o[r]=n}return o},a=(e,t)=>{if(!e)return!0;for(const[o,r]of Object.entries(e)){if(!(o in t))return!1;const s=f(r);if((t[o]??null)!==(s??null))return!1}return!0},b=(e,t)=>{const o=e.by??[],r=e.where,n=l(t??{},i=>o.includes(i)||r!==void 0&&i in r);if(n!==void 0){for(const i of o)if(!(i in n))return;return a(r,n)?n:void 0}},x=(e,t,o)=>{const r=e.where,s=l(t??{},n=>o.has(n)||r!==void 0&&n in r);if(!(s===void 0||!a(r,s)))return Object.fromEntries(Object.entries(s).filter(([n])=>o.has(n)))},p=(e,t,o,r)=>{let s;for(const n of e){if(n.op!==t||t!=="count"&&n.field!==o)continue;const i=b(n,r);i&&(!s||(n.by?.length??0)>(s.index.by?.length??0))&&(s={index:n,key:i})}return s},R=(e,t)=>p(e,"count",void 0,t),A=(e,t,o,r)=>p(e,t,o,r),E=(e,t,o,r,s)=>{const n=new Set(r);for(const i of e){if(i.op!==t||t!=="count"&&i.field!==o)continue;const c=i.by??[];if(c.length!==n.size||!c.every(y=>n.has(y)))continue;const u=x(i,s,n);if(u!==void 0)return{index:i,partial:u}}};export{g as CountRlsUnsupportedError,q as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,R as selectIndexForCount,E as selectIndexForGroupBy};
@@ -0,0 +1,31 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"@lunora/wire";import{runSql as E}from"./runDrizzle-RC09zZrh.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ id TEXT PRIMARY KEY,
3
+ direction TEXT NOT NULL,
4
+ status TEXT NOT NULL,
5
+ cursor TEXT,
6
+ processed INTEGER NOT NULL DEFAULT 0,
7
+ changed INTEGER NOT NULL DEFAULT 0,
8
+ started_at REAL,
9
+ updated_at REAL,
10
+ error TEXT
11
+ )`)},b=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),I=(e,t)=>{const r=E(e,`SELECT * FROM "${i}" WHERE id = ?`,t).toArray()[0];if(r)return{...b(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},F=(e,t,a)=>{E(e,`DELETE FROM "${i}"
12
+ WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,a)},O=(e,t)=>{E(e,`INSERT INTO "${i}"
13
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
15
+ ON CONFLICT(id) DO UPDATE SET
16
+ direction = excluded.direction,
17
+ status = excluded.status,
18
+ cursor = excluded.cursor,
19
+ processed = excluded.processed,
20
+ changed = excluded.changed,
21
+ updated_at = excluded.updated_at,
22
+ error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},v=(e,t,a,r)=>(E(e,`INSERT INTO "${i}"
23
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
24
+ VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
25
+ ON CONFLICT(id) DO UPDATE SET
26
+ status = 'in_progress',
27
+ updated_at = excluded.updated_at
28
+ WHERE
29
+ "${i}".status <> 'in_progress'
30
+ OR "${i}".updated_at IS NULL
31
+ OR "${i}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),E(e,"SELECT changes() AS changed").one().changed>0),H=(e,t,a)=>{E(e,`UPDATE "${i}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},P=(e,t)=>{E(e,`UPDATE "${i}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},j=(e,t)=>{if(E(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",i).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",d=t===void 0?[]:[t];return E(e,`SELECT * FROM "${i}"${r}`,...d).toArray().map(n=>({...b(n),error:typeof n.error=="string"?n.error:null,id:n.id,startedAt:typeof n.started_at=="number"?n.started_at:null,updatedAt:typeof n.updated_at=="number"?n.updated_at:null}))},W=[{direction:"asc",field:"_creationTime",nullable:!1}],X=/^~[23]/u,B=e=>{if(typeof e!="string")return e;const t=X.exec(e);return t===null?e:C+e.slice(t[0].length)},Y=async e=>{const{document:t,id:a,onSettled:r,previous:d,table:o,writer:n}=e;try{await n.replace(o,a,t,{allowExplicitId:!0})}catch(f){const p=await n.get(o,a);throw p!==null&&S(p)!==S(d)&&r("changed"),f}r("changed")},G=3,V=async e=>{const{context:t,document:a,dryRun:r,onSettled:d,table:o,transform:n,writer:f}=e,p=String(a._id);let T=a;for(let h=0;h<G;h+=1){const c=await n(T,t);if(c===void 0){d("unchanged");return}if(r){d("changed");return}const u=await f.get(o,p);if(u===null){d("unchanged");return}if(S(u)===S(T)){await Y({document:{...c,_creationTime:T._creationTime,_id:T._id},id:p,onSettled:d,previous:u,table:o,writer:f});return}T=u}throw new x(`data migration could not rewrite row ${p}: it was modified by concurrent traffic on every attempt`,"occ")},J=async e=>{const{migration:t,sql:a,writer:r}=e,d=e.direction??"up",o=e.dryRun??!1,n=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,p=e.batchSize??t.batchSize??M,T=d==="up"?t.up:t.down;if(!T)throw new D("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let c=null,u=0,g=0,A=n();if(!o){$(a);const s=I(a,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:o,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&F(a,t.id,n()-y),!v(a,t.id,d,n())){const R=I(a,t.id);return{changed:R?.changed??0,cursor:R?.cursor??c,direction:R?.direction??d,dryRun:o,id:t.id,processed:R?.processed??0,status:R?.status??"in_progress"}}const l=s?.direction===d?s:void 0;l&&(c=B(l.cursor),u=l.processed,g=l.changed,A=l.startedAt??A)}let _=!1,L=0,N=A;try{for(;!_&&L<f;){const s=await r.findMany(t.table,{cursor:c,includeDeleted:!0,limit:p});for(const m of s.page)if(await V({context:h,document:m,dryRun:o,onSettled:l=>{l==="changed"&&(g+=1),u+=1,c=w(m,W)},table:t.table,transform:T,writer:r}),!o){const l=n();l-N>=U&&(H(a,t.id,l),N=l)}if(c=s.continueCursor,_=s.isDone,L+=1,!o){const m=n();O(a,{changed:g,cursor:_?null:c,direction:d,error:null,id:t.id,processed:u,startedAt:A,status:_?"completed":"in_progress",updatedAt:m}),N=m;try{await e.onBatch?.({batches:L,changed:g,processed:u})}catch{}}}}catch(s){throw o||O(a,{changed:g,cursor:c,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:u,startedAt:A,status:"failed",updatedAt:n()}),s}if(!o&&!_)try{P(a,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:g,cursor:_?null:c,direction:d,dryRun:o,id:t.id,processed:u,status:_?"completed":"in_progress"}};export{i as DATA_MIGRATION_STATE_TABLE,j as readMigrationStatus,J as runDataMigration};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{i as L,R as P}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as O}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as $}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as D,uniqueIndexFields as _,equalityPinnedFields as K,buildSeekWhere as I,decodeCursor as v,buildSeekBeforeWhere as B,softDeleteScope as W,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as S}from"./applyInsertDefaults-CYSHgpFD.mjs";import{RELATION_EXISTS_KEY as F}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const C={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},M=e=>P.has(e)?e:void 0,E=e=>{const t=M(e),r=t===void 0?void 0:C[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},q=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},H=5e3,m=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],j=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>L(e),g=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const i=e[o];return o==="AND"||o==="OR"?p(i).some(s=>g(s,t,r)):o==="NOT"?g(i??{},t,r):!!n[o]&&y(i)})},z=e=>e.through===void 0?[e.table]:[e.table,e.through.table],b=(e,t,r,n,o=new Set)=>{const i=t.tables[r]?.relationMap??{};for(const[s,a]of Object.entries(e??{})){const d=i[s],c=s==="NOT"?[a??{}]:p(a);s==="AND"||s==="OR"||s==="NOT"?c.forEach(l=>b(l,t,r,n,o)):d&&y(a)&&(z(d).filter(l=>!o.has(l)).forEach(l=>{o.add(l),b(n?.(l),t,l,n,o)}),Object.values(a).forEach(l=>b(l,t,d.table,n,o)))}return o},le=(e,t,r,n)=>{if(e&&g(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},Y=async(e,t,r,n)=>{const o=await f(t,e.table,n),{page:i}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return S(i,r)},Q=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},X=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},x=async(e,t,r,n,o)=>{const i=await Y(e,t,r,n);return i.length<=n.maxRelationKeys?i:o?m:Q(e,i.length,n)},A=async(e,t,r,n)=>{const o=await f(t,e.table,n),i=n.maxRelationKeys+1,s=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:i,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>i)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(i)}; the fetcher did not honour the page limit`);for(const c of S(d.page,r))s.add(c);if(s.size>n.maxRelationKeys&&X(e,s.size,n),d.isDone)return[...s];if(typeof d.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},U=async(e,t,r,n,o)=>{const i=E(e),{clause:s,project:a}=q(t),d=await x(t,i.negateChild?{NOT:r}:r,a,n,o);return d===m?m:i.negated?i.nullDisjunct?{OR:[{[s]:{notIn:d}},{[s]:{isNull:!0}}]}:{[s]:{notIn:d}}:{[s]:{in:d}}},V=async(e,t,r,n)=>{const o=E(e),{from:i,table:s,to:a}=t.through,d=await A(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await A({table:s},{[a]:{in:d}},i,n);return{_id:o.negated?{notIn:c}:{in:c}}},T=async(e,t,r,n,o)=>{const i=E(e),s=o.relationBaseWhere?.(t.table),a=i.negateChild?{NOT:r}:r,l={childWhere:await f(s?{AND:[s,a]}:a,t.table,o),negated:i.negated,parentTable:n,relation:t};return{[F]:l}},J=(e,t,r)=>{const n=M(e),o=n===void 0?void 0:C[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},G=async(e,t,r,n,o)=>{const i=[];for(const s of Object.keys(r)){J(s,e,t);const a=r[s]??{};if(t.through!==void 0){i.push(await V(s,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){i.push(await T(s,t,a,n,o));continue}const c=await U(s,t,a,o,d);c===m?i.push(await T(s,t,a,n,o)):i.push(c)}return j(i)},Z=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const i=[];for(const s of p(t))i.push(await f(s,r,n));return{[e]:i}}if(e==="NOT")return{NOT:await f(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?G(e,o,t,r,n):{[e]:t}},f=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Z(o,e[o],t,r));return j(n)},ee=async(e,t)=>!e||!g(e,t.schema,t.tableName)?e:f(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??H,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),N=100,u=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,i)=>o+u(i),0):r==="NOT"?t+=u(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},he=async(e,t,r)=>{const n=D(t.orderBy,e.shape,{pinned:K(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?I(n,v(t.cursor)):void 0,i=typeof t.endCursor=="string"?B(n,v(t.endCursor)):void 0;if(i!==void 0&&u(o)+u(i)>N)throw new h("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(u(o)+u(i))} cursor parameters, and a statement takes at most ${String(N)} — order by fewer fields`);let s=O(t.baseWhere,t.where);s=O(s,W(e.softDeleteMode,t.includeDeleted)),s=await ee(s,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,i])d&&(s=s?{AND:[s,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:s}},ue=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:i}=t,s=n!==void 0&&e.length>n,a=s?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:s&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,i):null,...s?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:s&&d&&o!==!0?R(d,i):null,isDone:!s,page:a}},w=(e,t,r)=>{for(const n of e){const o=k(n,t,r);if(o)return o}},te=(e,t,r,n)=>{if(e==="AND"||e==="OR")return w(p(t),r,n);if(e==="NOT")return w([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const i=o.through===void 0?[o.table]:[o.table,o.through.table],s=i.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const a=i.find(d=>$(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:w(Object.values(t),r,o.table)},k=(e,t,r)=>{for(const n of Object.keys(e)){const o=te(n,e[n],t,r);if(o)return o}},re=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!g(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},fe=(e,t,r)=>{if($(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=k(e,t,r);if(!n){re(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{H as DEFAULT_MAX_RELATION_KEYS,le as assertFlatPredicate,fe as assertShapeShardable,he as composeReadPredicate,g as containsRelationPredicate,ue as findManyPage,y as isRelationPredicate,b as relationPredicateTables,ee as resolveRelationPredicates};
@@ -0,0 +1,8 @@
1
+ import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{b as W,D as I,n as $,s as b,a as A,d as T,p as K,c as H}from"./relay-CKEdfUjH.mjs";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as j,w,a as L,m as X,r as z,b as V,c as J}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{encodeRowsPatch as Q,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Z}from"./stubByName-DQSivmvb.mjs";import{awaitWsDrain as ee,trySendFrame as M}from"./DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{verifySiblingBody as te,RELAY_SIGNATURE_HEADER as C,siblingSecretOf as se,signSiblingBody as re}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const S="__lunora_relay_memos",oe=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ epoch TEXT,
6
+ PRIMARY KEY (connection_id, sub_id)
7
+ )`)},ne=i=>{const e=m(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(S)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ae=4,N=(i,e)=>{const s=Math.floor(B.boundParams/ae);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),n=u.join(r.map(o=>u`(${o.connectionId}, ${o.subId}, ${o.cursor}, ${o.epoch??null})`),u`, `);m(i,u`INSERT INTO ${u.identifier(S)} (connection_id, sub_id, cursor, epoch) VALUES ${n}
8
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ie=(i,e,s)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e} AND sub_id = ${s}`)},le=(i,e)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e}`)},ce=i=>{m(i,u`DELETE FROM ${u.identifier(S)}`)},he=2,de=i=>{const e=i?.LUNORA_WS_BEARER;return typeof e=="string"&&e.length>0},ue=8,ye=2e3,pe=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},pe)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},E={},fe=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},me=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,k=i=>Response.json(i,{headers:{"content-type":"application/json"}}),Se=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Re=new Set(["relay_attach","relay_shape_subscribe"]),_e=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!Se.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Re.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),x=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},ve=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),be=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await te(this.host.env(),e.headers.get(C),s))return new Response("forbidden",{status:403});const t=_e(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,n=r===void 0?void 0:this.host.getWebSockets().find(o=>this.host.readAttachment(o).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,n),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return k(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,n=Date.now(),{delivered:o,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-n),o<a?Response.json({delivered:o,matched:a},{status:503}):f()}case"relay_shape_subscribe":return k(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return fe(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",ue)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}isAdmitted(e){return this.host.readAttachment(e).authenticated!==!1}siblingStub(e){return Z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=be(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=se(this.host.env());o!==void 0&&(n[C]=await re(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:n,method:"POST"})}catch{return}}}class Ee extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recorded;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(n=>this.forwardToRelay(n,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()};let t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();const r=s.action==="reauth"?W(s.connectionId):void 0;if(r!==void 0&&t.has(r)&&(t=new Set([r])),t.size===0)return Promise.resolve(void 0);const n=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(n.map(async o=>{const a=await o;if(a===void 0||a.status===404)throw new Error("relay does not hold the socket");return a})).catch(()=>{}).then(o=>{for(const a of n)x(a,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(n=>this.forwardToRelay(n,{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets(),s=de(this.host.env())?e.filter(o=>this.isAdmitted(o)).length:e.length,t=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",I.tUp),r=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",I.tDown);if(this.promotionState=$(this.promotionState,s,H(t,r)),this.promotionState==="owned")return 0;const n=v(this.host.env(),"LUNORA_RELAY_FAN",he);return Math.min(this.maxRelays(),Math.max(1,n))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=b(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:A(e.relayIndex,e.connectionId,e.subId);for(const[r,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);j(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,n){if(e.table!==void 0&&!t.has(e.table))return;let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0)return;const a=e;if(a.table=o.table,!t.has(o.table))return;const c=a.cursor,l=this.host.buildShapeDiff(o,c,r);if(l.length!==0)return a.cursor=r,w(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:n,fromCursor:c,name:e.name,rowsPatch:Q(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const n=this.host.currentCdcEpoch(),o=[];for(const a of r.values()){const c=this.buildShapePoke(a,E,e,s,n);c&&o.push(this.multicastToRelays(t,c,a))}await Promise.all(o)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>{const{dropped:o,response:a}=await this.requestDroppingIdle(n,s);return o||a?.ok===!0}))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),n=[];for(const o of t.values()){const a=this.buildShapePoke(o,o.identity,e,s,r);a&&n.push(this.proxyToRelay(a,o))}await Promise.all(n)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(h){const{body:p}=Y(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.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:n,epoch:o,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=n;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=b(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:n,key:h,name:e.name,table:t.table},d.set(h,p),L(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=A(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,p),L(this.host.sql(),p)}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=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:o,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,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_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),X(this.host.sql()))}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recorded?.binding&&(this.recorded={binding: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.recorded!==void 0)return this.recorded.binding;try{const s=this.host.sql(),t=s.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__lunora_relay_binding'").toArray().length>0;this.recorded={binding:t?s.exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray()[0]?.binding:void 0}}catch{}return this.recorded?.binding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of z(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}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(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(T(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[n,o]of r)o.relayIndex===e&&r.delete(n);V(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),J(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,E)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),n=_(t.columns);let o=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(o=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[E,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===n})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(T(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let n;const o=new Promise(a=>{n=setTimeout(()=>{a(void 0)},ye)});return Promise.race([r,o]).then(a=>(a===void 0&&x(r,void 0),a)).finally(()=>{clearTimeout(n)})}}class ge extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),o={args:q(t.args??{}),connectionId:n,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,o)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};if(await ee(e),this.host.dropIfLapsed(e))return{code:"IDENTITY_STALE",message:"the socket lapsed before its shape seed was delivered"};for(const l of c.frames)M(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(n=>n!==e&&this.isAdmitted(n))||(this.relayMemos().clear(),ce(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){return!0}refusesAsIdle(){return this.host.getWebSockets().some(e=>this.isAdmitted(e))?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const n=Date.now();for(const[d,R]of this.liveControlSeqs){if(n-R.appliedAt<=ve)break;this.liveControlSeqs.delete(d)}const o=`${s}\0${r}`,a=this.liveControlSeqs.get(o);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:n,seq:t};this.liveControlSeqs.delete(o),this.liveControlSeqs.set(o,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(o)===c&&this.liveControlSeqs.delete(o),l}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},n=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},o=t.then(n,n);return r.chain=o,this.shapeControl.set(e,o),t}relayMemos(){return this.relayMemoCache===void 0&&(oe(this.host.sql()),this.relayMemoCache=ne(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:n,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),le(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ie(this.host.sql(),e,s)}deliverShapePoke(e){const s=b(e.name,e.args),t=[];let r=0,n=0;for(const o of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(o);if(this.host.dropIfLapsed(o)||c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(o,c,this.connectionMemos(a),e,s);n+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:n}}pokeSocketShapes(e,s,t,r,n){const o=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(b(l.name,l.args)!==n||!me(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>M(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),o.push(c),y&&(a+=1)}return{matched:o,sent:a}}}const qe=i=>{const e=i.doName();if(e===void 0)return;const s=K(e);return s===void 0?new Ee(i,e):new ge(i,s.ownerKey,s.relayIndex)};export{ue as DEFAULT_MAX_RELAYS,Ee as OwnerRelay,ge as RelayMember,qe as createRelayLink};
@@ -0,0 +1 @@
1
+ import{D as o,c as s,n as r,p as t,r as y,d as l,a as m,s as n}from"./relay-CKEdfUjH.mjs";export{o as DEFAULT_PROMOTION_THRESHOLDS,s as clampPromotionThresholds,r as nextPromotionState,t as parseRelayName,y as relayCountFor,l as relayName,m as relayProxyKey,n as shapeRoutingKey};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{e as a}from"./estimate-bytes-C-C35VXL.mjs";const o={maxReadBytes:32*1024*1024,maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4},n=.8,h={readBytes:"maxReadBytes",readRows:"maxReadRows",writtenBytes:"maxWrittenBytes",writtenRows:"maxWrittenRows"},w={readBytes:(s,t)=>`this transaction read ${s} bytes, over the ${t}-byte limit`,readRows:(s,t)=>`this transaction read ${s} documents, over the ${t}-document limit`,writtenBytes:(s,t)=>`this transaction wrote ${s} bytes, over the ${t}-byte limit`,writtenRows:(s,t)=>`this transaction wrote ${s} documents, over the ${t}-document limit`};class c{readBytes=0;readRows=0;writtenRows=0;writtenBytes=0;limits;onNearLimit;warned=new Set;chargedDocuments=new Set;constructor(t={},e){this.limits={...o,...t},this.onNearLimit=e}recordRead(t){this.readRows+=t,this.check("readRows",this.readRows)}recordReadBytes(t){this.readBytes+=t,this.check("readBytes",this.readBytes)}recordDocumentRead(t,e){this.chargedDocuments.has(t)||(this.recordReadBytes(e),this.chargedDocuments.add(t))}beginReadWindow(){this.readBytes=0,this.chargedDocuments.clear()}recordWrite(t){const e=a(t);if(e===void 0)throw new r("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");this.writtenRows+=1,this.writtenBytes+=e,this.check("writtenRows",this.writtenRows),this.check("writtenBytes",this.writtenBytes)}headroom(){return{readBytes:this.readBytes,readRows:this.readRows,remainingReadBytes:Math.max(0,this.limits.maxReadBytes-this.readBytes),remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}check(t,e){const i=this.limits[h[t]];if(e>i)throw new r("TRANSACTION_LIMIT_EXCEEDED",w[t](String(e),String(i)));if(e>=i*n&&!this.warned.has(t)){this.warned.add(t);try{this.onNearLimit?.({kind:t,limit:i,used:e})}catch{}}}}export{o as DEFAULT_TRANSACTION_LIMITS,c as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ import{isPlainObject as I,stableStringify as D,encodeWire as $,needsWireEncoding as x}from"@lunora/wire";import{ADMIN_WILDCARD as F,UNVOUCHABLE_DEP as N}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";const E="_id",p="_creationTime",g="page",M=e=>{let t;for(const o of e){const s=o[p];if(typeof s=="number"){if(t!==void 0){if(s<t)return!0;if(s>t)return!1}t=s}}return!1},P=(e,t)=>{const o=t[p];if(typeof o!="number")return e.length;const s=M(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(s?i<o:i>o))return n}return e.length},l="__lunora__",V=e=>{let t;for(const o of e){if(o===F)return l;if(o!==N){if(t!==void 0)return l;t=o}}return t??l},R=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[E];return typeof t=="string"?t:void 0},w=e=>{const t=new Map,o=[];for(const s of e){const n=R(s);if(n===void 0||t.has(n))return;t.set(n,s),o.push(n)}return{byId:t,order:o}},T=(e,t)=>{const o=e.order.filter(n=>t.byId.has(n)),s=t.order.filter(n=>e.byId.has(n));return o.length!==s.length?!1:o.every((n,r)=>s[r]===n)},J=(e,t,o,s)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:o},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${s}}`});return n},k=(e,t,o,s)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(x(i)?$(i):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:o},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${s}}`})}return n},W=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!I(e)||!I(t))return;const o=e[g],s=t[g];if(!Array.isArray(o)||!Array.isArray(s))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==g));if(D(n(e))===D($(n(t))))return{next:s,previous:o}},j=(e,t,o)=>{const s=o.filter(({delta:r})=>r.op==="insert");if(s.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 s){const i=r.row;n.splice(P(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[E]===t.order[i])},v=(e,t,o)=>{let s;try{s=JSON.parse(e)}catch{return}const n=W(s,t);if(n===void 0)return;const r=w(n.previous),i=w(n.next);if(r===void 0||i===void 0||!T(r,i))return;const a=o===""?l:o,d=JSON.stringify(a),c=[...J(r,i,a,d),...k(r,i,a,d)];return j(r,i,c)?c:void 0},O=new WeakMap,B=(e,t,o,s)=>{if(s===void 0)return v(e,t,o);let n=O.get(s);n===void 0&&(n=new Map,O.set(s,n));let r=n.get(o);if(r===void 0&&(r=new Map,n.set(o,r)),r.has(e))return r.get(e);const i=v(e,t,o);return r.set(e,i),i},q=(e,t,o,s)=>{const n=v(e,t,o);if(n!==void 0){if(s!==void 0)for(const{frame:r}of n)s.push(r);return n.map(({delta:r})=>r)}},z=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:o,nextResult:s,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=o===void 0?"":`,"lastMutationId":${String(o)}`,b=f+t,y=`{"type":"data","id":${c},"data":${i}${b}}`,u=r!==void 0&&(n===!0||Array.isArray(s))?B(r,s,d,e.diffKey):void 0;if(u===void 0||u.length===0)return[y];const m=[];let h=0;for(const[L,{frame:_}]of u.entries()){const S=L===u.length-1?b:`${f},"more":true`,A=`{"type":"delta","id":${c},"delta":${_}${S}}`;if(h+=A.length,h>=y.length)return[y];m.push(A)}return m},Q=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:o}=e;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{l as DELTA_PLACEHOLDER_TABLE,Q as awaitWsDrain,V as deltaTableFor,K as subscriptionFrames,q as subscriptionListDeltas,z as trySendFrame};
@@ -0,0 +1 @@
1
+ import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{encodeWire as A}from"@lunora/wire";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-BZYgGE9Y.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
@@ -0,0 +1 @@
1
+ const m="0123456789bcdefghjkmnpqrstuvwxyz",k=9,p=63710088e-1,d=Math.PI/180,f=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],S=f.map((t,n)=>n%2===0?t/2:t),I=.01,C=Math.acos(I)/d,z=2,_=t=>t/p/d,R=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},T=t=>Math.min(Math.max(Math.trunc(t),1),12),b=(t,n)=>{const a=T(n);let s=-90,o=90,e=-180,c=180,r="",g=0,l=0,u=!0;for(;r.length<a;){if(u){const h=(e+c)/2;t.lng>=h?(l=l*2+1,e=h):(l*=2,c=h)}else{const h=(s+o)/2;t.lat>=h?(l=l*2+1,s=h):(l*=2,o=h)}u=!u,g<4?g+=1:(r+=m[l]??"0",g=0,l=0)}return r},v=(t,n)=>Math.min(90,Math.abs(t)+_(n)),j=(t,n)=>{const a=(n.lat-t.lat)*d,s=(n.lng-t.lng)*d,o=t.lat*d,e=n.lat*d,c=Math.sin(a/2)**2+Math.cos(o)*Math.cos(e)*Math.sin(s/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(c)))},y=(t,n)=>{const a=Math.max(Math.cos(v(n,t)*d),I);for(let s=f.length-1;s>=1;s-=1){const o=f[s],e=S[s];if(o!==void 0&&e!==void 0&&o*a>=t&&e>=t)return s}return 1},B={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},P={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},i=(t,n)=>{const a=t.toLowerCase(),s=a.at(-1)??"";let o=a.slice(0,-1);const e=a.length%2===0?0:1;return P[n][e].includes(s)&&o!==""&&(o=i(o,n)),o+(m[B[n][e].indexOf(s)]??"")},q=(t,n,a)=>{const s=Math.min(a,z),{latBands:o,lngSectors:e}=R(s),c=180/o,r=360/e,g=_(n),l=Math.max(-90,t.lat-g),u=Math.min(90,t.lat+g),h=new Set;for(let M=0;M<o;M+=1){const w=-90+M*c;if(w+c<l||w>u)continue;const x=w+c/2;for(let E=0;E<e;E+=1){const L=-180+(E+.5)*r;h.add(b({lat:x,lng:L},s))}}return[...h]},A=(t,n)=>{const a=Math.max(n,1),s=y(a,t.lat);if(v(t.lat,a)>=C)return q(t,a,s);const e=b(t,s),c=i(e,"north"),r=i(e,"south"),g=[e,c,r,i(e,"east"),i(e,"west"),i(c,"east"),i(c,"west"),i(r,"east"),i(r,"west")];return[...new Set(g)]},G=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,D=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),H=t=>{const n=D(t);return A(n,Math.max(j(n,t.ne),1))};export{k as GEO_DEFAULT_PRECISION,D as boundingBoxCenter,H as boundingBoxGeohashes,A as coveringGeohashes,b as encodeGeohash,j as haversineMeters,G as pointInBoundingBox};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-RC09zZrh.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ members TEXT NOT NULL,
5
+ PRIMARY KEY (connection_id, sub_id)
6
+ )`)},b=(n,o,r)=>{const t=i(n,e`SELECT members FROM ${e.identifier(s)} WHERE connection_id = ${o} AND sub_id = ${r} LIMIT 1`).toArray()[0]?.members;if(t!==void 0)try{const a=JSON.parse(t);return a===null||typeof a!="object"?new Map:new Map(Object.entries(a))}catch{return new Map}},_=(n,o,r,c)=>{const t=JSON.stringify(Object.fromEntries(c));if(t.length>E)throw new p("BAD_REQUEST",`global shape snapshot for subscription "${r}" is ${String(t.length)} characters, past the ${String(E)}-character cap for one durable baseline row; narrow the shape with a predicate or an RLS read policy`);i(n,e`INSERT INTO ${e.identifier(s)} (connection_id, sub_id, members) VALUES (${o}, ${r}, ${t})
7
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},h=(n,o,r)=>{i(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${o} AND sub_id = ${r}`)},m=(n,o)=>{i(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${o}`)};export{E as GLOBAL_SHAPE_SNAPSHOT_MAX_CHARS,s as GLOBAL_SHAPE_SNAPSHOT_TABLE,h as deleteGlobalShapeSnapshot,m as deleteGlobalShapeSnapshotsForConnection,T as migrateGlobalShapeSnapshot,b as readGlobalShapeSnapshot,_ as writeGlobalShapeSnapshot};
@@ -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,7 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-RC09zZrh.mjs";const e="__idempotency",T=`${e}_ts`,I=i=>{E(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(e)} (
2
+ identity TEXT NOT NULL,
3
+ mutation_id TEXT NOT NULL,
4
+ result_json TEXT NOT NULL,
5
+ ts REAL NOT NULL,
6
+ PRIMARY KEY (identity, mutation_id)
7
+ )`);try{E(i,t`CREATE INDEX IF NOT EXISTS ${t.identifier(T)} ON ${t.identifier(e)} (ts)`)}catch{}},m=(i,n,r)=>{const o=E(i,t`SELECT result_json, ts FROM ${t.identifier(e)} WHERE identity = ${n} AND mutation_id = ${r} LIMIT 1`).toArray()[0];return o===void 0?void 0:{resultJson:o.result_json,ts:o.ts}},L=(i,n,r,s,o)=>{E(i,t`INSERT OR IGNORE INTO ${t.identifier(e)} (identity, mutation_id, result_json, ts) VALUES (${n}, ${r}, ${s}, ${o})`)},O=(i,n)=>{E(i,t`DELETE FROM ${t.identifier(e)} WHERE ts < ${n}`)};export{e as IDEMPOTENCY_TABLE,T as IDEMPOTENCY_TS_INDEX,I as migrateIdempotency,m as readIdempotent,O as trimIdempotent,L as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{encodeWire as L,decodeWire as $}from"@lunora/wire";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const T="__lunora_import_stage__",d="__lunora_import_session__",c="__lunora_import_manifest__",N=1440*60*1e3,f=3600*1e3,A=600*1e3,P=/^[\w-]{1,64}$/u,D=new Set(["committed","staging"]),C=new Set(["aborting","committed","committing","open"]),a=(t,e)=>new p(t,e,{status:409}),G=t=>{if(typeof t!="string"||!P.test(t))throw new p("BAD_REQUEST","an import session id is 1-64 characters of [A-Za-z0-9_-]",{status:400});return t},I=t=>{n(t,`CREATE TABLE IF NOT EXISTS "${T}" (seq INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT NOT NULL, tbl TEXT NOT NULL, id TEXT, line INTEGER NOT NULL, doc TEXT NOT NULL)`),n(t,`CREATE INDEX IF NOT EXISTS "${T}_by_session" ON "${T}" (session, seq)`),n(t,`CREATE TABLE IF NOT EXISTS "${d}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, generation TEXT NOT NULL, expires_at INTEGER NOT NULL, result TEXT)`),n(t,`CREATE TABLE IF NOT EXISTS "${c}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, expires_at INTEGER NOT NULL, manifest TEXT NOT NULL)`)},O=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0,m=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),M=t=>{let e;try{e=JSON.parse(t)}catch{return}const s=e;if(!(s===null||typeof s!="object"||typeof s.session!="string"||typeof s.generation!="string"||typeof s.state!="string"||!C.has(s.state)||typeof s.expiresAt!="number"||!O(s.batches)||!O(s.pending)||!O(s.rejected)||!O(s.received)||typeof s.globals!="boolean"||typeof s.storage!="boolean"||!m(s.sections)||!m(s.shards)||!m(s.tables)||typeof s.steps!="object"||s.steps===null))return s},_=(t,e)=>{I(t);const s=n(t,`SELECT state, generation, result FROM "${d}" WHERE session = ?`,e).toArray()[0];if(s===void 0)return;if(!D.has(s.state))throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has an unreadable state on this shard`);const o=s.state;return s.result===null?{generation:s.generation,state:o}:{generation:s.generation,result:JSON.parse(s.result),state:o}},g=(t,e)=>{n(t,`DELETE FROM "${T}" WHERE session = ?`,e),n(t,`DELETE FROM "${d}" WHERE session = ?`,e)},B=(t,e)=>{I(t),n(t,`DELETE FROM "${T}" WHERE session IN (SELECT session FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed'))`,e),n(t,`DELETE FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed')`,e);const s=[];for(const o of n(t,`SELECT session, manifest FROM "${c}" WHERE expires_at < ?`,e)){const i=M(o.manifest);i===void 0||i.state==="committing"||(i.state!=="committed"&&_(t,o.session)?.generation===i.generation&&g(t,o.session),n(t,`DELETE FROM "${c}" WHERE session = ?`,o.session),s.push(i))}return s},h=(t,e,s)=>{if(t!==void 0&&t.generation!==s)throw a("IMPORT_SESSION_STALE",`import session "${e}" on this shard belongs to an earlier session of the same id`)},J=(t,e,s,o,i)=>{const r=_(t,e);if(h(r,e,s),r?.state==="committed")throw a("IMPORT_SESSION_COMMITTED",`import session "${e}" is already committed`);n(t,`INSERT INTO "${d}" (session, state, generation, expires_at) VALUES (?, 'staging', ?, ?) ON CONFLICT (session) DO UPDATE SET expires_at = excluded.expires_at`,e,s,i+N);const E={};for(const S of o){const l=S.doc._id;n(t,`INSERT INTO "${T}" (session, tbl, id, line, doc) VALUES (?, ?, ?, ?, ?)`,e,S.table,typeof l=="string"?l:null,S.line,JSON.stringify(L(S.doc))),E[S.table]=(E[S.table]??0)+1}return E},v=(t,e,s)=>{n(t,`UPDATE "${d}" SET expires_at = ? WHERE session = ?`,s+N,e)},Y=(t,e,s)=>{I(t);let o="substr(tbl, 1, 1) <> '$'";s.sections!==void 0&&(o=s.sections.length===0?"0":`tbl IN (${s.sections.map(()=>"?").join(", ")})`);const i=n(t,`SELECT seq, tbl, line, doc FROM "${T}" WHERE session = ? AND seq > ? AND ${o} ORDER BY seq LIMIT ?`,e,s.afterSeq,...s.sections??[],s.limit).toArray();return{rows:i.map(r=>({doc:$(JSON.parse(r.doc)),line:r.line,table:r.tbl})),seq:i.at(-1)?.seq??s.afterSeq}},V=(t,e)=>new Set(n(t,`SELECT id FROM "${T}" WHERE session = ? AND id IS NOT NULL AND substr(tbl, 1, 1) <> '$'`,e).toArray().map(({id:s})=>s)),K=(t,e,s,o,i)=>{n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) <> '$'`,e),n(t,`INSERT INTO "${d}" (session, state, generation, expires_at, result) VALUES (?, 'committed', ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = 'committed', expires_at = excluded.expires_at, result = excluded.result`,e,s,i+N,JSON.stringify(o))},x=(t,e,s)=>{const o=_(t,e);return o!==void 0&&o.generation!==s?!1:(g(t,e),!0)},R=(t,e,s)=>{I(t);const o=n(t,`SELECT manifest FROM "${c}" WHERE session = ?`,e).toArray()[0];if(o===void 0)return;const i=M(o.manifest);if(i===void 0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has a manifest that cannot be read`);return i.state==="open"&&i.expiresAt<s?void 0:i},b=(t,e)=>{n(t,`INSERT INTO "${c}" (session, state, expires_at, manifest) VALUES (?, ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = excluded.state, expires_at = excluded.expires_at, manifest = excluded.manifest`,e.session,e.state,e.expiresAt,JSON.stringify(e))},y=(t,e)=>{const s=(o,i)=>o.localeCompare(i);return[...t].toSorted(s).join(",")===[...e].toSorted(s).join(",")},U=(t,e)=>({batches:0,expiresAt:0,generation:crypto.randomUUID(),globals:!1,pending:0,received:0,rejected:0,sections:[],session:t,shards:[],state:"open",steps:{},storage:!1,tables:[...e]}),k=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0&&!s.begin)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});if(i!==void 0&&i.state!=="open")throw a(i.state==="committed"?"IMPORT_SESSION_COMMITTED":"IMPORT_SESSION_CLOSED",`import session "${e}" is ${i.state==="committed"?"already committed":i.state}`);if(i!==void 0&&!y(i.tables,s.tables))throw new p("IMPORT_SESSION_MISMATCH",`import session "${e}" was opened over other tables`,{status:400});if(i!==void 0&&!s.begin&&i.pending===0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has no staging request in flight to finish`);const r=i??U(e,s.tables),E={...r,batches:r.batches+(s.begin?1:0),expiresAt:o+f,globals:r.globals||s.globals===!0,pending:r.pending+(s.begin?1:-1),received:r.received+(s.received??0),rejected:r.rejected+(s.rejected??0),sections:[...new Set([...r.sections,...s.sections??[]])],shards:[...new Set([...r.shards,...s.shards??[]])],storage:r.storage||s.storage===!0};return b(t,E),{created:i===void 0,manifest:E}},u=(t,e,s,o,i)=>{if(t.steps[e]!==void 0)return a("IMPORT_STEP_DONE",`import session "${t.session}" already ran its ${e} step — send the commit again for its totals`);const r=t.claims?.[e],E=r?.by===s;if(i?!E:r!==void 0&&!E&&r.until>=o)return a("IMPORT_STEP_CLAIMED",`another commit of import session "${t.session}" is running its ${e} step — send the commit again later`)},F=(t,e,s)=>{if(t.state!=="committing")return a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`);if(!("release"in e))return"claim"in e?u(t,e.step,e.claim,s,!1):u(t,e.step,e.claimant,s,!0)},w=(t,e,s)=>"step"in e?F(t,e,s):e.state==="committed"?t.state==="committing"?void 0:a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`):e.state==="aborting"?t.state==="open"||t.state==="aborting"?void 0:a("IMPORT_SESSION_COMMITTING",`import session "${t.session}" is ${t.state} — send the commit again to finish it`):t.state!=="open"?a("IMPORT_SESSION_CLOSED",`import session "${t.session}" is ${t.state}`):t.rejected>0?a("IMPORT_SESSION_REJECTED",`import session "${t.session}" had refused rows or unreachable shards while staging — abort it`):t.pending>0?a("IMPORT_SESSION_INCOMPLETE",`import session "${t.session}" has ${String(t.pending)} staging request(s) that never finished — abort it`):t.batches===e.batches?void 0:a("IMPORT_SESSION_CHANGED",`import session "${t.session}" took another batch after the commit's prepare — commit again`),H=(t,e,s)=>{if(!("step"in e))return{state:e.state};const{[e.step]:o,...i}=t.claims??{};return"claim"in e?{claims:{...i,[e.step]:{by:e.claim,until:s+A}}}:"release"in e?{claims:o===void 0||o.by===e.release?i:{...i,[e.step]:o}}:{claims:i,steps:{...t.steps,[e.step]:e.stepResult}}},z=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});const r=w(i,s,o);if(r!==void 0)throw r;const E={...i,...H(i,s,o),expiresAt:o+f};return b(t,E),v(t,e,o),"state"in s&&s.state==="committed"&&n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) = '$'`,e),E},Q=(t,e,s)=>{const o=R(t,e,s);if(o!==void 0){if(o.state!=="aborting")throw a("IMPORT_SESSION_CLOSED",`import session "${e}" is ${o.state}, not aborting`);x(t,e,o.generation),n(t,`DELETE FROM "${c}" WHERE session = ?`,e)}};export{f as IMPORT_MANIFEST_TTL_MS,N as IMPORT_STAGE_TTL_MS,A as IMPORT_STEP_CLAIM_MS,z as advanceImportManifest,G as assertImportSessionId,Q as dropImportManifest,x as dropImportSession,K as markShardImportCommitted,R as readImportManifest,_ as readShardImportSession,J as stageImportRows,V as stagedImportIds,Y as stagedImportPage,B as sweepImportStaging,k as touchImportManifest,v as touchShardImportSession};
@@ -0,0 +1,18 @@
1
+ import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-RC09zZrh.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
2
+ … [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
3
+ id TEXT PRIMARY KEY,
4
+ captured_at INTEGER NOT NULL,
5
+ from_addr TEXT,
6
+ to_addrs TEXT NOT NULL,
7
+ cc_addrs TEXT,
8
+ bcc_addrs TEXT,
9
+ reply_to TEXT,
10
+ subject TEXT NOT NULL,
11
+ html TEXT,
12
+ body_text TEXT,
13
+ headers TEXT
14
+ )`)},N=(t,r,T)=>{_(t);const E=crypto.randomUUID();return c(t,`INSERT INTO "${e}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
15
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,E,T,o(r.from),JSON.stringify(r.to),s(r.cc),s(r.bcc),o(r.replyTo),r.subject,o(n(r.html)),o(n(r.text)),s(r.headers)),c(t,`DELETE FROM "${e}"
16
+ WHERE id NOT IN (
17
+ SELECT id FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?
18
+ )`,l),{id:E}},u=(t,r={})=>{_(t);const T=Math.min(Math.max(r.limit??50,1),l);return{entries:c(t,`SELECT * FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?`,T).toArray().map(d=>({bcc:a(d.bcc_addrs),capturedAt:d.captured_at,cc:a(d.cc_addrs),from:d.from_addr??void 0,headers:a(d.headers),html:d.html??void 0,id:d.id,replyTo:d.reply_to??void 0,subject:d.subject,text:d.body_text??void 0,to:a(d.to_addrs)??d.to_addrs}))}},M=t=>(_(t),c(t,`DELETE FROM "${e}"`),{cleared:!0});export{l as MAIL_RETENTION,e as MAIL_TABLE,i as MAX_BODY_CHARS,M as clearCapturedMail,_ as ensureMailTable,u as readCapturedMail,N as recordCapturedMail};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as w}from"@lunora/errors";import{ADMIN_TOKEN_TABLE as v}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";const O="x",g=" ",x={'"':'"',"'":"'","[":"]","`":"`"},S=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
2
+ `;)n+=1;return n},L=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},R=e=>{const t=e.split("");let n=0;for(;n<e.length;){const o=e[n]??"",r=x[o];if(o==="-"&&e[n+1]==="-"){const s=S(e,n);t.fill(g,n,s),n=s}else if(o==="/"&&e[n+1]==="*"){const s=L(e,n);if(s===-1)return;t.fill(g,n,s),n=s}else if(r!==void 0){let s=n+1;for(;s<e.length;)if(e[s]!==r)s+=1;else if(r!=="]"&&e[s+1]===r)s+=2;else break;if(s>=e.length)return;t.fill(O,n,s+1),n=s+1}else n+=1}for(let o=0;o<e.length;o+=1)e[o]===`
3
+ `&&(t[o]=`
4
+ `);return t.join("")},f=new Set([v,"dbstat","sqlite_dbpage"]),_="pragma_",C=e=>/[\p{L}_]/u.test(e)||(e.codePointAt(0)??0)>127,T=e=>/[\p{L}\p{N}_$]/u.test(e)||(e.codePointAt(0)??0)>127,b=/^pragma_\w+$/u,y=e=>f.has(e)||b.test(e)?e:void 0,h=e=>{if(f.has(e)||e.startsWith(_))return e},m=(e,t,n)=>{let o="",r=t+1;for(;r<e.length;){const s=e[r];if(s===n){if(n!=="]"&&e[r+1]===n){o+=n,r+=2;continue}return{end:r+1,text:o}}o+=s,r+=1}},E={'"':'"',"`":"`","[":"]"},u=e=>{const t=e.toLowerCase().replaceAll(/["'`[\]]/gu,"");for(const n of f)if(t.includes(n))return n;return/\bpragma_/u.test(t)?_:void 0},I=e=>{let t=0;for(;t<e.length;){const n=e[t];if(/\s/u.test(n))t+=1;else if(n==="-"&&e[t+1]==="-"){const o=e.indexOf(`
5
+ `,t);t=o===-1?e.length:o+1}else if(n==="/"&&e[t+1]==="*"){const o=e.indexOf("*/",t+2);if(o===-1)return u(e.slice(t+2));t=o+2}else if(n==="'"){const o=m(e,t,"'");if(o===void 0)return u(e.slice(t+1));const r=y(o.text.trim().toLowerCase());if(r!==void 0)return r;t=o.end}else if(n in E){const o=m(e,t,E[n]);if(o===void 0)return u(e.slice(t+1));const r=h(o.text.toLowerCase());if(r!==void 0)return r;t=o.end}else if(C(n)){let o=t+1;for(;o<e.length&&T(e[o]);)o+=1;const r=e.slice(t,o).toLowerCase(),s=h(r);if(s!==void 0)return s;t=o}else t+=1}},M=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,Q=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|truncate|update|vacuum)\b|\breplace\b(?!\s*\()/iu,D=/^\w+/u,k=/;\s*$/u,P=/\s/u,$=e=>{let t=0;for(;t<e.length;){const n=e[t];if(n!==void 0&&P.test(n))t+=1;else if(n==="-"&&e[t+1]==="-")t=S(e,t);else if(n==="/"&&e[t+1]==="*"){const o=L(e,t);if(o===-1)break;t=o}else break}return t},A=e=>{const t=$(e),n=e.slice(t).trimEnd();if(n==="")return{code:"SQL_EMPTY",message:"the query is empty"};const r=(R(n)??n).replace(k,""),s=n.slice(0,r.length),i=r.indexOf(";");if(i!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+i};const a="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!M.test(s))return{code:"SQL_NOT_READONLY",length:D.exec(s)?.[0].length??1,message:a,offset:t};const c=Q.exec(s);if(c!==null)return{code:"SQL_NOT_READONLY",length:c[0].length,message:`${a} (\`${c[0].toUpperCase()}\` is not allowed)`,offset:t+c.index};const d=I(s);if(d!==void 0)return{code:"SQL_NOT_READONLY",message:`\`${d}\` is reserved framework storage and cannot be queried`}},U=1e3,p=e=>{const t=[];for(const n of e){if(t.length===U)return{items:t,truncated:!0};t.push(n)}return{items:t,truncated:!1}},Y=e=>{const t=new Map;return e.map(n=>{const o=(t.get(n)??0)+1;return t.set(n,o),o===1?n:`${n}:${String(o)}`})},W=e=>{const t=A(e);if(t!==void 0)throw new w(t.code,t.message,{status:400})},X=(e,t)=>{W(t);const n=e.exec(t),{columnNames:o,raw:r}=n;if(o===void 0||r===void 0){const{items:d,truncated:l}=p(n);return{columns:d.length>0?Object.keys(d[0]):[],rowCount:d.length,rows:d,truncated:l}}const s=Y(o),{items:i,truncated:a}=p(r.call(n)),c=i.map(d=>Object.fromEntries(s.map((l,N)=>[l,d[N]])));return{columns:s,rowCount:c.length,rows:c,truncated:a}},j=/near "([^"]*)": syntax error/iu,B=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,F=(e,t)=>{if(t==="")return{};const n=e.indexOf(t);return n===-1?{}:{length:t.length,offset:n}},G=(e,t)=>{const n=A(t);if(n!==void 0)return{diagnostics:n.code==="SQL_EMPTY"?[]:[{length:n.length,message:n.message,offset:n.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=e.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(i=>{const{detail:a}=i;return typeof a=="string"?a:""}).filter(i=>i!=="")}catch(i){const a=i instanceof Error?i.message:String(i),c=j.exec(a);return{diagnostics:[{...c?F(t,c[1]??""):{},message:a,severity:"error",source:"syntax"}],plan:[]}}const r=[],s=new Set;for(const i of o){const a=B.exec(i);if(a){const c=a[1]??"";s.has(c)||(s.add(c),r.push({message:`full table scan on \`${c}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:r,plan:o}};export{U as MAX_SQL_ROWS,W as assertReadonly,G as lintReadonlySql,X as runReadonlySql};
@@ -0,0 +1 @@
1
+ const f=["de","en","es","fr","it","nl","none","pt"],w=e=>f.includes(e),S="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",v="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",x="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",b="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",j="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",q="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",z="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",E=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),y=/[\u0080-\u{10FFFF}]/u,_=/[\p{L}\p{N}]+/gu,F=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,h=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,C=e=>{if(!h.test(e))return[e];const n=[];let s=0;for(const a of e.matchAll(F)){const r=a.index,i=[...a[0]];if(r>s&&n.push(e.slice(s,r)),s=r+a[0].length,i.length===1){n.push(a[0]);continue}for(let o=0;o+1<i.length;o+=1)n.push(`${String(i[o])}${String(i[o+1])}`)}return s<e.length&&n.push(e.slice(s)),n},g=e=>y.test(e)?e.normalize("NFD").replaceAll(E,"").normalize("NFC").toLowerCase():e.toLowerCase(),u=e=>new Set(g(e).split(" ")),H={de:u(v),en:u(S),es:u(x),fr:u(b),it:u(j),nl:u(q),none:new Set,pt:u(z)},k=3,N=256,m=new Map,$=e=>{const n=e!==void 0&&w(e)?e:"none",s=m.get(n);if(s)return s;const a=H[n],r=o=>{const c=g(o),l=c.match(_)??[],d=(h.test(c)?l.flatMap(t=>C(t)):l).filter(t=>t.length<=N);return a.size===0?d:d.filter(t=>!a.has(t))},i={document:r,profile:`${n}-v${String(k)}`,query:o=>{const c=r(o),l=new Set,d=[];for(let t=c.length-1;t>=0;t-=1){const p=c[t];l.has(p)||(l.add(p),d.push(p))}return d.toReversed()}};return m.set(n,i),i};export{$ as q};