@lunora/shard-engine 1.0.0-alpha.27 → 1.0.0-alpha.28

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 (144) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +1 -0
  4. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
  5. package/dist/packem_shared/AGG_COUNT-DOlqqroz.mjs +1 -0
  6. package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
  7. package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +8 -0
  8. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
  9. package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
  10. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
  11. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
  12. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs +1 -0
  14. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
  15. package/dist/packem_shared/DurableStreamRunner-Bm6KDMBU.mjs +1 -0
  16. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  17. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
  18. package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
  19. package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
  20. package/dist/packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs +2 -0
  21. package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +1 -0
  22. package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
  23. package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
  24. package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
  25. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  26. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
  27. package/dist/packem_shared/ReactiveCache-DfyeaJOA.mjs +1 -0
  28. package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
  29. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
  30. package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
  31. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +7 -0
  32. package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
  33. package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
  34. package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
  35. package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
  36. package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
  37. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  38. package/dist/packem_shared/awaitWsDrain-kSGvAfw1.mjs +1 -0
  39. package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +1 -0
  40. package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
  41. package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
  42. package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +1 -0
  43. package/dist/packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs +1 -0
  44. package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
  45. package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
  46. package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
  47. package/dist/packem_shared/createCompanionSync-zCwaB6wj.mjs +1 -0
  48. package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +1 -0
  49. package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +7 -0
  50. package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
  51. package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +1 -0
  52. package/dist/packem_shared/defineEngineContractSuite-0XtjRA7F.mjs +1 -0
  53. package/dist/packem_shared/diffExternalSource-pozJ4UdZ.mjs +1 -0
  54. package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +1 -0
  55. package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
  56. package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
  57. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  58. package/dist/packem_shared/isSoftDeleted-DcGB0pov.mjs +9 -0
  59. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  60. package/dist/packem_shared/materializeExternalRows-Drn0FGdb.mjs +1 -0
  61. package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
  62. package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
  63. package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
  64. package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +5 -0
  65. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  66. package/dist/packem_shared/selectExpiredIds-_5514W_v.mjs +1 -0
  67. package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +1 -0
  68. package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
  69. package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +1 -0
  70. package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
  71. package/dist/packem_shared/stableStringify-CujpENIO.mjs +1 -0
  72. package/dist/packem_shared/stableWireKey-BYB5GQJa.mjs +1 -0
  73. package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
  74. package/package.json +3 -3
  75. package/dist/packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs +0 -1
  76. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  77. package/dist/packem_shared/AGG_COUNT-CKtq03Go.mjs +0 -1
  78. package/dist/packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs +0 -8
  79. package/dist/packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs +0 -8
  80. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs +0 -7
  81. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  82. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs +0 -31
  83. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs +0 -1
  84. package/dist/packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs +0 -1
  85. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs +0 -1
  86. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs +0 -1
  87. package/dist/packem_shared/DurableStreamRunner-B54Jt9Iu.mjs +0 -1
  88. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  89. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs +0 -7
  90. package/dist/packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs +0 -7
  91. package/dist/packem_shared/MAIL_RETENTION-CzZuX9bd.mjs +0 -18
  92. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  93. package/dist/packem_shared/NotUniqueError-BlrEp5pr.mjs +0 -1
  94. package/dist/packem_shared/QUEUE_TABLE-BX0nopuT.mjs +0 -17
  95. package/dist/packem_shared/RANK_TIEBREAK-BGk411OR.mjs +0 -1
  96. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  97. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
  98. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  99. package/dist/packem_shared/ReactiveCache-D_T10KLy.mjs +0 -1
  100. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  101. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs +0 -6
  102. package/dist/packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs +0 -1
  103. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-pybVwKps.mjs +0 -7
  104. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  105. package/dist/packem_shared/aggregateTableName-DN7gk6uh.mjs +0 -1
  106. package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +0 -19
  107. package/dist/packem_shared/applyOnDelete-crbAzVfE.mjs +0 -1
  108. package/dist/packem_shared/applySelect-5w13bMAR.mjs +0 -1
  109. package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +0 -1
  110. package/dist/packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs +0 -1
  111. package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
  112. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  113. package/dist/packem_shared/buildPokeFrames-DmB-FBeQ.mjs +0 -1
  114. package/dist/packem_shared/buildReprojectionMigration-JUwsTNTB.mjs +0 -1
  115. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  116. package/dist/packem_shared/compileWhereSql-B3hq_v98.mjs +0 -1
  117. package/dist/packem_shared/computeRankPage-BU8LXvQs.mjs +0 -1
  118. package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +0 -1
  119. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  120. package/dist/packem_shared/createReplicaLink-BMNW0SX6.mjs +0 -7
  121. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  122. package/dist/packem_shared/ctx-db-companions-BJlCofon.mjs +0 -1
  123. package/dist/packem_shared/defineEngineContractSuite-ClCoUG6r.mjs +0 -1
  124. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  125. package/dist/packem_shared/do-sql-DKSFK627.mjs +0 -1
  126. package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
  127. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  128. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  129. package/dist/packem_shared/isSoftDeleted-DyEJueIu.mjs +0 -9
  130. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  131. package/dist/packem_shared/materializeExternalRows-C-5TKdc1.mjs +0 -1
  132. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  133. package/dist/packem_shared/param-CYxL68V-.mjs +0 -1
  134. package/dist/packem_shared/runDrizzle-C3n5gJsk.mjs +0 -1
  135. package/dist/packem_shared/runShardMigrations-C1mjoJS4.mjs +0 -5
  136. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  137. package/dist/packem_shared/selectExpiredIds-C4Ry_NxG.mjs +0 -1
  138. package/dist/packem_shared/selectShapeMemberIds-Bkkug6vU.mjs +0 -1
  139. package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
  140. package/dist/packem_shared/sibling-channel-bg9FBL5s.mjs +0 -1
  141. package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
  142. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  143. package/dist/packem_shared/stableWireKey-Diuu1gGc.mjs +0 -1
  144. package/dist/packem_shared/wire-codec-Dh0j-GnY.mjs +0 -1
