@lunora/shard-engine 1.0.0-alpha.14 → 1.0.0-alpha.141

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 (158) hide show
  1. package/README.md +1 -1
  2. package/dist/conformance/index.mjs +1 -1
  3. package/dist/index.d.mts +849 -169
  4. package/dist/index.d.ts +849 -169
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs +1 -0
  7. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
  8. package/dist/packem_shared/AGG_COUNT-CBe5drFS.mjs +1 -0
  9. package/dist/packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs +8 -0
  10. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  11. package/dist/packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs +18 -0
  12. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs +7 -0
  13. package/dist/packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs +4 -0
  14. package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
  15. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  16. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs +31 -0
  17. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs +1 -0
  18. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DwSg1Ecx.mjs +8 -0
  19. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
  20. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +1 -0
  21. package/dist/packem_shared/DurableStreamRunner-Dzge_ywD.mjs +1 -0
  22. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  23. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs +7 -0
  24. package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
  25. package/dist/packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs +7 -0
  26. package/dist/packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs +18 -0
  27. package/dist/packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs +4 -0
  28. package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
  29. package/dist/packem_shared/NotUniqueError-CNXsYOSU.mjs +1 -0
  30. package/dist/packem_shared/QUEUE_TABLE-jEc6-2wm.mjs +17 -0
  31. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
  32. package/dist/packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs +28 -0
  33. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +1 -0
  34. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  35. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs +1 -0
  36. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  37. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs +1 -0
  38. package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
  39. package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
  40. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs +11 -0
  41. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs +6 -0
  42. package/dist/packem_shared/SEARCH_STATE_TABLE-BThmEiED.mjs +1 -0
  43. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs +8 -0
  44. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  45. package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
  46. package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
  47. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs +1 -0
  48. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs +1 -0
  49. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  50. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  51. package/dist/packem_shared/appendStreamChunk-DF_Jrgpy.mjs +17 -0
  52. package/dist/packem_shared/applyOnDelete-BwxDC4lU.mjs +1 -0
  53. package/dist/packem_shared/archiveCdcSegment-CIiYU1FU.mjs +4 -0
  54. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  55. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  56. package/dist/packem_shared/awaitWsDrain-N-oR29RI.mjs +1 -0
  57. package/dist/packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs +1 -0
  58. package/dist/packem_shared/buildIndexRange-DQ3eWAGd.mjs +1 -0
  59. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  60. package/dist/packem_shared/buildReprojectionMigration-DQV0q3w9.mjs +1 -0
  61. package/dist/packem_shared/buildSettings-BRkZd6_E.mjs +1 -0
  62. package/dist/packem_shared/buildShapeDiff-BHr3i1m6.mjs +1 -0
  63. package/dist/packem_shared/clearCompanionSignatures-8uVX84aT.mjs +1 -0
  64. package/dist/packem_shared/clearMemoryTables-Lu0S2GOb.mjs +1 -0
  65. package/dist/packem_shared/compileWhereSql-CKoO19by.mjs +1 -0
  66. package/dist/packem_shared/computeRankPage-DLSi_oBt.mjs +1 -0
  67. package/dist/packem_shared/createCompanionSync-DhYLePyV.mjs +1 -0
  68. package/dist/packem_shared/createReplicaLink-BqNxWyzF.mjs +7 -0
  69. package/dist/packem_shared/createSystemReader-DcDLFfC-.mjs +1 -0
  70. package/dist/packem_shared/ctx-db-relay-shapes-CPwELrMf.mjs +17 -0
  71. package/dist/packem_shared/ctx-db-search-state-CrTLPmFN.mjs +1 -0
  72. package/dist/packem_shared/defineEngineContractSuite-DoGZerel.mjs +1 -0
  73. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  74. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  75. package/dist/packem_shared/do-sql-DqU-17Fs.mjs +1 -0
  76. package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
  77. package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
  78. package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +1 -0
  79. package/dist/packem_shared/exportShardRows-yxw7vFf9.mjs +1 -0
  80. package/dist/packem_shared/fts-companion-DzfEHonU.mjs +1 -0
  81. package/dist/packem_shared/ftsCompanionDdl-Cka6_-Fm.mjs +1 -0
  82. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  83. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  84. package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
  85. package/dist/packem_shared/isSoftDeleted-D5MeQSk0.mjs +9 -0
  86. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  87. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  88. package/dist/packem_shared/materializeExternalRows-D2zEvCAa.mjs +1 -0
  89. package/dist/packem_shared/mergeChangedKeys-CF2mjYuy.mjs +1 -0
  90. package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
  91. package/dist/packem_shared/runDrizzle-B2GG3IJa.mjs +1 -0
  92. package/dist/packem_shared/runShardMigrations-BeqUbznb.mjs +5 -0
  93. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  94. package/dist/packem_shared/selectExpiredIds-B8PxwbIr.mjs +1 -0
  95. package/dist/packem_shared/selectShapeMembers-B1MIaRkE.mjs +1 -0
  96. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  97. package/dist/packem_shared/where-sql-DO1vOrhc.mjs +1 -0
  98. package/package.json +5 -4
  99. package/dist/packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs +0 -1
  100. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  101. package/dist/packem_shared/AGG_COUNT-B0Pb1nQZ.mjs +0 -1
  102. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
  103. package/dist/packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs +0 -8
  104. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
  105. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  106. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
  107. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-C7Iky4H5.mjs +0 -1
  108. package/dist/packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs +0 -1
  109. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs +0 -1
  110. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +0 -1
  111. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  112. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
  113. package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
  114. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
  115. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  116. package/dist/packem_shared/NotUniqueError-GHJiYnzm.mjs +0 -1
  117. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
  118. package/dist/packem_shared/RANK_TIEBREAK-D541BOFR.mjs +0 -1
  119. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  120. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  121. package/dist/packem_shared/ReactiveCache-iWA9VRqk.mjs +0 -1
  122. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  123. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
  124. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
  125. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  126. package/dist/packem_shared/aggregateTableName-DKo6dwBP.mjs +0 -1
  127. package/dist/packem_shared/applyOnDelete-CxpItW0j.mjs +0 -1
  128. package/dist/packem_shared/applySelect-BjgwvZmI.mjs +0 -1
  129. package/dist/packem_shared/awaitWsDrain-DKycCSBS.mjs +0 -1
  130. package/dist/packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs +0 -1
  131. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  132. package/dist/packem_shared/buildPokeFrames-CCxYXd2V.mjs +0 -1
  133. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  134. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  135. package/dist/packem_shared/computeRankPage-B7U6t1fW.mjs +0 -1
  136. package/dist/packem_shared/createCompanionSync-Dym8huD9.mjs +0 -1
  137. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  138. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  139. package/dist/packem_shared/ctx-db-companions-7fIu-E2H.mjs +0 -1
  140. package/dist/packem_shared/defineEngineContractSuite-Zg5xN9h4.mjs +0 -1
  141. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  142. package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
  143. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  144. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  145. package/dist/packem_shared/isSoftDeleted-doD_8AwX.mjs +0 -9
  146. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  147. package/dist/packem_shared/materializeExternalRows-BR8MvZTz.mjs +0 -1
  148. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  149. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  150. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
  151. package/dist/packem_shared/runShardMigrations-DhZLG0bn.mjs +0 -5
  152. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  153. package/dist/packem_shared/selectExpiredIds-DxFEwNlT.mjs +0 -1
  154. package/dist/packem_shared/selectShapeMemberIds-BD3JiZn-.mjs +0 -1
  155. package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
  156. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  157. package/dist/packem_shared/stableWireKey-C4JfdJ_e.mjs +0 -1
  158. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +0 -1
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{RELATION_EXISTS_KEY as c}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const N=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],h=new Set(N),p={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},I=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>h.has(t))},L=r=>typeof r=="string"?r.replaceAll(/[\\%_]/g,e=>`\\${e}`):r,g=(r,e,t)=>{const o=s`${t.serialize(L(e))}`;return t.likeContains?t.likeContains(r,o):s`${r} LIKE '%' || ${o} || '%' ESCAPE '\\'`},O=(r,e,t,o,n)=>o===null?e==="ne"?s`${r} IS NOT NULL`:s`${r} IS NULL`:s`${r} ${s.raw(t)} ${n.serialize(o)}`,S=(r,e,t,o)=>{const n=Array.isArray(t)?t:[];if(n.length===0)return e==="IN"?s`0 = 1`:s`1 = 1`;const i=s.join(n.map(l=>s`${o.serialize(l)}`),s`, `);return e==="IN"?s`${r} IN (${i})`:s`${r} NOT IN (${i})`},A=(r,e,t)=>{const o=e,n=[];for(const i of N){if(!(i in o))continue;const l=o[i],u=p[i];u?n.push(O(r,i,u,l,t)):i==="isNull"?n.push(l?s`${r} IS NULL`:s`${r} IS NOT NULL`):i==="contains"?n.push(g(r,l,t)):n.push(S(r,i==="in"?"IN":"NOT IN",l,t))}return n},y=(r,e,t)=>{const o=t.fieldRef(r);return I(e)?A(o,e,t):e===null?[s`${o} IS NULL`]:[s`${o} = ${t.serialize(e)}`]},f=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:s.join(r.map(t=>s`(${t})`),s` ${s.raw(e)} `)},E=(r,e,t)=>{const o=Array.isArray(r)?r:[],n=[];for(const i of o){const l=a(i??{},t);l&&n.push(l)}return n.length===0?e==="OR"?s`0 = 1`:void 0:f(n,e)},m=new Set(["AND","NOT","OR",c]),T=(r,e,t)=>{if(r===c){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const o=a(e??{},t);return o?s`NOT (${o})`:void 0}return E(e,r,t)},a=(r,e)=>{const t=[];for(const[o,n]of Object.entries(r))if(m.has(o)){const i=T(o,n,e);i&&t.push(i)}else t.push(...y(o,n,e));return f(t,"AND")},R=(r,e)=>{if(!(!r||Object.keys(r).length===0))return a(r,e)};export{R as compileWhereSql};
@@ -1 +0,0 @@
1
- import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as x}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{param as q}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-BjgwvZmI.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-D541BOFR.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,c)=>{if(n?.length!==1+o.length+1)return;const i=[{column:"__partition__",direction:"asc"}];for(const[a,f]of o.entries())i.push({column:f,direction:c[a]?.direction??"asc"});i.push({column:m,direction:"asc"});const s=[];for(const[a,f]of i.entries()){const e=[];for(const[r,$]of i.slice(0,a).entries())e.push(t`${t.identifier($.column)} IS ${n[r]}`);e.push(t`${t.identifier(f.column)} ${t.raw(f.direction==="desc"?"<":">")} ${n[a]}`);const[d]=e;s.push(e.length===1&&d!==void 0?d:t`(${t.join(e,t` AND `)})`)}return t`(${t.join(s,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const c=[n.__partition__,...o.map(i=>n[i]),n[m]];return G(c)},U=(n,o,c)=>{const i=[];for(const s of n){const a=s[m];if(typeof a!="string")continue;const f=o.get(a);if(!f)continue;const e=typeof s.__partition__=="string"?s.__partition__:"",d=c.map(r=>s[r]??null);i.push({doc:f,key:{partitionKey:e,rowId:a,sortValues:d}})}return i},tt=(n,o,c)=>{const{rowToDocument:i}=n,s=new Map;if(c.length===0)return s;const a=t.join(c.map(e=>q(e)),t`, `),f=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE id IN (${a})`).toArray();for(const e of f){const d=i(e),r=e.id;d&&typeof r=="string"&&s.set(r,d)}return s},ft=(n,o,c,i)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:a,onRead:f,schema:e}=n,d=e.tables[o];if(!d)throw new A("INTERNAL",`unknown table: ${o}`);const r=d.rankIndexes?.find(p=>p.name===c);if(!r)throw new A("INTERNAL",`unknown rankIndex "${c}" on table "${o}"`);s(o,d,r),f(o,O),a(o,r);const $=V(o,r.name),u=r.sortBy.map((p,w)=>F(w)),l=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),S=x(i.baseWhere,i.where),R=H(r,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[p,w]of u.entries()){const v=r.sortBy[p]?.direction;h.push(t`${t.identifier(w)} ${t.raw(v==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof i.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${i.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(r.partitionBy??[],R)}`);const T=X(i),k=Z(T,u,r.sortBy);k&&_.push(k);const I=t.identifier(m),N=t.identifier("__partition__"),M=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,D=u.length>0?t`${I}, ${N}, ${t.join(u.map(p=>t.identifier(p)),t`, `)}`:t`${I}, ${N}`,K=t`SELECT ${D} FROM ${t.identifier($)}${M} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String(l+1))}`,y=B(n.sql,K).toArray(),g=y.length>l,E=g?y.slice(0,l):y,L=E.map(p=>p[m]),b=U(E,tt(n,o,L),u),j=g?Q(E.at(-1),u):C,P=r.sortBy.map(p=>p.direction==="desc"?"desc":"asc");return{continueCursor:j,directions:P,hasMore:g,rows:b}};export{ft as computeRankPage,tt as hydrateDocsById};
@@ -1 +0,0 @@
1
- import{k as l,q,O as C}from"./ctx-db-companions-7fIu-E2H.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DKo6dwBP.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./AGG_COUNT-B0Pb1nQZ.mjs";import"./param-B5lF5Jd9.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./RANK_TIEBREAK-D541BOFR.mjs";import"./serializeSqlValue-DnpyaLcw.mjs";export{l as createCompanionSync,q as insertRankRow,C 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 +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 x,aggregateSqlFunction as ie}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as oe,aggregateTableName as U,coerceAggregateNumber as I}from"./aggregateTableName-DKo6dwBP.mjs";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{isFtsAvailable as re,DOC_COLUMN as W,rowToDocument as B,AGG_KEY as N,AGG_VALUE as S,AGG_COUNT as _,geoTableName as ae,aggUpsertSql as j,jsonPathSql as F}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{param as se}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as le,GEO_DEFAULT_PRECISION as de}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{encodePartitionKey as ce,sortColumnName as ue,matchesRankStaticWhere as P,rankTableName as V}from"./RANK_TIEBREAK-D541BOFR.mjs";import{serializeSqlValue as K}from"./serializeSqlValue-DnpyaLcw.mjs";const fe=["de","en","es","fr","it","nl","none","pt"],$e=t=>fe.includes(t),me="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",Ee="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",he="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",ge="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",pe="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",ye="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",_e="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ê",be=/[\u0300-\u036F]/gu,J=t=>t.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase(),O=t=>new Set(J(t).split(" ")),Se={de:O(Ee),en:O(me),es:O(he),fr:O(ge),it:O(pe),nl:O(ye),none:new Set,pt:O(_e)},ve=2,Te=256,G=new Map,Ae=t=>{const o=t!==void 0&&$e(t)?t:"none",l=G.get(o);if(l)return l;const g=Se[o],v=r=>{const T=(J(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(A=>A.length<=Te);return g.size===0?T:T.filter(A=>!g.has(A))},m={document:v,profile:`${o}-v${String(ve)}`,query:r=>{const T=v(r);return T.filter((A,w)=>T.lastIndexOf(A)===w)}};return G.set(o,m),m},we=(t,o)=>{if(!o.includes("."))return t[o];let l=t;for(const g of o.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Re=(t,o)=>`${t}__fts_${o}`,Le="__text__",H="__id__",Oe=1e3,Ne=(t,o)=>o.document(t),k=(t,o)=>we(t,o),je=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",xe=(t,o,l)=>t!==void 0&&o!==void 0&&k(t,l.field)===k(o,l.field),Ie=(t,o)=>Ne(je(k(t,o.field)),Ae(o.language)).slice(0,Oe).join(" "),Fe=(t,o,l)=>[...t.partitionBy??[],...t.sortBy.map(g=>g.field),...t.where?Object.keys(t.where):[]].every(g=>o[g]===l[g]),X=t=>e.join(["__id__","__partition__",...t.sortBy.map((o,l)=>ue(l))].map(o=>e.identifier(o)),e`, `),Y=(t,o,l,g,v,m)=>{const r=ce(l.partitionBy??[],m),T=l.sortBy.map(w=>K(m[w.field]??null)),A=e.join([v,r,...T].map(w=>se(w)),e`, `);$(t,e`INSERT INTO ${e.identifier(o)} (${g}) VALUES (${A})`)},ke=(t,o,l,g,v,m)=>{if(v&&m&&Fe(l,v,m))return;const r=V(o,l.name);v&&$(t,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!P(m,l.where))&&Y(t,r,l,X(l),g,m)},Pe=t=>{const{broadcast:o,indexKeysFor:l,invalidateCache:g,recordCdc:v,schema:m,sql:r}=t,T=new Set,A=new Set,w=(i,n)=>{const s=`${i}::${n.name}`;if(T.has(s))return;const u=U(i,n.name),d=n.by??[],f=new Map,E=$(r,e`SELECT id, _creationTime, ${e.identifier(W)} FROM ${e.identifier(i)}`).toArray();for(const b of E){const a=B(b);if(!a||n.where&&!x(a,n.where))continue;const c=L(d,a);oe(f,c,n,a)}$(r,e`DELETE FROM ${e.identifier(u)}`);const p=32,h=[...f];for(let b=0;b<h.length;b+=p){const a=h.slice(b,b+p),c=e.join(a.map(([y,R])=>e`(${y}, ${R.value}, ${R.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(u)} (${N}, ${S}, ${_}) VALUES ${c}`)}T.add(s)},Q=(i,n,s)=>{const u=n.by??[],d=ie(n.op),f=n.field??"",E=[],p=(a,c)=>{const y=K(c);y===null?E.push(e`${F(a)} IS NULL`):E.push(e`${F(a)} = ${y}`)};for(const a of u)p(a,s[a]??null);for(const[a,c]of Object.entries(n.where??{}))p(a,c!==null&&typeof c=="object"&&!Array.isArray(c)?c.eq:c);const h=E.length>0?e` WHERE ${e.join(E,e` AND `)}`:e``,b=F(f);return{value:$(r,e`SELECT ${e.raw(d)}(${b}) AS value FROM ${e.identifier(i)}${h}`).one().value??null}},Z=(i,n,s,u)=>{const d=U(i,n.name),{op:f}=n,E=n.field??"",p=a=>{$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${N} = ${a} AND ${_} <= 0`)},h=s&&(!n.where||x(s,n.where))?s:void 0,b=u&&(!n.where||x(u,n.where))?u:void 0;if(!(!h&&!b)){if(f==="count"){for(const[a,c]of[[h,-1],[b,1]]){if(!a)continue;const y=L(n.by??[],a);$(r,j(d,y,c,c,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}h&&p(L(n.by??[],h));return}if(f==="sum"||f==="avg"){for(const[a,c]of[[h,-1],[b,1]]){if(!a)continue;const y=I(a[E]);if(y===void 0)continue;const R=L(n.by??[],a);$(r,j(d,R,c*y,c,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}h&&p(L(n.by??[],h));return}if(h){const a=L(n.by??[],h),c=I(h[E]),y=$(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(d)} WHERE ${N} = ${a}`).toArray()[0],R=(y?.count??0)-1;if(R<=0)$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${N} = ${a}`);else if(y&&c!==void 0&&y.value!==null&&c===y.value){const te=Q(i,n,h);$(r,e`UPDATE ${e.identifier(d)} SET ${S} = ${te.value}, ${_} = ${R} WHERE ${N} = ${a}`)}else $(r,e`UPDATE ${e.identifier(d)} SET ${_} = ${_} - 1 WHERE ${N} = ${a}`)}if(b){const a=L(n.by??[],b),c=I(b[E]);if(c===void 0)$(r,j(d,a,null,1,e`${_} = ${_} + 1`));else{const y=f==="min"?"MIN":"MAX";$(r,j(d,a,c,1,e`${S} = ${e.raw(y)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ee=i=>{for(const n of m.tables[i]?.aggregateIndexes??[])w(i,n)},q=(i,n,s)=>{for(const u of m.tables[i]?.aggregateIndexes??[])Z(i,u,n,s)},C=(i,n)=>{const s=`${i}::rank::${n.name}`;if(A.has(s))return;const u=V(i,n.name),d=$(r,e`SELECT id, _creationTime, ${e.identifier(W)} FROM ${e.identifier(i)}`).toArray();$(r,e`DELETE FROM ${e.identifier(u)}`);const f=X(n);for(const E of d){const p=B(E);!p||n.where&&!P(p,n.where)||Y(r,u,n,f,p._id,p)}A.add(s)},ne=i=>{for(const n of m.tables[i]?.rankIndexes??[])C(i,n)},M=(i,n,s,u)=>{for(const d of m.tables[i]?.rankIndexes??[])ke(r,i,d,n,s,u)},D=(i,n,s,u)=>{const d=m.tables[i]?.searchIndexes??[];if(!(d.length===0||!re(r)))for(const f of d){if(xe(u,s,f))continue;const E=Re(i,f.name);$(r,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier(H)} = ${n}`),s&&$(r,e`INSERT INTO ${e.identifier(E)} (${e.identifier(Le)}, ${e.identifier(H)}) VALUES (${Ie(s,f)}, ${n})`)}},z=(i,n,s)=>{for(const u of m.tables[i]?.geoIndexes??[]){const d=ae(i,u.name);$(r,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[u.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:E,lng:p}=f,h=le({lat:E,lng:p},u.precision??de);$(r,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${h}, ${E}, ${p})`)}}};return{ensureBackfilledForTable:ee,ensureBackfilledIndex:w,ensureRankBackfilled:C,ensureRankBackfilledForTable:ne,syncAggregates:q,syncCompanionsForInsert:(i,n,s)=>{D(i,n,s),z(i,n,s),q(i,void 0,s),M(i,n,void 0,s),g(i,n,s),v(i,n,"insert",s),o({indexKeys:l(i,s),key:n,op:"insert",row:s,table:i})},syncGeo:z,syncRanks:M,syncSearch:D}};export{X as O,H as T,Re as c,Pe as k,Le as l,Ne as n,Y as q,Ae as x,Ie as y};
@@ -1 +0,0 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-GHJiYnzm.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DhZLG0bn.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.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
- const r=n=>{try{const t=JSON.stringify(n);return t===void 0?0:t.length}catch{return}};export{r as t};
@@ -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-B6rnz3so.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-BR8MvZTz.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-D__2M4gX.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-BD3JiZn-.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{sql as m}from"drizzle-orm";import{MySqlDialect as s}from"drizzle-orm/mysql-core";import{PgDialect as l}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as n}from"drizzle-orm/sqlite-core";const p=new l,a=new s,i=new n,q={mysql:a,postgres:p,sqlite:i},w=(r,t)=>{const{params:e,sql:o}=q[r].sqlToQuery(t);return{params:e,sql:o}},D=r=>m`${r}`;export{D as param,w as renderSql};
@@ -1 +0,0 @@
1
- import{renderSql as t}from"./param-B5lF5Jd9.mjs";const n=(r,e,...l)=>r.exec.call(r,e,...l),c=(r,e)=>{const{params:l,sql:o}=t("sqlite",e);return n(r,o,...l)},s=r=>r??null,a=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{a as decodeJsonColumn,s as orNull,c as runDrizzle,n as runSql};
@@ -1,5 +0,0 @@
1
- import{l as I,T as N,c as l}from"./ctx-db-companions-7fIu-E2H.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as S}from"./aggregateTableName-DKo6dwBP.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{migrateCdcLog as p,migrateCdcMeta as h}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as t}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as b,jsonPathSql as E,createIndexSql as T,tableColumns as u,isFtsAvailable as X,AGG_KEY as x,AGG_VALUE as B,AGG_COUNT as c,geoTableName as G}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{sortColumnName as Y,rankTableName as F}from"./RANK_TIEBREAK-D541BOFR.mjs";import{recordSchemaVersion as M}from"./SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";const D=(r,o,a)=>{for(const i of a.indexes){const n=`${o}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);t(r,T(n,o,s,i.unique??!1))}for(const[i,n]of u(a)){if(!n.unique)continue;const s=`${o}_unique_${i}`;t(r,T(s,o,E(i),!0))}},k=(r,o,a)=>{if(!(!a.searchIndexes||a.searchIndexes.length===0||!X(r))){for(const i of a.searchIndexes){const n=l(o,i.name);t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,o,a)}},j=(r,o,a)=>{if(a.geoIndexes)for(const i of a.geoIndexes){const n=G(o,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=`${o}__geo_${i.name}__btree`;t(r,T(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,o,a)=>{if(a.aggregateIndexes)for(const i of a.aggregateIndexes){const n=S(o,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} 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 ${c} INTEGER NOT NULL DEFAULT 0`)}},y=(r,o,a)=>{if(a.rankIndexes)for(const i of a.rankIndexes){const n=F(o,i.name),s=i.sortBy.map((_,d)=>Y(d)),f=s.map(_=>e`${e.identifier(_)} 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 m=[e`${e.identifier("__partition__")} ASC`];for(const[_,d]of s.entries()){const L=i.sortBy[_]?.direction;m.push(e`${e.identifier(d)} ${e.raw(L==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const A=`${o}__rank_${i.name}__btree`;t(r,T(A,n,e.join(m,e`, `),!1))}},ne=(r,o,a={})=>{a.schemaSnapshot!==void 0&&M(r,a.schemaSnapshot.hash,a.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(o.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
- )`),D(r,i,n),k(r,i,n),j(r,i,n),q(r,i,n),y(r,i,n));a.cdc&&(p(r),h(r),R(r)),O(r),C(r)};export{ne 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 L}from"./runDrizzle-B6rnz3so.mjs";import{jsonPathSql as r}from"./AGG_COUNT-B0Pb1nQZ.mjs";const E=(s,i,a,o)=>{const d=a-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${d}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const f=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=L(s,f).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-B6rnz3so.mjs";import{DOC_COLUMN as a,rowToDocument as c,jsonPathSql as u}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{compileWhereSql as h}from"./compileWhereSql-B4rPariq.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-DnpyaLcw.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(o=>e`${o}`),e`, `)})`},p=(i,o)=>{const r=[];o&&r.push(o);const t=h(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},C=(i,o,r)=>{const t=p(r,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(a)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of d){const f=c(s),{id:l}=s;f!==void 0&&typeof l=="string"&&n.push({doc:f,id:l})}return n},D=(i,o,r,t)=>{if(t.length===0)return new Set;const d=p(r,E(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{D as selectShapeMemberIds,C as selectShapeRows};
@@ -1 +0,0 @@
1
- const e=t=>typeof t=="boolean"?t?1:0:t===null||typeof t=="string"||typeof t=="number"?t:typeof t=="bigint"?t.toString():JSON.stringify(t);export{e as serializeSqlValue};
@@ -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-D_fiax9d.mjs";const i=t=>r(e(t));export{i as stableWireKey};
@@ -1 +0,0 @@
1
- const b=r=>{let n="";for(let u=0;u<r.length;u+=32768)n+=String.fromCharCode(...r.subarray(u,u+32768));return btoa(n)},g=r=>{const n=atob(r),u=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)u[c]=n.codePointAt(c)??0;return u},o="$lunora.wire$";const p="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},d={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},m=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},s=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const u=typeof r;if(u==="bigint")return[o,"bigint",r.toString()];if(u==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(u!=="object")return r;if(r instanceof Date)return[o,"date",s(r.getTime(),n+1)];if(r instanceof Error){const e=r,a={};for(const l of Object.keys(e))e[l]!==void 0&&(a[l]=s(e[l],n+1));const i=[o,"error",e.name,e.message,a];return e.cause!==void 0&&i.push(s(e.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,a])=>[s(e,n+1),s(a,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>s(e,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,a=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return a==="Uint8Array"?[o,"bytes",b(i)]:[o,"bytes",b(i),a]}if(Array.isArray(r)){const e=r.map(a=>s(a,n+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!m(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 c=r,t={};for(const e of Object.keys(c)){const a=c[e];if(a===void 0)continue;const i=s(a,n+1);e===p?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}return t},f=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>f(t,n+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>1024||!/^-?\d+$/.test(t))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(t)}case"date":return new Date(f(r[2],n+1));case"map":return new Map(r[2].map(([t,e])=>[f(t,n+1),f(e,n+1)]));case"set":return new Set(r[2].map(t=>f(t,n+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],a=(Object.hasOwn(d,t)?d[t]:void 0)??Error,i=new a(e);i.name!==t&&Object.defineProperty(i,"name",{configurable:!0,value:t,writable:!0});const l=f(r[4],n+1);for(const y of Object.keys(l))y===p?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:l[y],writable:!0}):i[y]=l[y];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],n+1),writable:!0}),i}case"bytes":{const t=g(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const a=Object.hasOwn(w,e)?w[e]:void 0;return a?new a(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>f(t,n+1))}return r.map(t=>f(t,n+1))}const u=r,c={};for(const t of Object.keys(u)){const e=f(u[t],n+1);t===p?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[t]=e}return c};export{s as a,f as s};