@@ -1,2 +0,0 @@
1
- import{LunoraError as f}from"@lunora/errors";const d=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,g=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,y=/;\s*$/u,m=/\s/u,p=(s,e)=>{let t=e+2;for(;t<s.length&&s[t]!==`
2
- `;)t+=1;return t},S=(s,e)=>{const t=s.indexOf("*/",e+2);return t===-1?-1:t+2},E=s=>{let e=0;for(;e<s.length;){const t=s[e];if(t!==void 0&&m.test(t))e+=1;else if(t==="-"&&s[e+1]==="-")e=p(s,e);else if(t==="/"&&s[e+1]==="*"){const r=S(s,e);if(r===-1)break;e=r}else break}return e},u=s=>{const e=E(s),t=s.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const r=t.replace(y,""),l=r.indexOf(";");if(l!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+l};const c="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!d.test(r))return{code:"SQL_NOT_READONLY",length:h.exec(r)?.[0].length??1,message:c,offset:e};const n=g.exec(r);if(n!==null)return{code:"SQL_NOT_READONLY",length:n[0].length,message:`${c} (\`${n[0].toUpperCase()}\` is not allowed)`,offset:e+n.index}},i=1e3,L=s=>{const e=u(s);if(e!==void 0)throw new f(e.code,e.message,{status:400})},N=(s,e)=>{L(e);const t=s.exec(e).toArray(),r=t.length>i?t.slice(0,i):t;return{columns:r.length>0?Object.keys(r[0]):[],rowCount:t.length,rows:r,truncated:t.length>i}},x=/near "([^"]*)": syntax error/iu,T=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,A=(s,e)=>{if(e==="")return{};const t=s.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},b=(s,e)=>{const t=u(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let r;try{r=s.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(n=>{const{detail:o}=n;return typeof o=="string"?o:""}).filter(n=>n!=="")}catch(n){const o=n instanceof Error?n.message:String(n),a=x.exec(o);return{diagnostics:[{...a?A(e,a[1]??""):{},message:o,severity:"error",source:"syntax"}],plan:[]}}const l=[],c=new Set;for(const n of r){const o=T.exec(n);if(o){const a=o[1]??"";c.has(a)||(c.add(a),l.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:l,plan:r}};export{i as MAX_SQL_ROWS,L as assertReadonly,b as lintReadonlySql,N as runReadonlySql};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-BJlCofon.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dh0j-GnY.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DN7gk6uh.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{computeRankPage as at}from"./computeRankPage-BU8LXvQs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-DKSFK627.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-BGk411OR.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-crbAzVfE.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-C1mjoJS4.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
@@ -1,17 +0,0 @@
1
- import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-C3n5gJsk.mjs";const s="__lunora_queue_messages",T=500,E=128*1024,i="… [truncated by the dev queue catcher]",m="[unserializable message body]",p=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>E?JSON.stringify(`${t.slice(0,E)}${i}`):t}catch{return JSON.stringify(m)}},g=e=>typeof e=="string"&&(e===m||e.endsWith(i)),o=e=>{d(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
- id TEXT PRIMARY KEY,
3
- captured_at INTEGER NOT NULL,
4
- message_id TEXT NOT NULL,
5
- queue TEXT NOT NULL,
6
- export_name TEXT,
7
- body TEXT NOT NULL,
8
- attempts INTEGER NOT NULL,
9
- outcome TEXT NOT NULL,
10
- error TEXT,
11
- dead_lettered INTEGER NOT NULL,
12
- message_ts INTEGER NOT NULL
13
- )`)},R=(e,t,a)=>{o(e);for(const r of t)d(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
14
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),a,r.messageId,r.queue,u(r.exportName),p(r.body),r.attempts,r.outcome,u(r.error),r.deadLettered===!0?1:0,r.timestamp);return d(e,`DELETE FROM "${s}"
15
- WHERE id NOT IN (
16
- SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
17
- )`,T),{recorded:t.length}},n=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),l=(e,t={})=>{o(e);const a=Math.min(Math.max(t.limit??100,1),T),r=typeof t.queue=="string"&&t.queue.length>0?t.queue:void 0,N=r===void 0?"":"WHERE queue = ?",L=r===void 0?[a]:[r,a];return{entries:d(e,`SELECT * FROM "${s}" ${N} ORDER BY captured_at DESC, id DESC LIMIT ?`,...L).toArray().map(c=>n(c))}},I=(e,t)=>{o(e);const a=d(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,t).toArray()[0];return a===void 0?void 0:n(a)},y=e=>(o(e),d(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,T as QUEUE_RETENTION,s as QUEUE_TABLE,y as clearQueueMessages,o as ensureQueueTable,g as isLossyBody,I as readQueueMessageById,l as readQueueMessages,R as recordQueueMessages};
@@ -1 +0,0 @@
1
- import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-DN7gk6uh.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-BR4UOWoP.mjs";const n=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:n}return r},u=(r,t)=>{if(r.length===0)return"";const o={};for(const s of r.toSorted(c))o[s]=t[s]??null;return JSON.stringify(o)},h="__id__",k=r=>`__sort_k${String(r)}__`,S=(r,t)=>{const o=r.partitionBy??[],s=t??{};for(const e of Object.keys(s))if(e==="AND"||e==="OR"||e==="NOT")return;const i={};for(const e of o)if(e in s){const a=m(s[e]);if(a===n)return;i[e]=a}else if(r.where&&e in r.where)i[e]=r.where[e];else return;return i},d=(r,t)=>`${r}__rank_${t}`,b=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),g=l;export{h as RANK_TIEBREAK,u as encodePartitionKey,g as matchesRankStaticWhere,b as rankKeyFromDoc,d as rankTableName,S as resolveRankPartition,k as sortColumnName};
@@ -1 +0,0 @@
1
- const s="__relationExists";export{s as RELATION_EXISTS_KEY};
@@ -1 +0,0 @@
1
- const t="__lunora_reproject__",o=r=>`${t}${r}`,i=r=>{if(!r.startsWith(t))return;const e=r.slice(t.length);return e===""?void 0:e};export{t as REPROJECTION_MIGRATION_PREFIX,o as reprojectionMigrationId,i as reprojectionMigrationTable};
@@ -1 +0,0 @@
1
- import{LunoraError as w}from"@lunora/errors";const b=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends w{table;constructor(s){super("RLS_REQUIRED",`ctx.db access to "${s}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=s}}const g=o=>Object.entries(o.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s),k=(o,s,u)=>{const l=s?.tables,r=new Set(s?.exclude);for(const d of o)(l===void 0||l.includes(d))&&!r.has(d)&&u(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],S=(o,s,u,l)=>{if(s.rlsMode!=="required")return o;const r=o,d=e=>{const t=s.tables[e];return t!==void 0&&t.isPublic!==!0},n=e=>{if(d(e))throw new R(e)},c=async(e,t)=>{if(t!==void 0){n(t);return}const a=await u(e);a!==void 0&&n(a)},h=async(e,t)=>{if(t!==void 0){n(t);return}if(!l){for(const i of e)await c(i,t);return}const a=await l([...new Set(e)],t);for(const i of e){const y=a.get(i);y!==void 0&&n(y)}},p={...o,[b]:o,delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await h(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(n(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await c(e,t),r.get(e,t)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a)=>(await c(e,a),r.patch(e,t,a)),patchMany:async(e,t,a)=>(await h(e.map(i=>i.id),a),r.patchMany(e,t,a)),patchWhere:r.patchWhere?async(e,t,a)=>(n(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,i)=>(await c(e,a),r.replace(e,t,a,i)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))},f=r;for(const e of m){const t=f[e];typeof t=="function"&&(p[e]=(a,...i)=>(n(a),t.call(r,a,...i)))}if(r.wipeShard){const{wipeShard:e}=r;p.wipeShard=t=>(k(g(s),t,n),e.call(r,t))}return p};export{b as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,S as guardWriter};
@@ -1 +0,0 @@
1
- import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";import{depKey as l,SCAN_DEP as f}from"./SCAN_DEP-D_yR9EeV.mjs";import{o as m}from"./estimate-bytes-Drp8rhPs.mjs";import{keysTouchRanges as u}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const c=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},x=1e3,g=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??x,this.maxBytes=t.maxBytes??g,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const r=await s(),h=m(r);if(h===void 0)return r;const d=i(),b={bytes:h,deps:e,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of e)c(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const y=c(this.rangeIndex,a.table,()=>new Map);c(y,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,e,s){const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,f),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)u([n],e)&&this.dropKeys(r,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),n=i?.get(s);n?.delete(t),i&&n?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const E=(o,t,e)=>`${e??"\0anon"}\0${o}:${p(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,p as stableWireKey};
@@ -1 +0,0 @@
1
- const t="*scan",n=(e,r)=>`${e}:${r}`,d=e=>{const r=e.indexOf(":");return r===-1?e:e.slice(0,r)},o=()=>{const e=new Set;return{collect(){return e},recordRead(r,c){e.add(n(r,c))}}};export{t as SCAN_DEP,o as createDependencyTracker,n as depKey,d as tableFromDepKey};
@@ -1,6 +0,0 @@
1
- import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-C3n5gJsk.mjs";const i="__lunora_schema_history",R=50,a=T(i),n=s=>({appliedAt:typeof s.applied_at=="number"?s.applied_at:0,hash:typeof s.hash=="string"?s.hash:"",seq:typeof s.seq=="number"?s.seq:0}),h=s=>{e(s,`CREATE TABLE IF NOT EXISTS ${a} (
2
- hash TEXT PRIMARY KEY,
3
- seq INTEGER NOT NULL,
4
- snapshot_json TEXT NOT NULL,
5
- applied_at INTEGER NOT NULL
6
- )`)},S=s=>{e(s,`DELETE FROM ${a} WHERE hash NOT IN (SELECT hash FROM ${a} ORDER BY seq DESC LIMIT ?)`,R)},L=(s,t,r,o=Date.now())=>{if(t===""||r==="")return!1;try{if(h(s),e(s,`SELECT hash FROM ${a} WHERE hash = ? LIMIT 1`,t).toArray().length>0)return!1;const[E]=e(s,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${a}`).toArray(),p=typeof E?.next=="number"?E.next:1;return e(s,`INSERT INTO ${a} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,t,p,r,o),S(s),!0}catch{return!1}},N=s=>{try{return h(s),e(s,`SELECT hash, seq, applied_at FROM ${a} ORDER BY seq DESC`).toArray().map(t=>n(t))}catch{return[]}},_=(s,t)=>{try{h(s);const[r]=e(s,`SELECT hash, seq, applied_at, snapshot_json FROM ${a} WHERE hash = ? LIMIT 1`,t).toArray();return r===void 0?void 0:{...n(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{R as SCHEMA_HISTORY_MAX_VERSIONS,N as readSchemaHistory,_ as readSchemaVersion,L as recordSchemaVersion};
@@ -1 +0,0 @@
1
- import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const o="__lunora_search_state",a=e=>{n(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(o)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{n(e,i`ALTER TABLE ${i.identifier(o)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},c=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=n(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(o)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,t,r,d,f)=>{const $=r??null;n(e,i`INSERT INTO ${i.identifier(o)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{o as SEARCH_STATE_TABLE,a as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
@@ -1,7 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const E="__shape_poke_cursor",T=i=>{n(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(E)} (
2
- connection_id TEXT NOT NULL,
3
- sub_id TEXT NOT NULL,
4
- cursor INTEGER NOT NULL,
5
- PRIMARY KEY (connection_id, sub_id)
6
- )`)},t=(i,o,r)=>n(i,e`SELECT cursor FROM ${e.identifier(E)} WHERE connection_id = ${o} AND sub_id = ${r} LIMIT 1`).toArray()[0]?.cursor,u=(i,o,r,s)=>{n(i,e`INSERT INTO ${e.identifier(E)} (connection_id, sub_id, cursor) VALUES (${o}, ${r}, ${s})
7
- ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=(i,o,r)=>{n(i,e`DELETE FROM ${e.identifier(E)} WHERE connection_id = ${o} AND sub_id = ${r}`)},a=(i,o)=>{n(i,e`DELETE FROM ${e.identifier(E)} WHERE connection_id = ${o}`)};export{E as SHAPE_POKE_CURSOR_TABLE,_ as deleteShapePokeCursor,a as deleteShapePokeCursorsForConnection,T as migrateShapePokeCursor,t as readShapePokeCursor,u as writeShapePokeCursor};
@@ -1 +0,0 @@
1
- class r{shardHost;socketHost;options;constructor(s,t,e={}){this.shardHost=s,this.socketHost=t,this.options=e}get shardKey(){return this.shardHost.shardKey}socketFor(s){return this.socketHost.handleFor(s)??s}sockets(s){return this.socketHost.getSockets(s)}background(s){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(s),!0)}async runInTransaction(s){return this.shardHost.runSerialized(async()=>this.shardHost.transaction(s))}async handleFetch(s){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(s):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{r as ShardRunner};
@@ -1 +0,0 @@
1
- import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-Dh0j-GnY.mjs";const n=BigInt(Number.MAX_SAFE_INTEGER),i=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,c=e=>{if(typeof e=="bigint"){if(e>n||e<-n)throw new l("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},d=(e,t,o,u)=>{const r=e.get(t)??{count:0,value:null};if(o.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const a=c(u[o.field??""]);if(o.op==="sum"||o.op==="avg"){a!==void 0&&(r.value=(r.value??0)+a,r.count+=1),e.set(t,r);return}r.count+=1,a!==void 0&&(r.value===null?r.value=a:r.value=o.op==="min"?Math.min(r.value,a):Math.max(r.value,a)),e.set(t,r)},f=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,p=(e,t)=>{if(e.length===0)return"";const o={};for(const u of e.toSorted(i))o[u]=t[u]??null;return JSON.stringify(g(o))};export{s as aggregateTableName,c as coerceAggregateNumber,i as compareStrings,p as encodeAggregateKey,d as foldAggregateTally,f as readAggregateValue};
@@ -1,19 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-C3n5gJsk.mjs";const n="__stream_runs",T="__stream_chunks",L=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (
2
- run_key TEXT PRIMARY KEY,
3
- status TEXT NOT NULL,
4
- last_seq INTEGER NOT NULL DEFAULT 0,
5
- error_code TEXT,
6
- error TEXT,
7
- started_at REAL NOT NULL,
8
- ttl_ms REAL NOT NULL
9
- )`),E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T)} (
10
- run_key TEXT NOT NULL,
11
- seq INTEGER NOT NULL,
12
- data_json TEXT NOT NULL,
13
- PRIMARY KEY (run_key, seq)
14
- )`)},d=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(n)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},$=(r,t,s,a)=>d(r,t)!==void 0?!1:(E(r,e`INSERT INTO ${e.identifier(n)} (run_key, status, last_seq, started_at, ttl_ms)
15
- VALUES (${t}, ${"running"}, 0, ${s}, ${a})`),!0),N=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key = ${t}`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE run_key = ${t}`)},S=(r,t,s,a)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(T)} (run_key, seq, data_json) VALUES (${t}, ${s}, ${a})`)},l=(r,t,s)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(T)} WHERE run_key = ${t} AND seq > ${s} ORDER BY seq ASC`).toArray().map(a=>({dataJson:a.data_json,seq:a.seq})),m=(r,t,s,a,i)=>{const _=i?.code??null,R=i?.message??null;E(r,e`UPDATE ${e.identifier(n)}
16
- SET status = ${s}, last_seq = ${a}, error_code = ${_}, error = ${R}
17
- WHERE run_key = ${t}`)},A=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key IN (
18
- SELECT run_key FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}
19
- )`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}`)};export{T as STREAM_CHUNKS_TABLE,n as STREAM_RUNS_TABLE,S as appendStreamChunk,$ as claimStreamRun,N as deleteStreamRun,m as finishStreamRun,L as migrateDurableStreams,l as readStreamChunks,d as readStreamRun,A as trimStreamRuns};
@@ -1 +0,0 @@
1
- import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-5w13bMAR.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?A(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},R=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new B("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new B("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=R(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=R(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],D=w.get(h);D?D.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},v=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=R(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await v(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},I=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new B("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,R as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-Dh0j-GnY.mjs";const g="id",y=new Set(["_id","id"]),C=r=>{const e=[];for(const o of r??[])for(const[t,i]of Object.entries(o))e.push({direction:i,field:t});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},w=r=>{const e=new TextEncoder().encode(r);let o="";for(const t of e)o+=String.fromCodePoint(t);return btoa(o)},b=r=>{const e=atob(r),o=Uint8Array.from(e,t=>t.codePointAt(0)??0);return new TextDecoder().decode(o)},D=(r,e)=>{const o=e.map(t=>r[t.field]);return o.push(r._id),w(JSON.stringify(S(o)))},a=()=>new h("BAD_REQUEST","invalid cursor"),E=r=>{let e;try{e=m(JSON.parse(b(r)))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(r,e,o)=>{const t=r.some(s=>y.has(s.field))?r:[...r,{direction:"asc",field:g}],i=[];for(const[s,n]of t.entries()){const c=[];for(const[u,p]of t.slice(0,s).entries())c.push({[p.field]:{eq:e[u]}});const l=o(n.direction,s===t.length-1);c.push({[n.field]:{[l]:e[s]}});const[d]=c;i.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:i}},T=(r,e)=>f(r,e,o=>o==="desc"?"lt":"gt"),v=(r,e)=>r==="desc"?e?"gte":"gt":e?"lte":"lt",k=(r,e)=>f(r,e,v),A=["_id","_creationTime"],B=(r,e,o)=>{if(!e)return r;const t=new Set([...e,...A,...o?Object.keys(o):[]]);return r.map(i=>{const s={};for(const n of t)n in i&&(s[n]=i[n]);return s})},N=(r,e)=>r&&e!==!0?{[r.field]:{isNull:!0}}:void 0,x=(r,e)=>e===void 0||r[e]===null||r[e]===void 0;export{B as applySelect,k as buildSeekBeforeWhere,T as buildSeekWhere,E as decodeCursor,D as encodeCursor,b as fromBase64,a as invalidCursor,x as isLiveForCompanion,C as normalizeOrderKeys,N as softDeleteScope,w as toBase64};
@@ -1 +0,0 @@
1
- import{stableStringify as v}from"./stableStringify-BjLh4gvA.mjs";import{A as m,a as A}from"./wire-codec-Dh0j-GnY.mjs";const S="_id",p="_creationTime",y="page",O=r=>{let t;for(const s of r){const n=s[p];if(typeof n=="number"){if(t!==void 0){if(n<t)return!0;if(n>t)return!1}t=n}}return!1},w=(r,t)=>{const s=t[p];if(typeof s!="number")return r.length;const n=O(r);for(const[o,e]of r.entries()){const i=e[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return r.length},x="__lunora__",N=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[S];return typeof t=="string"?t:void 0},$=r=>{const t=new Map,s=[];for(const n of r){const o=N(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},_=(r,t)=>{const s=r.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>r.byId.has(o));return s.length!==n.length?!1:s.every((o,e)=>n[e]===o)},k=(r,t,s,n)=>{const o=[];for(const e of r.order)t.byId.has(e)||o.push({delta:{key:e,op:"delete",table:s},frame:`{"key":${JSON.stringify(e)},"op":"delete","table":${n}}`});return o},D=(r,t,s,n)=>{const o=[];for(const e of t.order){const i=t.byId.get(e),a=r.byId.get(e),u=JSON.stringify(A(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";o.push({delta:{key:e,op:d,row:i,table:s},frame:`{"key":${JSON.stringify(e)},"op":"${d}","row":${u},"table":${n}}`})}return o},M=(r,t)=>{if(Array.isArray(r)&&Array.isArray(t))return{next:t,previous:r};if(!m(r)||!m(t))return;const s=r[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=e=>Object.fromEntries(Object.entries(e).filter(([i])=>i!==y));if(v(o(r))===v(A(o(t))))return{next:n,previous:s}},j=(r,t,s)=>{const n=s.filter(({delta:e})=>e.op==="insert");if(n.length===0)return!0;const o=r.order.filter(e=>t.byId.has(e)).map(e=>r.byId.get(e));for(const{delta:e}of n){const i=e.row;o.splice(w(o,i),0,i)}return o.length===t.order.length&&o.every((e,i)=>e[S]===t.order[i])},I=(r,t,s)=>{let n;try{n=JSON.parse(r)}catch{return}const o=M(n,t);if(o===void 0)return;const e=$(o.previous),i=$(o.next);if(e===void 0||i===void 0||!_(e,i))return;const a=s===""?x:s,u=JSON.stringify(a),f=[...k(e,i,a,u),...D(e,i,a,u)];return j(e,i,f)?f:void 0},P=(r,t,s,n)=>{const o=I(r,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:e}of o)n.push(e);return o.map(({delta:e})=>e)}},T=(r,t)=>{try{return r.send(t),!0}catch{return!1}},E=r=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:e,snapshotJson:i,subId:a,table:u}=r,f=JSON.stringify(a),d=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,c=`{"type":"data","id":${f},"data":${i}${d}}`,l=e!==void 0&&(o===!0||Array.isArray(n))?I(e,n,u):void 0;if(l===void 0||l.length===0)return[c];const b=[];let g=0;for(const{frame:J}of l){const h=`{"type":"delta","id":${f},"delta":${J}${d}}`;if(g+=h.length,g>=c.length)return[c];b.push(h)}return b},R=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=r;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{R as awaitWsDrain,E as subscriptionFrames,P as subscriptionListDeltas,T as trySendFrame};
@@ -1 +0,0 @@
1
- import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DN7gk6uh.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as d}from"./runDrizzle-C3n5gJsk.mjs";import{C as T,E as p,c as v,p as B,T as W,a as E,D as j}from"./do-sql-DKSFK627.mjs";import{isLiveForCompanion as _}from"./applySelect-5w13bMAR.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
@@ -1 +0,0 @@
1
- const e=n=>{let r="";for(let t=0;t<n.length;t+=32768)r+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(r)},a=n=>{const r=atob(n),t=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)t[o]=r.codePointAt(o)??0;return t};export{e as a,a as o};
@@ -1 +0,0 @@
1
- const v=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let r=o.getUint32(0,!1),e=o.getUint32(4,!1);return(r&2147483648)===0?r=(r^2147483648)>>>0:(r=~r>>>0,e=~e>>>0),r.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},g=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},c=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${v(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${g(t)}`},d=t=>{const o=[];for(const r of t){const e=c(r);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),h=(t,o,r,e)=>{const i=o.comparator==="=",n=p.has(o.comparator)||x.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},w=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,a){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},f=(t,o)=>{const r=c(o);if(r!==void 0)return t===""?r:t+"!"+r},y=(t,o,r,e,i)=>{if(r.length===0)return;const n=w(r,e,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"￿";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"!￿":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+"￿"}if(!(a>=l))return{hi:l,index:o,lo:a,table:t}},E=(t,o,r)=>{const e=[];for(const i of t){const n=d(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},m=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>m(e,n))})};export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,m as rangeContains};
@@ -1 +0,0 @@
1
- import{a as u}from"./wire-codec-Dh0j-GnY.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
@@ -1 +0,0 @@
1
- import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-Dh0j-GnY.mjs";import{runSql as p}from"./runDrizzle-C3n5gJsk.mjs";import{L as E,a as g}from"./do-sql-DKSFK627.mjs";import{y as b}from"./sql-projection-jfoe331H.mjs";const R=m(0n)[0],l=t=>t.shardMode?.kind==="global"?[]:Object.entries(t.shape).filter(([,r])=>b(r)).map(([r])=>r),T=t=>Object.entries(t.tables).filter(([,r])=>l(r).length>0).map(([r])=>r),f=t=>{const r=`json_each(${_(g)}) AS __f__`;return{params:[JSON.stringify(t),R,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},M=(t,r,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=f(o);return p(t,`SELECT COUNT(*) AS count FROM ${_(r)} WHERE ${n}`,...e).toArray()[0]?.count??0},$=(t,r,o,e)=>{const{params:n,sql:i}=f(o);return p(t,`SELECT 1 FROM ${_(r)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},N=(t,r,o)=>{const e=u(t);if(e===void 0)return;const n=r.tables[e];if(!n)return;const i=l(n);if(i.length!==0)return{id:t,table:e,up:a=>{const s=a._id;if(!(typeof s!="string"||!$(o,e,i,s))){try{E(a)}catch(c){console.warn(`${t}: skipping row ${s} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return a}}}};export{L as REPROJECTION_MIGRATION_PREFIX,N as buildReprojectionMigration,M as countLegacyRows,l as reprojectableFields,C as reprojectionMigrationId,T as reprojectionTables};
@@ -1 +0,0 @@
1
- const u=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,c=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],l=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,f=n=>u.test(n),g=n=>{const e=t=>typeof n[t]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},m=n=>{const e=i=>i.map(a=>n[a]).find(a=>typeof a=="string"&&a!==""),t={},o=e(d),s=e(l);o!==void 0&&(t.workerUrl=o),s!==void 0&&(t.environment=s);const r=n.CF_VERSION_METADATA;if(r!==null&&typeof r=="object"){const i=r;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},v=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,y=n=>{const e=n??{};for(const t of l){const o=e[t];if(typeof o=="string"&&v.test(o))return!0}return!1},E=n=>{const e=n??{},t=[];for(const[o,s]of Object.entries(e))if(!c.has(o)){if(typeof s=="string"){const r=f(o);t.push({kind:r?"secret":"var",name:o,value:p(s)});continue}if(typeof s=="number"||typeof s=="boolean"){t.push({kind:"var",name:o,value:String(s)});continue}if(s!==null&&typeof s=="object"){t.push({bindingType:g(s),kind:"binding",name:o,value:null});continue}t.push({kind:"var",name:o,value:null})}return t.sort((o,s)=>o.name.localeCompare(s.name)),{deploy:m(e),settings:t}};export{g as bindingType,E as buildSettings,y as isDevEnvironment,f as looksSecret,m as readDeployInfo,p as redact};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{sqliteInList as N,WORKERD_SQLITE_LIMITS as p}from"./param-CYxL68V-.mjs";import{RELATION_EXISTS_KEY as I}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const h=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],O=new Set(h),T={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>O.has(t))},y=(r,e,t)=>{const s=o`${t.serialize(e)}`;return t.containsExpr?t.containsExpr(r,s):o`instr(lower(${r}), lower(${s})) > 0`},S=(r,e,t,s,i)=>s===null?e==="ne"?o`${r} IS NOT NULL`:o`${r} IS NULL`:o`${r} ${o.raw(t)} ${i.serialize(s)}`,m=(r,e,t,s)=>{const i=Array.isArray(t)?t:[];if(i.length===0)return e==="IN"?o`0 = 1`:o`1 = 1`;const n=i.map(a=>s.serialize(a)),l=e==="NOT IN";return(s.inList??N)(r,n,l)},U=(r,e,t)=>{const s=o.join(e.map(i=>o`${i}`),o`, `);return t?o`${r} NOT IN (${s})`:o`${r} IN (${s})`},A=(r,e,t)=>{const s=e,i=[];for(const n of h){if(!(n in s))continue;const l=s[n],a=T[n];a?i.push(S(r,n,a,l,t)):n==="isNull"?i.push(l?o`${r} IS NULL`:o`${r} IS NOT NULL`):n==="contains"?i.push(y(r,l,t)):i.push(m(r,n==="in"?"IN":"NOT IN",l,t))}return i},E=(r,e,t)=>{const s=t.fieldRef(r);return L(e)?A(s,e,t):e===null?[o`${s} IS NULL`]:[o`${s} = ${t.serialize(e)}`]},u=(r,e)=>{if(r.length<=1)return r[0];const t=Math.floor(r.length/2);return o`(${u(r.slice(0,t),e)}) ${o.raw(e)} (${u(r.slice(t),e)})`},g=(r,e,t)=>{const s=Array.isArray(r)?r:[],i=[];for(const n of s){const l=c(n??{},t);l&&i.push(l)}return i.length===0?e==="OR"?o`0 = 1`:void 0:u(i,e)},w=new Set(["AND","NOT","OR",I]),R=(r,e,t)=>{if(r===I){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const s=c(e??{},t);return s?o`NOT (${s})`:void 0}return g(e,r,t)},c=(r,e)=>{const t=[];for(const[s,i]of Object.entries(r))if(w.has(s)){const n=R(s,i,e);n&&t.push(n)}else t.push(...E(s,i,e));return u(t,"AND")},b=p.boundParams/2,f=r=>{if(Array.isArray(r))return r.reduce((t,s)=>t+f(s),0);if(r===null||typeof r!="object")return 0;let e=0;for(const[t,s]of Object.entries(r))t==="in"||t==="notIn"?e+=1:(t==="AND"||t==="NOT"||t==="OR"||L(s))&&(e+=f(s));return e},k=(r,e)=>{if(!r||Object.keys(r).length===0)return;const t=e.inList??N,s=f(r);if(s===0)return c(r,e);const i=Math.max(1,Math.floor(b/s));return c(r,{...e,inList:(n,l,a)=>t(n,l,a,i)})};export{k as compileWhereSql,U as literalInList};
@@ -1 +0,0 @@
1
- import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,f)=>{if(n?.length!==1+o.length+1)return;const r=[{column:"__partition__",direction:"asc"}];for(const[s,a]of o.entries())r.push({column:a,direction:f[s]?.direction??"asc"});r.push({column:m,direction:"asc"});const e=[];for(const[s,a]of r.entries()){const c=[];for(const[i,l]of r.slice(0,s).entries())c.push(t`${t.identifier(l.column)} IS ${n[i]}`);c.push(t`${t.identifier(a.column)} ${t.raw(a.direction==="desc"?"<":">")} ${n[s]}`);const[p]=c;e.push(c.length===1&&p!==void 0?p:t`(${t.join(c,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const f=[n.__partition__,...o.map(r=>n[r]),n[m]];return G(f)},U=(n,o,f)=>{const r=[];for(const e of n){const s=e[m];if(typeof s!="string")continue;const a=o.get(s);if(!a)continue;const c=typeof e.__partition__=="string"?e.__partition__:"",p=f.map(i=>e[i]??null);r.push({doc:a,key:{partitionKey:c,rowId:s,sortValues:p}})}return r},tt=t`${t.identifier("id")}`,nt=(n,o,f)=>{const{rowToDocument:r}=n,e=new Map;if(f.length===0)return e;const s=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE ${O(tt,f,!1)}`).toArray();for(const a of s){const c=r(a),p=a.id;c&&typeof p=="string"&&e.set(p,c)}return e},pt=(n,o,f,r)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:a,schema:c}=n,p=c.tables[o];if(!p)throw new N("INTERNAL",`unknown table: ${o}`);const i=p.rankIndexes?.find(u=>u.name===f);if(!i)throw new N("INTERNAL",`unknown rankIndex "${f}" on table "${o}"`);e(o,p,i),a(o,x),s(o,i);const l=V(o,i.name),d=i.sortBy.map((u,w)=>F(w)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),S=v(r.baseWhere,r.where),R=H(i,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[u,w]of d.entries()){const q=i.sortBy[u]?.direction;h.push(t`${t.identifier(w)} ${t.raw(q==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof r.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${r.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(i.partitionBy??[],R)}`);const T=X(r),k=Z(T,d,i.sortBy);k&&_.push(k);const I=t.identifier(m),A=t.identifier("__partition__"),L=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,M=d.length>0?t`${I}, ${A}, ${t.join(d.map(u=>t.identifier(u)),t`, `)}`:t`${I}, ${A}`,D=t`SELECT ${M} FROM ${t.identifier(l)}${L} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String($+1))}`,y=B(n.sql,D).toArray(),g=y.length>$,E=g?y.slice(0,$):y,K=E.map(u=>u[m]),b=U(E,nt(n,o,K),d),P=g?Q(E.at(-1),d):C,j=i.sortBy.map(u=>u.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:j,hasMore:g,rows:b}};export{pt as computeRankPage,nt as hydrateDocsById};
@@ -1 +0,0 @@
1
- import{S as C,W as R,B as f}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DN7gk6uh.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./do-sql-DKSFK627.mjs";import"./param-CYxL68V-.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-5w13bMAR.mjs";import"./RANK_TIEBREAK-BGk411OR.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,f as rankColumnsSql};
@@ -1 +0,0 @@
1
- const d=()=>{const a=new Set,t=new Map,n=new Set;return{onRead(e){a.add(e),n.add(e)},onReadRange(e){a.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of n)t.delete(e);return t.size>0?t:void 0},tables:a}};export{d as createReadFootprint};
@@ -1,7 +0,0 @@
1
- import{f as S,g,u as f,l as q,s as w,o as _}from"./sibling-channel-bg9FBL5s.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=t=>typeof t=="string"&&N.has(t),u="::replica::",v=t=>{const e=t.lastIndexOf(u);if(e===-1)return;const s=t.slice(0,e),r=t.slice(e+u.length);if(!(s.length===0||!T(r)))return{ownerKey:s,region:r}},L=t=>{if(t==null||!/^\d+$/.test(t))return;const e=Number.parseInt(t,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,y=1e3,C=10,m=5e4,b=t=>f(t,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",m),h="__replica_state",l=new WeakSet,E=t=>{l.has(t)||(t.exec(`CREATE TABLE IF NOT EXISTS ${h} (
2
- id INTEGER PRIMARY KEY CHECK (id = 1),
3
- epoch TEXT NOT NULL,
4
- applied_seq INTEGER NOT NULL,
5
- synced_at REAL NOT NULL
6
- )`),l.add(t))},c=t=>(E(t),t.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${h} WHERE id = 1`).toArray()[0]),d=(t,e)=>{E(t),t.exec(`INSERT INTO ${h} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
- ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},F=t=>{const e=t.doName();if(e!==void 0&&v(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(t.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(w(t.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},U=async(t,e)=>{const s=F(t);if(s!==void 0)return s;const r=t.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await S(t.env(),e.headers.get(g),i))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap"){if(t.rowCount()>b(t.env()))return Response.json({cursor:0,epoch:r,rows:[],truncated:!0});const a=t.ownerCursor()??0,o=await t.exportRows();return Response.json({cursor:a,epoch:r,rows:o})}if(n.type==="replica_pull"){const a=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0,{changes:o,cursor:R}=t.readChanges(a,y),p=t.ownerFloor();return Response.json({changes:o,cursor:R,epoch:r,...p===void 0?{}:{floor:p}})}return new Response("unknown replica frame",{status:400})};class I{constructor(e,s,r){this.host=e,this.ownerKey=s,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const s=await this.inFlight;return s==="fresh"&&!this.isCaughtUp(e)?"stale":s}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let s=c(this.host.sql());if(s===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";s=r}return this.catchUp(s,e)}isCaughtUp(e){const s=c(this.host.sql());return s!==void 0&&this.isFreshEnough(s,e)}async catchUp(e,s){let r=e;for(let i=0;i<C;i+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return s===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const a=n.changes.length<y;if(r=await this.applyPage(n),a||this.isFreshEnough(r,s))return this.isFreshEnough(r,s)?"fresh":"stale"}return this.isFreshEnough(r,s)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return d(this.host.sql(),s),s}hasDiverged(e,s){const r=s.changes.length===0&&s.cursor>e.appliedSeq,i=s.floor??(r?s.cursor:0),n=i>0&&i>e.appliedSeq+1;return s.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const s=await e.json();if(s.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(s.rows);if(r.length>0){this.divergent=!0;return}const i={appliedSeq:s.cursor,epoch:s.epoch,syncedAtMs:Date.now()};return d(this.host.sql(),i),i}isFreshEnough(e,s){return s!==void 0?e.appliedSeq>=s:Date.now()-e.syncedAtMs<=f(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",O)}async pull(e){const s=await this.request({sinceSeq:e,type:"replica_pull"});return s===void 0?void 0:await s.json()}async request(e){const s=this.host.shardBinding(),r=q(this.host.env(),s,this.ownerKey);if(r===void 0)return;const i=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":s??""},a=w(this.host.env());a!==void 0&&(n[g]=await _(a,i));try{const o=await r.fetch("https://replica.internal/_lunora/replica",{body:i,headers:n,method:"POST"});return o.ok?o:void 0}catch{return}}}const $=t=>{const e=t.doName();if(e===void 0)return;const s=v(e);return s===void 0?void 0:new I(t,s.ownerKey,s.region)},D=async(t,e,s)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${s}" is a write and cannot run on a read replica`}},{status:421});const r=await t.ensureFresh(L(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{$ as createReplicaLink,D as gateReplicaDispatch,U as handleReplicaControl};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";const d=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,functionPath:typeof t.functionPath=="string"?t.functionPath:"",id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};return typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),e},i=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},s=t.httpMetadata?.contentType??t.contentType;typeof s=="string"&&(e.contentType=s),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:r}=t;return typeof r=="number"?e.uploaded=r:r instanceof Date&&(e.uploaded=r.getTime()),e},f=(t={})=>{const e=()=>{if(!t.scheduler)throw new c("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},s=()=>{if(!t.storage)throw new c("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},r=async()=>(await e().list()).map(a=>d(a)),y=async()=>{const{objects:a}=await s().list();return a.map(n=>i(n))};return{get:(async(a,n)=>{if(a==="_scheduled_functions"){const u=await e().get(n);return u?d(u):null}const o=await s().getMetadata(n);return o?i(o):null}),query:(a=>a==="_scheduled_functions"?{collect:r}:{collect:y})}};export{f as createSystemReader};
@@ -1 +0,0 @@
1
- import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DN7gk6uh.mjs";import{runDrizzle as u}from"./runDrizzle-C3n5gJsk.mjs";import{C as ce,a as M,E as D,c as j,p as S,T as _,h as fe,A as C,N as k}from"./do-sql-DKSFK627.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as $e}from"./param-CYxL68V-.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-5w13bMAR.mjs";import{encodePartitionKey as he,sortColumnName as pe,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-BGk411OR.mjs";import{y as ge}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const _e=["de","en","es","fr","it","nl","none","pt"],ye=o=>_e.includes(o),be="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",Se="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",Te="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",ve="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",we="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",Ae="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",Re="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ê",Le=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Le,"").normalize("NFC").toLowerCase(),O=o=>new Set(ne(o).split(" ")),Ie={de:O(Se),en:O(be),es:O(Te),fr:O(ve),it:O(we),nl:O(Ae),none:new Set,pt:O(Re)},Ne=2,Oe=256,Q=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=Q.get(a);if(l)return l;const g=Ie[a],w=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Oe);return g.size===0?A:A.filter(T=>!g.has(T))},m={document:w,profile:`${a}-v${String(Ne)}`,query:r=>{const A=w(r);return A.filter((T,L)=>A.lastIndexOf(T)===L)}};return Q.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ce="__text__",X="__id__",Me=1e3,De=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",qe=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),ze=(o,a)=>De(ke(q(o,a.field)),je(a.language)).slice(0,Me).join(" "),We=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>pe(l))].map(a=>e.identifier(a)),e`, `),te=(o,a,l,g,w,m)=>{const r=he(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),T=e.join([w,r,...A].map(L=>ue(L)),e`, `);u(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${T})`)},Be=(o,a,l,g,w,m)=>{if(w&&m&&We(l,w,m))return;const r=Z(a,l.name);w&&u(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&te(o,r,l,oe(l),g,m)},nn=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:w,schema:m,sql:r}=o,A=new Set,T=t=>m.tables[t]?.softDeleteMode?.field,L=new Set,z=(t,n)=>{const s=`${t}::${n.name}`;if(A.has(s))return;const d=G(t,n.name),c=n.by??[],f=T(t),h=new Map,y=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();for(const v of y){const $=D(v);if(!$||!J($,f)||n.where&&!P($,n.where))continue;const E=N(c,$);V(h,E,n,$)}u(r,e`DELETE FROM ${e.identifier(d)}`);const R=Math.floor($e.boundParams/3),I=[...h];for(let v=0;v<I.length;v+=R){const $=I.slice(v,v+R),E=e.join($.map(([i,p])=>e`(${i}, ${p.value}, ${p.count})`),e`, `);u(r,e`INSERT INTO ${e.identifier(d)} (${j}, ${S}, ${_}) VALUES ${E}`)}A.add(s)},ie=(t,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,i)=>{const p=ee(i);p===null?f.push(e`${k(E)} IS NULL`):f.push(e`${k(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const y=T(t);y!==void 0&&h(y,null);for(const[E,i]of Object.entries(n.where??{}))h(E,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,I=m.tables[t]?.shape[c];if(I&&ge(I)){const E=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}${R}`).toArray(),i=new Map;for(const p of E){const b=D(p);b&&V(i,"",n,b)}return{value:i.get("")?.value??null}}const v=de(n.op),$=k(c);return{value:u(r,e`SELECT ${e.raw(v)}(${$}) AS value FROM ${e.identifier(t)}${R}`).one().value??null}},re=(t,n,s,d)=>{const c=G(t,n.name),{op:f}=n,h=n.field??"",y=i=>{u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i} AND ${_} <= 0`)},R=T(t),I=i=>!n.where||P(i,n.where),v=i=>J(i,R)&&I(i);d!==void 0&&f!=="count"&&I(d)&&F(d[h]);const $=s&&v(s)?s:void 0,E=d&&v(d)?d:void 0;if(!(!$&&!E)){if(f==="count"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=N(n.by??[],i);u(r,C(c,b,p,p,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if(f==="sum"||f==="avg"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=F(i[h]);if(b===void 0)continue;const x=N(n.by??[],i);u(r,C(c,x,p*b,p,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if($){const i=N(n.by??[],$),p=F($[h]),b=u(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(c)} WHERE ${j} = ${i}`).toArray()[0],x=(b?.count??0)-1;if(x<=0)u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=ie(t,n,$);u(r,e`UPDATE ${e.identifier(c)} SET ${S} = ${le.value}, ${_} = ${x} WHERE ${j} = ${i}`)}else u(r,e`UPDATE ${e.identifier(c)} SET ${_} = ${_} - 1 WHERE ${j} = ${i}`)}if(E){const i=N(n.by??[],E),p=F(E[h]);if(p===void 0)u(r,C(c,i,null,1,e`${_} = ${_} + 1`));else{const b=f==="min"?"MIN":"MAX";u(r,C(c,i,p,1,e`${S} = ${e.raw(b)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ae=t=>{for(const n of m.tables[t]?.aggregateIndexes??[])z(t,n)},W=(t,n,s)=>{for(const d of m.tables[t]?.aggregateIndexes??[])re(t,d,n,s)},B=(t,n)=>{const s=`${t}::rank::${n.name}`;if(L.has(s))return;const d=Z(t,n.name),c=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();u(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const y=D(h);!y||n.where&&!Y(y,n.where)||te(r,d,n,f,y._id,y)}L.add(s)},se=t=>{for(const n of m.tables[t]?.rankIndexes??[])B(t,n)},H=(t,n,s,d)=>{for(const c of m.tables[t]?.rankIndexes??[])Be(r,t,c,n,s,d)},U=(t,n,s,d)=>{const c=m.tables[t]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(qe(d,s,f))continue;const h=Fe(t,f.name);u(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(X)} = ${n}`),s&&u(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ce)}, ${e.identifier(X)}) VALUES (${ze(s,f)}, ${n})`)}},K=(t,n,s)=>{for(const d of m.tables[t]?.geoIndexes??[]){const c=fe(t,d.name);u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:y}=f,R=me({lat:h,lng:y},d.precision??Ee);u(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${y})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(t,n,s)=>{U(t,n,s),K(t,n,s),W(t,void 0,s),H(t,n,void 0,s),g(t,n,s),w(t,n,"insert",s),a({indexKeys:l(t,s),key:n,op:"insert",row:s,table:t})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,nn as S,X as T,te as W,Fe as c,Ce as l,De as n,je as x,ze as y};
@@ -1 +0,0 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-BlrEp5pr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-C1mjoJS4.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -1 +0,0 @@
1
- import{stableStringify as u}from"./stableStringify-BjLh4gvA.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},h=(t,s,o)=>{const{columns:e,table:n}=o,i=[],d=new Map;for(const r of t){const c=l(r,e),a=String(c._id),f=u(c);d.set(a,f);const p=s.get(a);p===void 0?i.push({doc:c,id:a,op:"insert",seq:0,table:n,ts:0}):p!==f&&i.push({doc:c,id:a,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||i.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:i,nextBaseline:d}};export{h as diffExternalSource,l as projectExternalSourceRow};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dh0j-GnY.mjs";import{runDrizzle as _}from"./runDrizzle-C3n5gJsk.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
@@ -1 +0,0 @@
1
- import{r as c}from"./sql-projection-jfoe331H.mjs";const i=40,s=o=>{let r=0;const f=(e,t)=>typeof t=="bigint"?(r+=c+1+i,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r+=2*Math.ceil(t.byteLength/3)*4+i,""):t;try{const e=JSON.stringify(o,f);return(e===void 0?0:e.length)+r}catch{return}};export{s as o};
@@ -1 +0,0 @@
1
- import{toErrorBody as f}from"@lunora/errors";const d=200,b=(r,s)=>{const n=o=>{const e=r.tables[o];return e!==void 0&&e.shardMode?.kind!=="global"};return(s&&s.length>0?[...s]:Object.keys(r.tables)).filter(o=>n(o))},u=async function*(r,s,n=d){let o=null,e=!1;for(;!e;){const t=await r.findMany(s,{cursor:o,limit:n});for(const a of t.page)yield{doc:a,table:s};o=t.continueCursor,e=t.isDone||o===null}},k=async function*(r,s,n){const o=b(s,n.tables),e=n.batchSize??d;for(const t of o)yield*u(r,t,e)},p=new Set(["_creationTime","_id"]),y=(r,s)=>{for(const[n,o]of Object.entries(r.shape)){const e=s[n];if(e===void 0&&o.kind==="optional")continue;const t=o.parse;if(typeof t=="function")try{t(e)}catch(a){const c=a instanceof Error?a.message:String(a);return`field "${n}": ${c}`}}},h=(r,s,n)=>{const o=r.tables[s];if(!o)return`unknown table: ${s}`;if(o.shardMode?.kind==="global")return`table "${s}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(n).filter(([t])=>!p.has(t)));for(const t of Object.keys(e))if(!(t in o.shape))return`unexpected field "${t}": not declared in table "${s}"`;return y(o,e)},g=async(r,s)=>{try{return await r.get(s)!==null}catch{return!1}},m=async(r,s,n,o)=>{const{doc:e,table:t}=n;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:o,message:"row is missing `table`",table:t},kind:"error"};if(!e||typeof e!="object"||Array.isArray(e))return{error:{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:t},kind:"error"};const a=h(s,t,e);if(a!==void 0)return{error:{code:"VALIDATION_ERROR",line:o,message:a,table:t},kind:"error"};const c=typeof e._id=="string"?e._id:void 0;if(c!==void 0&&await g(r,c))return{kind:"conflict"};try{return await r.insert(t,e,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(i){const{body:l}=f(i,{fallbackCode:"INSERT_FAILED"});return{error:{code:l.code,line:o,message:l.message,table:t},kind:"error"}}},A=async(r,s,n)=>{const o=[],e={};let t=0,a=(n.startLine??1)-1;for(const c of n.rows){a+=1;const i=await m(r,s,c,a);i.kind==="error"?o.push(i.error):i.kind==="conflict"?t+=1:e[i.table]=(e[i.table]??0)+1}return{conflicts:t,errors:o,inserted:e}},S=r=>{const s=Array.isArray(r.tables)?r.tables.filter(n=>typeof n=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:s}},v=r=>{const s=Array.isArray(r.rows)?r.rows:[],n=[];for(const e of s){if(!e||typeof e!="object")continue;const t=e;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){n.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}n.push({doc:t.doc,table:t.table})}const o=typeof r.startLine=="number"?r.startLine:void 0;return{rows:n,startLine:o}};export{k as exportShardRows,u as exportShardTable,A as importShardRows,S as parseExportShardArgs,v as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
@@ -1 +0,0 @@
1
- const g=async t=>{const e=t.schema.tables[t.tableName]?.triggerMap;if(e)for(const a of Object.values(e))a.timing===t.timing&&a.op===t.op&&await a.handler(t.ctx,t.event)},i=(t,e,a)=>{const r=t.tables[e]?.triggerMap;return r?Object.values(r).some(s=>s.op===a):!1};export{i as hasTrigger,g as runTriggers};
@@ -1,9 +0,0 @@
1
- import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-C-5TKdc1.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
2
- table_name TEXT NOT NULL,
3
- shard_key TEXT NOT NULL,
4
- watermark TEXT,
5
- last_reconcile_ms INTEGER,
6
- PRIMARY KEY (table_name, shard_key)
7
- )`)},B=(e,t,a)=>{const n=h(e,m`SELECT watermark, last_reconcile_ms FROM ${m.identifier(_)} WHERE table_name = ${t} AND shard_key = ${a} LIMIT 1`).toArray()[0];return{lastReconcileMs:n?.last_reconcile_ms??null,watermark:n?.watermark??null}},C=(e,t,a,n)=>{h(e,m`INSERT INTO ${m.identifier(_)} (table_name, shard_key, watermark, last_reconcile_ms)
8
- VALUES (${t}, ${a}, ${n.watermark}, ${n.lastReconcileMs})
9
- ON CONFLICT(table_name, shard_key) DO UPDATE SET watermark = excluded.watermark, last_reconcile_ms = excluded.last_reconcile_ms`)},P=(e,t,a)=>e==="manual"?!1:e===void 0||t===void 0?!0:a-t>=e.everyMs,T=async(e,t,a,n)=>{const r=await e.query(t,a);return{documents:r.map(s=>x(s,{idColumn:n.idColumn,map:n.map})),rows:r}},V=async(e,t,a,n,r,s)=>{const i=r.tenantBy?r.tenantBy(s):[],{documents:l}=await T(a,r.query,i,r);return v(e,t,l,{columns:r.columns,table:n})},N=(e,t)=>{const a=e[t];return a!=null&&a!==!1&&a!==0},Y=async(e,t,a,n,r,s,i)=>{const{cursor:l}=r;if(!l)throw new E("INTERNAL",`external-source: table "${n}" is mode "incremental" but has no \`cursor\` — this should have been rejected at defineSchema`);O(e);const u=B(e,n,s),b=r.tenantBy?r.tenantBy(s):[],g=r.reconcileEveryMs!==void 0&&(u.lastReconcileMs===null||i-u.lastReconcileMs>=r.reconcileEveryMs),w=u.watermark===null||g;let o,f;if(u.watermark===null||g){o=await T(a,r.query,b,r);const{softDeleteColumn:c}=r,y=c?o.documents.filter(($,p)=>{const d=o.rows[p];return!(d&&N(d,c))}):o.documents;({applied:f}=await v(e,t,y,{columns:r.columns,table:n}))}else{o=await T(a,l.query,[...b,R(u.watermark)],r);const{softDeleteColumn:c}=r,y=c?new Set(o.documents.flatMap(($,p)=>{const d=o.rows[p];return d&&N(d,c)?[String($._id)]:[]})):void 0;({applied:f}=await M(t,o.documents,{columns:r.columns,deletedIds:y,table:n}))}const S=q(o.rows,l.column,u.watermark);if(w&&S===null&&o.rows.length>0)throw new E("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(o.rows.length)} rows but none carry the cursor column "${l.column}" — the seed \`query\` must project it (matching \`cursor.query\`'s alias), or the watermark can never advance.`);const L=o.rows.length>0&&o.rows.every(c=>c[l.column]===null||c[l.column]===void 0);if(!w&&L)throw new E("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(o.rows.length)} rows but none carry the cursor column "${l.column}" — \`cursor.query\` must project it (matching the seed \`query\`'s alias), or the watermark can never advance and every tick re-pulls the same stranded slice.`);return C(e,n,s,{lastReconcileMs:w?i:u.lastReconcileMs,watermark:S}),{applied:f}};export{N as isSoftDeleted,P as isSourceDue,x as liftSourceId,K as normalizeSourceValue,Y as pullExternalSourceIncrementalTick,V as pullExternalSourceTick};
@@ -1 +0,0 @@
1
- import{LunoraError as m}from"@lunora/errors";const f=r=>r instanceof Date?r.toISOString():typeof r=="bigint"?String(r):Array.isArray(r)?r.map(t=>f(t)):r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype?n(r):r,n=r=>{const t={};for(const[o,i]of Object.entries(r))t[o]=f(i);return t},p=(r,t={})=>{const{idColumn:o="id",map:i}=t,e=r[o];if(e==null)throw new m("INTERNAL",`external-source: row is missing id column "${o}"`);if(typeof e!="string"&&typeof e!="number"&&typeof e!="bigint")throw new TypeError(`external-source: id column "${o}" must be a string or number`);const s=String(e);if(i)return n({...i(r),_id:s});const c={};for(const[u,a]of Object.entries(r))u!==o&&(c[u]=a);return n({...c,_id:s})};export{p as liftSourceId,n as normalizeSourceDocument,f as normalizeSourceValue};
@@ -1 +0,0 @@
1
- import{applyCdcChanges as m}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
@@ -1 +0,0 @@
1
- import{keysTouchRanges as g}from"./buildIndexRange-DFsdtPjD.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
@@ -1 +0,0 @@
1
- import{LunoraError as m}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{MySqlDialect as c}from"drizzle-orm/mysql-core";import{PgDialect as u}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const f=new u,d=new c,S=new p,g={mysql:d,postgres:f,sqlite:S},a={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},h=a.boundParams/2,L=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),w=(e,t)=>{const{params:n,sql:o}=g[e].sqlToQuery(t);return{params:n,sql:o}},$=e=>r`${e}`,O=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let t=[...e];for(;t.length>a.compoundSelect;){const n=[];for(let o=0;o<t.length;o+=a.compoundSelect){const l=r.join(t.slice(o,o+a.compoundSelect),r` UNION ALL `);n.push(r`SELECT * FROM (${l}) ${r.identifier("__u__")}`)}t=n}return r.join(t,r` UNION ALL `)},I=(e,t,n,o=h)=>{const l=n?r` NOT IN `:r` IN `,s=t.every(i=>L(i));if(t.length>o&&!s)throw new m("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return t.length<=o?r`${e}${l}(${r.join(t.map(i=>$(i)),r`, `)})`:r`${e}${l}(SELECT ${r.identifier("value")} FROM json_each(${JSON.stringify(t)}))`};export{a as WORKERD_SQLITE_LIMITS,$ as param,w as renderSql,I as sqliteInList,O as unionAll};
@@ -1 +0,0 @@
1
- import{LunoraError as l}from"@lunora/errors";import{renderSql as o,WORKERD_SQLITE_LIMITS as n}from"./param-CYxL68V-.mjs";const i=(t,e,...r)=>{if(e.length*3>n.sqlTextLength){const s=new TextEncoder().encode(e).length;if(s>n.sqlTextLength)throw new l("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(n.sqlTextLength)}-byte limit`)}if(r.length>n.boundParams)throw new l("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(n.boundParams)}`);return t.exec.call(t,e,...r)},u=(t,e)=>{const{params:r,sql:s}=o("sqlite",e);return i(t,s,...r)},h=t=>t??null,g=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{g as decodeJsonColumn,h as orNull,u as runDrizzle,i as runSql};
@@ -1,5 +0,0 @@
1
- import{l as I,T as S,c as N}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DN7gk6uh.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as u}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as O}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{migrateShapePokeCursor as U}from"./SHAPE_POKE_CURSOR_TABLE-pybVwKps.mjs";import{runDrizzle as t}from"./runDrizzle-C3n5gJsk.mjs";import{a as b,N as c,y as T,I as X,C as x,c as B,p as D,T as E,h as F}from"./do-sql-DKSFK627.mjs";import{migrateDurableStreams as M}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as Y,rankTableName as k}from"./RANK_TIEBREAK-BGk411OR.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const P=(r,a,o)=>{for(const i of o.indexes){const n=`${a}_${i.name}`,s=e.join(i.fields.map(f=>c(f)),e`, `);t(r,T(n,a,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${a}_unique_${i}`;t(r,T(s,a,c(i),!0))}},j=(r,a,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!x(r))){for(const i of o.searchIndexes){const n=N(a,i.name);t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(S)} UNINDEXED)`),t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,a,o)}},q=(r,a,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(a,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${a}__geo_${i.name}__btree`;t(r,T(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,a,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(a,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${B} TEXT PRIMARY KEY, ${D} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),t(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||t(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},K=(r,a,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=k(a,i.name),s=i.sortBy.map((m,d)=>Y(d)),f=s.map(m=>e`${e.identifier(m)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const _=[e`${e.identifier("__partition__")} ASC`];for(const[m,d]of s.entries()){const A=i.sortBy[m]?.direction;_.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}_.push(e`${e.identifier("__id__")} ASC`);const L=`${a}__rank_${i.name}__btree`;t(r,T(L,n,e.join(_,e`, `),!1))}},se=(r,a,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),O(r);for(const[i,n]of Object.entries(a.tables))n.shardMode?.kind!=="global"&&(t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(b)} TEXT NOT NULL
5
- )`),P(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n),K(r,i,n));o.cdc&&(h(r),l(r),R(r),U(r)),u(r),C(r),M(r)};export{se as runShardMigrations};
@@ -1 +0,0 @@
1
- const l=async(o,e,n=8)=>{let t=0;const c=async()=>{let a=o[t];for(t+=1;a!==void 0;){try{await e(a)}catch{}a=o[t],t+=1}};await Promise.all(Array.from({length:Math.min(n,o.length)},()=>c()))};export{l as runSocketPool};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-DKSFK627.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-DKSFK627.mjs";import{sqliteInList as h}from"./param-CYxL68V-.mjs";import{compileWhereSql as S}from"./compileWhereSql-B3hq_v98.mjs";import{serializeSqlValue as E}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:E},R=i=>{if(i.length!==0)return h(e`${e.identifier("id")}`,i,!1)},p=(i,o)=>{const r=[];o&&r.push(o);const t=S(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},L=(i,o,r)=>{const t=p(r,void 0),f=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of f){const d=a(s),{id:l}=s;d!==void 0&&typeof l=="string"&&n.push({doc:d,id:l})}return n},M=(i,o,r,t)=>{if(t.length===0)return new Set;const f=p(r,R(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${f}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
@@ -1 +0,0 @@
1
- import{b as o}from"./sql-projection-jfoe331H.mjs";const t=e=>typeof e=="boolean"?e?1:0:e===null||typeof e=="string"||typeof e=="number"?e:o(e)??JSON.stringify(e);export{t as serializeSqlValue};
@@ -1 +0,0 @@
1
- const s=/^\d+$/,m=(n,t,o)=>{const e=n?.[t];let r=Number.NaN;return typeof e=="string"&&s.test(e.trim())?r=Number(e.trim()):typeof e=="number"&&(r=e),Number.isSafeInteger(r)&&r>0?r:o},c=(n,t)=>{const o=Math.max(n.length,t.length);let e=n.length^t.length;for(let r=0;r<o;r+=1){const i=r<n.length?n.charCodeAt(r):0,a=r<t.length?t.charCodeAt(r):0;e|=i^a}return e===0},u="LUNORA_RELAY_SECRET",y="x-lunora-relay-sig",l=n=>{const t=n?.[u];return typeof t=="string"&&t.length>0?t:void 0},g=async(n,t)=>{const o=new TextEncoder,e=await crypto.subtle.importKey("raw",o.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",e,o.encode(t));return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")},d=async(n,t,o)=>{const e=l(n);return e===void 0?!0:t===null?!1:c(t,await g(e,o))},f=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},h=(n,t,o)=>{if(t===void 0)return;const e=f(n?.[t]);if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))};export{d as f,y as g,h as l,g as o,l as s,m as u};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{a}from"./base64-fKomMf5D.mjs";const n=t=>{if(t.kind!=="optional")return t.kind;const r=t._meta?.inner;return r?n(r):t.kind},e=39,s="0",u="1",y=t=>{const r=t<0n,i=(r?-t:t).toString();if(i.length>e)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(i.length)} digits, over the ${String(e)}-digit limit for a queryable column`);const o=i.padStart(e,"0");return r?s+Array.from(o,f=>String(9-Number(f))).join(""):u+o},d=t=>typeof t=="bigint"?y(t):t instanceof ArrayBuffer?a(new Uint8Array(t)):ArrayBuffer.isView(t)?a(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,m=t=>{const r=n(t);return r==="bigint"||r==="bytes"},S=t=>{const r=n(t);return m(t)||r==="any"||r==="union"||r==="from"};export{d as b,m as f,e as r,S as y};
@@ -1 +0,0 @@
1
- const y=(e,t)=>e<t?-1:e>t?1:0,s=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>s(r)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,a=Object.keys(n).toSorted(y),i=[];for(const r of a){const o=n[r];o!==void 0&&i.push(`${JSON.stringify(r)}:${s(o)}`)}return`{${i.join(",")}}`};export{s as stableStringify};
@@ -1 +0,0 @@
1
- import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-Dh0j-GnY.mjs";const i=t=>r(e(t));export{i as stableWireKey};
@@ -1 +0,0 @@
1
- import{a as p,o as A}from"./base64-fKomMf5D.mjs";const i="$lunora.wire$",b=64,g=1024,d="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},m={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},v=r=>{if(r===null||typeof r!="object")return!1;const a=Object.getPrototypeOf(r);return a===null||a===Object.prototype},c=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const s=typeof r;if(s==="bigint")return[i,"bigint",r.toString()];if(s==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(s!=="object")return r;if(r instanceof Date)return[i,"date",c(r.getTime(),a+1)];if(r instanceof Error){const e=r,n={};for(const f of Object.keys(e))e[f]!==void 0&&(n[f]=c(e[f],a+1));const o=[i,"error",e.name,e.message,n];return e.cause!==void 0&&o.push(c(e.cause,a+1)),o}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,n])=>[c(e,a+1),c(n,a+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>c(e,a+1))];if(r instanceof ArrayBuffer)return[i,"bytes",p(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[i,"bytes",p(o)]:[i,"bytes",p(o),n]}if(Array.isArray(r)){const e=r.map(n=>c(n,a+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!v(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const l=r,t={};for(const e of Object.keys(l)){const n=l[e];if(n===void 0)continue;const o=c(n,a+1);e===d?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:o,writable:!0}):t[e]=o}return t},u=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>u(t,a+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>g||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(t)}case"date":return new Date(u(r[2],a+1));case"map":return new Map(r[2].map(([t,e])=>[u(t,a+1),u(e,a+1)]));case"set":return new Set(r[2].map(t=>u(t,a+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],n=(Object.hasOwn(m,t)?m[t]:void 0)??Error,o=new n(e);o.name!==t&&Object.defineProperty(o,"name",{configurable:!0,value:t,writable:!0});const f=u(r[4],a+1);for(const y of Object.keys(f))y===d?Object.defineProperty(o,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):o[y]=f[y];return r.length>5&&Object.defineProperty(o,"cause",{configurable:!0,value:u(r[5],a+1),writable:!0}),o}case"bytes":{const t=A(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(w,e)?w[e]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>u(t,a+1))}return r.map(t=>u(t,a+1))}const s=r,l={};for(const t of Object.keys(s)){const e=u(s[t],a+1);t===d?Object.defineProperty(l,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):l[t]=e}return l};export{v as A,c as a,u as s};