solve-engine 2.24.0 → 2.25.0

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 (186) hide show
  1. package/dist/{BytecodeBuilder-aqVa7Plx.d.cts → BytecodeBuilder-DSWKZi4f.d.cts} +11 -9
  2. package/dist/{BytecodeBuilder-aqVa7Plx.d.ts → BytecodeBuilder-DSWKZi4f.d.ts} +11 -9
  3. package/dist/{EngineError-D1kXsjIj.d.cts → EngineError-fR1K1rvx.d.cts} +2 -0
  4. package/dist/{EngineError-D1kXsjIj.d.ts → EngineError-fR1K1rvx.d.ts} +2 -0
  5. package/dist/{Lexer-CqagTewQ.d.ts → Lexer-Bmctxl0n.d.ts} +84 -35
  6. package/dist/{Lexer-CCHFDcgP.d.cts → Lexer-aB95pjoX.d.cts} +84 -35
  7. package/dist/{PackageCompatibility-Bq82y0ZN.d.ts → PackageCompatibility-BludTs7v.d.ts} +1 -1
  8. package/dist/{PackageCompatibility-CeAPVHZr.d.cts → PackageCompatibility-CUVg8tmt.d.cts} +1 -1
  9. package/dist/{PackageRegistry-CDEgfhT_.d.ts → PackageRegistry-DT-x32OM.d.ts} +54 -6
  10. package/dist/{PackageRegistry-B9-7fJGH.d.cts → PackageRegistry-Dvn4i2QK.d.cts} +54 -6
  11. package/dist/{Parselet-4oH5OuRt.d.cts → Parselet-BawfGuTF.d.cts} +7 -1
  12. package/dist/{Parselet-BwDqKFfK.d.ts → Parselet-DqTbbtWA.d.ts} +7 -1
  13. package/dist/{ScopeManager-BQBhlDAu.d.ts → ScopeManager-B636am7Y.d.ts} +2 -2
  14. package/dist/{ScopeManager-DrXB3Nvm.d.cts → ScopeManager-CdwX0VTw.d.cts} +2 -2
  15. package/dist/{TokenNormalizer-OTPS0Otq.d.ts → TokenNormalizer-CLBtiE8M.d.ts} +45 -26
  16. package/dist/{TokenNormalizer-MXaKLJ_m.d.cts → TokenNormalizer-CjTDmHgB.d.cts} +45 -26
  17. package/dist/{VMCheckpoints-BK32PTl2.d.cts → VMCheckpoints-CYqeq8IV.d.cts} +2 -2
  18. package/dist/{VMCheckpoints-C5jC92o3.d.ts → VMCheckpoints-DDlxNssY.d.ts} +2 -2
  19. package/dist/{WorkerError-DaNWQFp1.d.cts → WorkerError-B1dF3VYT.d.cts} +1 -1
  20. package/dist/{WorkerError-CVQbs6_D.d.ts → WorkerError-dneODN-u.d.ts} +1 -1
  21. package/dist/{chunk-CMZSK6FY.cjs → chunk-4BAUQE6A.cjs} +3 -3
  22. package/dist/{chunk-CMZSK6FY.cjs.map → chunk-4BAUQE6A.cjs.map} +1 -1
  23. package/dist/chunk-4BRTUFTH.js +2 -0
  24. package/dist/chunk-4BRTUFTH.js.map +1 -0
  25. package/dist/{chunk-UY3ID6JF.cjs → chunk-4NZXCHQL.cjs} +2 -2
  26. package/dist/chunk-4NZXCHQL.cjs.map +1 -0
  27. package/dist/chunk-57PSJQQW.js +3 -0
  28. package/dist/chunk-57PSJQQW.js.map +1 -0
  29. package/dist/chunk-634ILVMP.cjs +2 -0
  30. package/dist/{chunk-AUOE7MFI.cjs.map → chunk-634ILVMP.cjs.map} +1 -1
  31. package/dist/{chunk-3SHWTGTP.js → chunk-63ZOOUOL.js} +2 -2
  32. package/dist/{chunk-3SHWTGTP.js.map → chunk-63ZOOUOL.js.map} +1 -1
  33. package/dist/chunk-72PYPENZ.js +2 -0
  34. package/dist/chunk-72PYPENZ.js.map +1 -0
  35. package/dist/chunk-77KI7AKJ.cjs +2 -0
  36. package/dist/chunk-77KI7AKJ.cjs.map +1 -0
  37. package/dist/chunk-7DP57BA7.js +2 -0
  38. package/dist/chunk-7DP57BA7.js.map +1 -0
  39. package/dist/chunk-7N3IJSWF.js +5 -0
  40. package/dist/chunk-7N3IJSWF.js.map +1 -0
  41. package/dist/chunk-BMXYR5LI.cjs +2 -0
  42. package/dist/chunk-BMXYR5LI.cjs.map +1 -0
  43. package/dist/{chunk-HQ7BKXG7.js → chunk-DUYTXLO2.js} +2 -2
  44. package/dist/chunk-DUYTXLO2.js.map +1 -0
  45. package/dist/chunk-EL2XUOWX.js +2 -0
  46. package/dist/chunk-EL2XUOWX.js.map +1 -0
  47. package/dist/{chunk-MWWAKZOD.cjs → chunk-FYAMQFZZ.cjs} +3 -3
  48. package/dist/{chunk-MWWAKZOD.cjs.map → chunk-FYAMQFZZ.cjs.map} +1 -1
  49. package/dist/chunk-FYTB7SDP.cjs +2 -0
  50. package/dist/chunk-FYTB7SDP.cjs.map +1 -0
  51. package/dist/chunk-GBCN7FNV.cjs +2 -0
  52. package/dist/chunk-GBCN7FNV.cjs.map +1 -0
  53. package/dist/{chunk-PTQCHMYA.js → chunk-JFZ5SLF7.js} +2 -2
  54. package/dist/{chunk-PTQCHMYA.js.map → chunk-JFZ5SLF7.js.map} +1 -1
  55. package/dist/{chunk-RMCN5WFO.cjs → chunk-JSM3O7EM.cjs} +2 -2
  56. package/dist/{chunk-RMCN5WFO.cjs.map → chunk-JSM3O7EM.cjs.map} +1 -1
  57. package/dist/chunk-MZMA32NE.js +3 -0
  58. package/dist/chunk-MZMA32NE.js.map +1 -0
  59. package/dist/{chunk-D2Q2VFJ6.js → chunk-N4SSR7Q6.js} +2 -2
  60. package/dist/{chunk-D2Q2VFJ6.js.map → chunk-N4SSR7Q6.js.map} +1 -1
  61. package/dist/{chunk-RN3ISTM3.cjs → chunk-NEGZZB7F.cjs} +2 -2
  62. package/dist/{chunk-RN3ISTM3.cjs.map → chunk-NEGZZB7F.cjs.map} +1 -1
  63. package/dist/{chunk-IPSOWFCA.js → chunk-NMU5E7W7.js} +2 -2
  64. package/dist/{chunk-IPSOWFCA.js.map → chunk-NMU5E7W7.js.map} +1 -1
  65. package/dist/chunk-OB2VX4IL.js +2 -0
  66. package/dist/chunk-OB2VX4IL.js.map +1 -0
  67. package/dist/{chunk-OMHRBKAT.js → chunk-OONQ3V3I.js} +2 -2
  68. package/dist/{chunk-OMHRBKAT.js.map → chunk-OONQ3V3I.js.map} +1 -1
  69. package/dist/{chunk-LTJV3VJE.cjs → chunk-RAPEZR5L.cjs} +2 -2
  70. package/dist/{chunk-LTJV3VJE.cjs.map → chunk-RAPEZR5L.cjs.map} +1 -1
  71. package/dist/{chunk-UXR7JIPX.js → chunk-RDYXH7ML.js} +2 -2
  72. package/dist/{chunk-UXR7JIPX.js.map → chunk-RDYXH7ML.js.map} +1 -1
  73. package/dist/{chunk-CDNJZBM3.cjs → chunk-SAF3B3AX.cjs} +2 -2
  74. package/dist/{chunk-CDNJZBM3.cjs.map → chunk-SAF3B3AX.cjs.map} +1 -1
  75. package/dist/chunk-SPOVFRZO.cjs +5 -0
  76. package/dist/chunk-SPOVFRZO.cjs.map +1 -0
  77. package/dist/{chunk-DA7M6H63.cjs → chunk-SQHBOWES.cjs} +2 -2
  78. package/dist/{chunk-DA7M6H63.cjs.map → chunk-SQHBOWES.cjs.map} +1 -1
  79. package/dist/{chunk-2BXNZM3G.js → chunk-UF5XMZTT.js} +2 -2
  80. package/dist/{chunk-2BXNZM3G.js.map → chunk-UF5XMZTT.js.map} +1 -1
  81. package/dist/chunk-UV3EUIBT.cjs +3 -0
  82. package/dist/chunk-UV3EUIBT.cjs.map +1 -0
  83. package/dist/chunk-VMSCRVNX.cjs +2 -0
  84. package/dist/chunk-VMSCRVNX.cjs.map +1 -0
  85. package/dist/{chunk-2VE4OW4A.cjs → chunk-WGP4UUO5.cjs} +2 -2
  86. package/dist/{chunk-2VE4OW4A.cjs.map → chunk-WGP4UUO5.cjs.map} +1 -1
  87. package/dist/{chunk-F7QIBC4B.cjs → chunk-XBGK3TTU.cjs} +3 -3
  88. package/dist/{chunk-F7QIBC4B.cjs.map → chunk-XBGK3TTU.cjs.map} +1 -1
  89. package/dist/{chunk-GP4H5OIT.js → chunk-XHQYHXRE.js} +3 -3
  90. package/dist/{chunk-GP4H5OIT.js.map → chunk-XHQYHXRE.js.map} +1 -1
  91. package/dist/{chunk-RE6AIU6Y.js → chunk-XX55RR4Q.js} +3 -3
  92. package/dist/{chunk-RE6AIU6Y.js.map → chunk-XX55RR4Q.js.map} +1 -1
  93. package/dist/chunk-YBQPEWT7.cjs +3 -0
  94. package/dist/chunk-YBQPEWT7.cjs.map +1 -0
  95. package/dist/{chunk-7EP36NXE.js → chunk-ZDCZ5IDD.js} +3 -3
  96. package/dist/{chunk-7EP36NXE.js.map → chunk-ZDCZ5IDD.js.map} +1 -1
  97. package/dist/constants.cjs +1 -1
  98. package/dist/constants.js +1 -1
  99. package/dist/engine.cjs +1 -1
  100. package/dist/engine.d.cts +9 -9
  101. package/dist/engine.d.ts +9 -9
  102. package/dist/engine.js +1 -1
  103. package/dist/errors.cjs +1 -1
  104. package/dist/errors.d.cts +3 -3
  105. package/dist/errors.d.ts +3 -3
  106. package/dist/errors.js +1 -1
  107. package/dist/format.cjs +1 -1
  108. package/dist/format.js +1 -1
  109. package/dist/index.cjs +1 -1
  110. package/dist/index.d.cts +9 -9
  111. package/dist/index.d.ts +9 -9
  112. package/dist/index.js +1 -1
  113. package/dist/language.d.cts +8 -8
  114. package/dist/language.d.ts +8 -8
  115. package/dist/lexer.cjs +1 -1
  116. package/dist/lexer.cjs.map +1 -1
  117. package/dist/lexer.d.cts +8 -7
  118. package/dist/lexer.d.ts +8 -7
  119. package/dist/lexer.js +1 -1
  120. package/dist/lexer.js.map +1 -1
  121. package/dist/normalizer.cjs +1 -1
  122. package/dist/normalizer.d.cts +2 -2
  123. package/dist/normalizer.d.ts +2 -2
  124. package/dist/normalizer.js +1 -1
  125. package/dist/packages.cjs +1 -1
  126. package/dist/packages.d.cts +7 -7
  127. package/dist/packages.d.ts +7 -7
  128. package/dist/packages.js +1 -1
  129. package/dist/parser.cjs +1 -1
  130. package/dist/parser.d.cts +2 -2
  131. package/dist/parser.d.ts +2 -2
  132. package/dist/parser.js +1 -1
  133. package/dist/resolvers.d.cts +1 -1
  134. package/dist/resolvers.d.ts +1 -1
  135. package/dist/testing.cjs +2 -2
  136. package/dist/testing.d.cts +8 -8
  137. package/dist/testing.d.ts +8 -8
  138. package/dist/testing.js +1 -1
  139. package/dist/uom.cjs +1 -1
  140. package/dist/uom.d.cts +1 -1
  141. package/dist/uom.d.ts +1 -1
  142. package/dist/uom.js +1 -1
  143. package/dist/vm.cjs +1 -1
  144. package/dist/vm.d.cts +5 -5
  145. package/dist/vm.d.ts +5 -5
  146. package/dist/vm.js +1 -1
  147. package/dist/worker.cjs +2 -2
  148. package/dist/worker.d.cts +8 -8
  149. package/dist/worker.d.ts +8 -8
  150. package/dist/worker.js +1 -1
  151. package/package.json +5 -5
  152. package/dist/chunk-2JSNWYYA.cjs +0 -3
  153. package/dist/chunk-2JSNWYYA.cjs.map +0 -1
  154. package/dist/chunk-5GL4SAVH.cjs +0 -2
  155. package/dist/chunk-5GL4SAVH.cjs.map +0 -1
  156. package/dist/chunk-72N3ZRVE.cjs +0 -2
  157. package/dist/chunk-72N3ZRVE.cjs.map +0 -1
  158. package/dist/chunk-A4JV7HRB.js +0 -3
  159. package/dist/chunk-A4JV7HRB.js.map +0 -1
  160. package/dist/chunk-AUOE7MFI.cjs +0 -2
  161. package/dist/chunk-BDF4VCQX.js +0 -3
  162. package/dist/chunk-BDF4VCQX.js.map +0 -1
  163. package/dist/chunk-ELQQKZN3.cjs +0 -3
  164. package/dist/chunk-ELQQKZN3.cjs.map +0 -1
  165. package/dist/chunk-HQ7BKXG7.js.map +0 -1
  166. package/dist/chunk-IHAZL4EF.cjs +0 -2
  167. package/dist/chunk-IHAZL4EF.cjs.map +0 -1
  168. package/dist/chunk-LM6ZQUEU.js +0 -2
  169. package/dist/chunk-LM6ZQUEU.js.map +0 -1
  170. package/dist/chunk-NUF66H57.js +0 -5
  171. package/dist/chunk-NUF66H57.js.map +0 -1
  172. package/dist/chunk-PWWQZFAE.js +0 -2
  173. package/dist/chunk-PWWQZFAE.js.map +0 -1
  174. package/dist/chunk-RECRD45C.cjs +0 -5
  175. package/dist/chunk-RECRD45C.cjs.map +0 -1
  176. package/dist/chunk-RENO2AWO.js +0 -2
  177. package/dist/chunk-RENO2AWO.js.map +0 -1
  178. package/dist/chunk-S46R5QZP.cjs +0 -2
  179. package/dist/chunk-S46R5QZP.cjs.map +0 -1
  180. package/dist/chunk-UPH22K2T.cjs +0 -2
  181. package/dist/chunk-UPH22K2T.cjs.map +0 -1
  182. package/dist/chunk-UY3ID6JF.cjs.map +0 -1
  183. package/dist/chunk-WFOQRPA6.js +0 -2
  184. package/dist/chunk-WFOQRPA6.js.map +0 -1
  185. package/dist/chunk-XFJABR3B.js +0 -2
  186. package/dist/chunk-XFJABR3B.js.map +0 -1
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkR2SZFJTT_cjs=require('./chunk-R2SZFJTT.cjs'),chunk5TVI2UPZ_cjs=require('./chunk-5TVI2UPZ.cjs'),chunk2VE4OW4A_cjs=require('./chunk-2VE4OW4A.cjs'),chunkDA7M6H63_cjs=require('./chunk-DA7M6H63.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs');var x={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function P(t,e,o,r){let n=o.floatResult.enableSeperator,a=o.numberResult.decimalSeparatorLocale;if(r!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(a||"en-US",{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:n});return `${e.display.resultPrefix}${c}`}let i=o.floatResult.decimalPlaces,s=chunkR2SZFJTT_cjs.a(t,i,n,a);return `${e.display.resultPrefix}${s}`}function T(t,e,o,r){let n=r.floatResult.decimalPlaces,a=r.floatResult.enableSeperator,i=r.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(n,1),c=t.toLocaleString(i,{useGrouping:a,minimumFractionDigits:0,maximumFractionDigits:n}),l=Math.abs(e).toLocaleString(i,{useGrouping:a,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${l}`}function w(t,e,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let r=typeof t=="bigint"?t<0n:t<0,n=r?"-":"",a=c=>typeof t=="bigint"?(r?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${n}0b${a(2)}`;if(o==="oct")return `= ${n}0o${a(8)}`;let i=e.hexResult.enablePadding?e.hexResult.paddingZeros:0,s=a(16).toUpperCase().padStart(i,"0");return `= ${n}0x${s}`}var N=2e4;function U(t){let e=t<0n?-t:t;if(Number.isFinite(Number(e)))return `= ${t}`;let o=e.toString(16).length*4;if(o*Math.LN2/Math.LN10<=N)return `= ${t}`;let r=o*Math.LN2/Math.LN10,n=Math.floor(r),a=Math.pow(10,r-n);return `= ${t<0n?"-":""}~${a.toFixed(3)}e+${n} (an exact integer of about ${(n+1).toLocaleString("en-US")} digits, too large to print)`}function C(t){return `= ${t}`}function E(t){return `= ${t}`}function G(t,e,o){let r=new Date(t),n=o.dateResult?.format??"long",a=r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getMilliseconds()===0;if(n==="long"){let g=r.toLocaleDateString(e.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return a?`= ${g}`:`= ${g}, ${r.toLocaleTimeString(e.code)}`}let i=g=>String(g).padStart(2,"0"),s=r.getFullYear(),c=i(r.getMonth()+1),l=i(r.getDate()),u;if(n==="iso"?u=`${s}-${c}-${l}`:n==="dmy"?u=`${l}/${c}/${s}`:u=`${c}/${l}/${s}`,a)return `= ${u}`;let m=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return n==="iso"?`= ${u}T${m}`:`= ${u} ${m}`}function j(t){let e=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),r=Math.floor(o/3600),n=Math.floor(o%3600/60),a=o%60,i=String(n).padStart(2,"0");if(a===0)return `${e}${r}:${i}`;let s=String(a).padStart(2,"0");return `${e}${r}:${i}:${s}`}var L=new Map;function k(t){let e=L.get(t);return e===void 0&&(e=new Intl.NumberFormat(t).formatToParts(1.1).find(o=>o.type==="decimal")?.value??".",L.set(t,e)),e}function f(t,e,o){let r=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return t;let[,n,a,i]=r,s=o?BigInt(a).toLocaleString(e,{useGrouping:true}):a;return i===void 0?`${n}${s}`:`${n}${s}${k(e)}${i}`}function A(t,e,o,r,n){if(e==="ms")return `= ${j(t)}`;e==="l100km"&&(e="l/100km"),e==="mps2"&&(e="m/s\xB2");let a=r.unitOfMeasurementResult.decimalPlaces,i=r.floatResult.enableSeperator,s=r.numberResult.decimalSeparatorLocale||"en-US",l=e&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(e),u;l&&t===Math.floor(t)?u=f(t.toString(),s,i):u=f(t.toFixed(a),s,i);let m=e?chunk2VE4OW4A_cjs.ua[e.toUpperCase()]:void 0;if(m){let h=n?f(chunk2VE4OW4A_cjs.sa(n,a),s,i):u,y=m.spaced?" ":"";return `= ${m.position==="prefix"?`${m.symbol}${y}${h}`:`${h}${y}${m.symbol}`}`}return `= ${n?f(chunk2VE4OW4A_cjs.sa(n,a),s,i):u} ${e||""}`.trim()}function I(t,e){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return chunk2VE4OW4A_cjs.R(t);let o=e.floatResult.decimalPlaces,r=e.floatResult.enableSeperator,n=e.numberResult.decimalSeparatorLocale;return chunkR2SZFJTT_cjs.a(t,o,r,n)}function O(t,e,o){let r=chunk2VE4OW4A_cjs.Z(t),n=[];for(let a=0;a<t.rows;a++){let i=[];for(let s=0;s<t.cols;s++)i.push(I(r[a*t.cols+s],o));n.push(i.join(", "));}return `${e.display.resultPrefix}[${n.join("; ")}]`}function at(t,e){let o=e||x,r=chunk2VE4OW4A_cjs.Z(t),n=[];for(let i=0;i<t.rows;i++){let s=[];for(let c=0;c<t.cols;c++)s.push(I(r[i*t.cols+c],o));n.push(s);}let a=[];for(let i=0;i<t.cols;i++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,n[c][i].length);a.push(s);}return n.map(i=>`[ ${i.map((s,c)=>s.padStart(a[c])).join(" ")} ]`).join(`
2
- `)}function _(t,e,o){return `${o.display.resultPrefix}${t}:${e}`}function B(t,e,o){let r=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(r)}${e.display.percentageSuffix}`}function H(t,e){return `= ${t} ${e||""}`.trim()}function V(t){if(t.addr===void 0)return `/${t.prefix}`;let e=chunk5TVI2UPZ_cjs.D(t.addr);return t.prefix===void 0?e:`${e}/${t.prefix}`}function Y(t,e,o){let r=e.display.resultPrefix,n=l=>{let u=t.unit!==void 0?new chunkDA7M6H63_cjs.m(6,l.value,t.unit):new chunkDA7M6H63_cjs.m(0,l.value);u.exact=l.exact;let m=W(u,o);return m.startsWith(r)?m.slice(r.length):m},[a,i]=t.shares,s=`${n(a)} each`;if(i===void 0)return `${r}${s}`;let c=i.count===1?"share":"shares";return `${r}${s}, with ${i.count} ${c} paying ${n(i)}`}function W(t,e){let o=e||x,r=o.numberResult.decimalSeparatorLocale||"en",n=chunkS3DFU33X_cjs.a(r);switch(t.type){case 0:return t.uncertainty!==void 0?T(t.value,t.uncertainty,n,o):P(t.value,n,o,t.decimalPlaces);case 1:return w(t.value,o,t.unit);case 2:return U(t.value);case 3:return C(t.value);case 10:return E(t.value);case 4:return G(t.value,n,o);case 6:return A(t.value,t.unit,n,o,t.exact);case 7:return O(t.value,n,o);case 8:{let a=t.value;return _(a.min,a.max,n)}case 14:return `${n.display.resultPrefix}${chunk5TVI2UPZ_cjs.g(t.value)}`;case 15:return Y(t.value,n,o);case 16:return `${n.display.resultPrefix}${t.value.label}`;case 17:return `${n.display.resultPrefix}${V(t.value)}`;case 9:return chunk2VE4OW4A_cjs.R(t.value);case 5:return B(t.value,n,o);case 11:return H(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}exports.a=x;exports.b=at;exports.c=W;//# sourceMappingURL=chunk-F7QIBC4B.cjs.map
3
- //# sourceMappingURL=chunk-F7QIBC4B.cjs.map
1
+ 'use strict';var chunkR2SZFJTT_cjs=require('./chunk-R2SZFJTT.cjs'),chunk5TVI2UPZ_cjs=require('./chunk-5TVI2UPZ.cjs'),chunkWGP4UUO5_cjs=require('./chunk-WGP4UUO5.cjs'),chunkSQHBOWES_cjs=require('./chunk-SQHBOWES.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs');var x={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function P(t,e,o,r){let n=o.floatResult.enableSeperator,a=o.numberResult.decimalSeparatorLocale;if(r!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(a||"en-US",{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:n});return `${e.display.resultPrefix}${c}`}let i=o.floatResult.decimalPlaces,s=chunkR2SZFJTT_cjs.a(t,i,n,a);return `${e.display.resultPrefix}${s}`}function T(t,e,o,r){let n=r.floatResult.decimalPlaces,a=r.floatResult.enableSeperator,i=r.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(n,1),c=t.toLocaleString(i,{useGrouping:a,minimumFractionDigits:0,maximumFractionDigits:n}),l=Math.abs(e).toLocaleString(i,{useGrouping:a,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${l}`}function w(t,e,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let r=typeof t=="bigint"?t<0n:t<0,n=r?"-":"",a=c=>typeof t=="bigint"?(r?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${n}0b${a(2)}`;if(o==="oct")return `= ${n}0o${a(8)}`;let i=e.hexResult.enablePadding?e.hexResult.paddingZeros:0,s=a(16).toUpperCase().padStart(i,"0");return `= ${n}0x${s}`}var N=2e4;function U(t){let e=t<0n?-t:t;if(Number.isFinite(Number(e)))return `= ${t}`;let o=e.toString(16).length*4;if(o*Math.LN2/Math.LN10<=N)return `= ${t}`;let r=o*Math.LN2/Math.LN10,n=Math.floor(r),a=Math.pow(10,r-n);return `= ${t<0n?"-":""}~${a.toFixed(3)}e+${n} (an exact integer of about ${(n+1).toLocaleString("en-US")} digits, too large to print)`}function C(t){return `= ${t}`}function E(t){return `= ${t}`}function G(t,e,o){let r=new Date(t),n=o.dateResult?.format??"long",a=r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getMilliseconds()===0;if(n==="long"){let g=r.toLocaleDateString(e.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return a?`= ${g}`:`= ${g}, ${r.toLocaleTimeString(e.code)}`}let i=g=>String(g).padStart(2,"0"),s=r.getFullYear(),c=i(r.getMonth()+1),l=i(r.getDate()),u;if(n==="iso"?u=`${s}-${c}-${l}`:n==="dmy"?u=`${l}/${c}/${s}`:u=`${c}/${l}/${s}`,a)return `= ${u}`;let m=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return n==="iso"?`= ${u}T${m}`:`= ${u} ${m}`}function j(t){let e=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),r=Math.floor(o/3600),n=Math.floor(o%3600/60),a=o%60,i=String(n).padStart(2,"0");if(a===0)return `${e}${r}:${i}`;let s=String(a).padStart(2,"0");return `${e}${r}:${i}:${s}`}var L=new Map;function k(t){let e=L.get(t);return e===void 0&&(e=new Intl.NumberFormat(t).formatToParts(1.1).find(o=>o.type==="decimal")?.value??".",L.set(t,e)),e}function f(t,e,o){let r=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return t;let[,n,a,i]=r,s=o?BigInt(a).toLocaleString(e,{useGrouping:true}):a;return i===void 0?`${n}${s}`:`${n}${s}${k(e)}${i}`}function A(t,e,o,r,n){if(e==="ms")return `= ${j(t)}`;e==="l100km"&&(e="l/100km"),e==="mps2"&&(e="m/s\xB2");let a=r.unitOfMeasurementResult.decimalPlaces,i=r.floatResult.enableSeperator,s=r.numberResult.decimalSeparatorLocale||"en-US",l=e&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(e),u;l&&t===Math.floor(t)?u=f(t.toString(),s,i):u=f(t.toFixed(a),s,i);let m=e?chunkWGP4UUO5_cjs.ua[e.toUpperCase()]:void 0;if(m){let h=n?f(chunkWGP4UUO5_cjs.sa(n,a),s,i):u,y=m.spaced?" ":"";return `= ${m.position==="prefix"?`${m.symbol}${y}${h}`:`${h}${y}${m.symbol}`}`}return `= ${n?f(chunkWGP4UUO5_cjs.sa(n,a),s,i):u} ${e||""}`.trim()}function I(t,e){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return chunkWGP4UUO5_cjs.R(t);let o=e.floatResult.decimalPlaces,r=e.floatResult.enableSeperator,n=e.numberResult.decimalSeparatorLocale;return chunkR2SZFJTT_cjs.a(t,o,r,n)}function O(t,e,o){let r=chunkWGP4UUO5_cjs.Z(t),n=[];for(let a=0;a<t.rows;a++){let i=[];for(let s=0;s<t.cols;s++)i.push(I(r[a*t.cols+s],o));n.push(i.join(", "));}return `${e.display.resultPrefix}[${n.join("; ")}]`}function at(t,e){let o=e||x,r=chunkWGP4UUO5_cjs.Z(t),n=[];for(let i=0;i<t.rows;i++){let s=[];for(let c=0;c<t.cols;c++)s.push(I(r[i*t.cols+c],o));n.push(s);}let a=[];for(let i=0;i<t.cols;i++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,n[c][i].length);a.push(s);}return n.map(i=>`[ ${i.map((s,c)=>s.padStart(a[c])).join(" ")} ]`).join(`
2
+ `)}function _(t,e,o){return `${o.display.resultPrefix}${t}:${e}`}function B(t,e,o){let r=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(r)}${e.display.percentageSuffix}`}function H(t,e){return `= ${t} ${e||""}`.trim()}function V(t){if(t.addr===void 0)return `/${t.prefix}`;let e=chunk5TVI2UPZ_cjs.D(t.addr);return t.prefix===void 0?e:`${e}/${t.prefix}`}function Y(t,e,o){let r=e.display.resultPrefix,n=l=>{let u=t.unit!==void 0?new chunkSQHBOWES_cjs.m(6,l.value,t.unit):new chunkSQHBOWES_cjs.m(0,l.value);u.exact=l.exact;let m=W(u,o);return m.startsWith(r)?m.slice(r.length):m},[a,i]=t.shares,s=`${n(a)} each`;if(i===void 0)return `${r}${s}`;let c=i.count===1?"share":"shares";return `${r}${s}, with ${i.count} ${c} paying ${n(i)}`}function W(t,e){let o=e||x,r=o.numberResult.decimalSeparatorLocale||"en",n=chunkS3DFU33X_cjs.a(r);switch(t.type){case 0:return t.uncertainty!==void 0?T(t.value,t.uncertainty,n,o):P(t.value,n,o,t.decimalPlaces);case 1:return w(t.value,o,t.unit);case 2:return U(t.value);case 3:return C(t.value);case 10:return E(t.value);case 4:return G(t.value,n,o);case 6:return A(t.value,t.unit,n,o,t.exact);case 7:return O(t.value,n,o);case 8:{let a=t.value;return _(a.min,a.max,n)}case 14:return `${n.display.resultPrefix}${chunk5TVI2UPZ_cjs.g(t.value)}`;case 15:return Y(t.value,n,o);case 16:return `${n.display.resultPrefix}${t.value.label}`;case 17:return `${n.display.resultPrefix}${V(t.value)}`;case 9:return chunkWGP4UUO5_cjs.R(t.value);case 5:return B(t.value,n,o);case 11:return H(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}exports.a=x;exports.b=at;exports.c=W;//# sourceMappingURL=chunk-XBGK3TTU.cjs.map
3
+ //# sourceMappingURL=chunk-XBGK3TTU.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["DEFAULT_FORMATTING_SETTINGS","formatNumber","value","locale","settings","decimalPlaces","sep","loc","formatted","dp","autoFormatIntegerOrFloat","formatUncertain","center","uncertainty","useGrouping","spreadMax","centerText","spreadText","formatHex","base","negative","sign","digits","radix","padding","hex","MAX_DISPLAYED_BIGINT_DIGITS","formatBigInt","magnitude","bits","log10","exponent","mantissa","formatString","formatBoolean","formatDatetime","d","format","isMidnight","dateStr","p2","n","year","month","day","datePart","time","formatMsDuration","ms","totalSeconds","hours","minutes","seconds","mm","ss","decimalMarkByLocale","decimalMark","mark","part","localiseFixedDecimal","fixed","match","integer","fraction","integerText","formatUom","unit","exact","isTimeSpan","currencyDisplay","CURRENCY_DISPLAY","moneyText","decimalToFixed","formatMatrixEntry","entry","formatSymbolic","formatMatrix","m","rowMajor","columnMajorToRowMajor","rows","r","cells","c","formatMatrixAligned","us","row","colWidth","width","cell","formatRange","min","max","formatPercentage","formatUnit","formatIpCidr","data","dotted","formatIp","formatSplit","prefix","render","share","v","Value","text","formatValue","high","each","shareWord","localeCode","getLocale","formatColour"],"mappings":"2QA8CO,IAAMA,CAAAA,CAAkD,CAC7D,WAAA,CAAa,CACX,aAAA,CAAe,CAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CACA,YAAA,CAAc,CACZ,sBAAA,CAAwB,OAC1B,CAAA,CACA,SAAA,CAAW,CACT,aAAA,CAAe,KAAA,CACf,YAAA,CAAc,CAChB,CAAA,CACA,uBAAA,CAAyB,CACvB,aAAA,CAAe,CACjB,CAAA,CACA,gBAAA,CAAkB,CAChB,aAAA,CAAe,CACjB,CAAA,CACA,UAAA,CAAY,CACV,MAAA,CAAQ,MACV,CACF,ECxDA,SAASC,CAAAA,CAAaC,CAAAA,CAAeC,CAAAA,CAAiBC,CAAAA,CAA8BC,CAAAA,CAAgC,CAClH,IAAMC,CAAAA,CAAMF,EAAS,WAAA,CAAY,eAAA,CAC3BG,CAAAA,CAAMH,CAAAA,CAAS,YAAA,CAAa,sBAAA,CAMlC,GAAIC,CAAAA,GAAkB,MAAA,EAAa,MAAA,CAAO,QAAA,CAASH,CAAK,CAAA,CAAG,CACzD,IAAMM,CAAAA,CAAYN,EAAM,cAAA,CAAeK,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A,EAAG6G,mBAAAA,CAAa9G,EAAM,KAAmB,CAAC,GACjF,KAAA,EAAA,CACE,OAAOiG,EAAYjG,CAAAA,CAAM,KAAA,CAAoBC,EAAQkF,CAAE,CAAA,CACzD,QAGE,OAAO,CAAA,EAAGlF,EAAO,OAAA,CAAQ,YAAY,GAAID,CAAAA,CAAM,KAAA,CAAoB,KAAK,CAAA,CAAA,CAC1E,KAAA,EAAA,CACE,OAAO,CAAA,EAAGC,CAAAA,CAAO,QAAQ,YAAY,CAAA,EAAG4F,EAAa7F,CAAAA,CAAM,KAAmB,CAAC,CAAA,CAAA,CACjF,KAAA,CAAA,CACE,OAAOyE,mBAAAA,CAAezE,CAAAA,CAAM,KAAqB,CAAA,CACnD,KAAA,CAAA,CACE,OAAO2F,CAAAA,CAAiB3F,CAAAA,CAAM,MAAiBC,CAAAA,CAAQkF,CAAE,EAC3D,KAAA,EAAA,CACE,OAAOS,EAAW5F,CAAAA,CAAM,KAAA,CAAiBA,EAAM,IAAI,CAAA,CACrD,QAKE,OAAOA,CAAAA,CAAM,MAAQ,MAAA,CAAOA,CAAAA,CAAM,KAAK,CAAA,CACzC,QACE,OAAO,CAAA,EAAA,EAAK,MAAA,CAAOA,EAAM,KAAK,CAAC,EACnC,CACF","file":"chunk-F7QIBC4B.cjs","sourcesContent":["/**\n * How a Datetime value is rendered.\n *\n * - `'long'`: the spelled-out form, \"Tuesday, March 10, 2026\" (the default).\n * - `'iso'`: \"2026-03-10\" (ISO 8601, with a `T`-separated time when present).\n * - `'dmy'`: \"10/03/2026\" (day first).\n * - `'mdy'`: \"03/10/2026\" (month first).\n *\n * The weekday and long month name in `'long'` are localised through the same\n * locale the number separators come from; the numeric forms are locale-neutral.\n */\nexport type DateOutputFormat = \"long\" | \"iso\" | \"dmy\" | \"mdy\";\n\n/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n /**\n * Optional so a host that built a `FormattingSettings` before this field\n * existed still compiles; a missing `dateResult` reads as `'long'`, the\n * historic output.\n */\n dateResult?: {\n format: DateOutputFormat;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n dateResult: {\n format: \"long\",\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type SplitData, type SplitShare, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { formatIp } from \"@solve-js/packages/ip/IpMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale, settings: FormattingSettings): string {\n const d = new Date(value);\n const format = settings.dateResult?.format ?? \"long\";\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n\n // The spelled-out default, localised through the locale's own names.\n if (format === \"long\") {\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n }\n\n // The numeric forms, built from the local calendar fields so they read the\n // same regardless of the JS runtime's own default locale.\n const p2 = (n: number) => String(n).padStart(2, \"0\");\n const year = d.getFullYear();\n const month = p2(d.getMonth() + 1);\n const day = p2(d.getDate());\n let datePart: string;\n if (format === \"iso\") datePart = `${year}-${month}-${day}`;\n else if (format === \"dmy\") datePart = `${day}/${month}/${year}`;\n else datePart = `${month}/${day}/${year}`; // mdy\n\n if (isMidnight) return `= ${datePart}`;\n const time = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;\n // ISO joins date and time with `T`; the slash forms with a space.\n return format === \"iso\" ? `= ${datePart}T${time}` : `= ${datePart} ${time}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\n/** The decimal mark each locale writes, looked up once per locale rather than on every value. */\nconst decimalMarkByLocale = new Map<string, string>();\n\nfunction decimalMark(loc: string): string {\n let mark = decimalMarkByLocale.get(loc);\n if (mark === undefined) {\n mark = new Intl.NumberFormat(loc).formatToParts(1.1).find((part) => part.type === \"decimal\")?.value ?? \".\";\n decimalMarkByLocale.set(loc, mark);\n }\n return mark;\n}\n\n/**\n * Write a fixed-decimal string (`\"1234567.50\"`) the way `loc` writes numbers:\n * its decimal mark, and its digit grouping when `useGrouping` is on.\n *\n * Every quantity and every money amount used to be rendered with a bare\n * `toFixed`, so a plain `52000` showed as `52,000` while `£52000` showed as\n * `£52000.00`, and the `enableSeperator` setting had no effect on the one\n * value type people most want grouped. The digits are taken from the string\n * rather than re-rendered from the double, because an exact money amount has\n * already been rounded from its decimal (see {@link formatUom}) and\n * re-rendering would undo that. `BigInt` carries the integer part through\n * `Intl` so grouping follows the locale's own rule (Indian lakhs included)\n * rather than a hand-written every-three-digits. Anything that is not plain\n * digits, an `Infinity` or an exponent form, is returned as it came.\n */\nfunction localiseFixedDecimal(fixed: string, loc: string, useGrouping: boolean): string {\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?$/.exec(fixed);\n if (!match) return fixed;\n const [, sign, integer, fraction] = match;\n const integerText = useGrouping ? BigInt(integer).toLocaleString(loc, { useGrouping: true }) : integer;\n if (fraction === undefined) return `${sign}${integerText}`;\n return `${sign}${integerText}${decimalMark(loc)}${fraction}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n // A fuel-consumption unit is stored slash-free (so it is not read as a rate)\n // but shown the way it is written.\n if (unit === \"l100km\") unit = \"l/100km\";\n if (unit === \"mps2\") unit = \"m/s²\";\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"months\", \"years\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = localiseFixedDecimal(value.toString(), loc, useGrouping);\n } else {\n // For other values, use the configured decimal places\n formatted = localiseFixedDecimal(value.toFixed(dp), loc, useGrouping);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Renders a per-person bill split: \"= $45.00 each\", or, when the division is\n * uneven, \"= $33.33 each, with 1 share paying $33.34\". Each share's amount is\n * rendered through the ordinary value formatter (a throwaway {@link Value}), so\n * a currency share honours the same symbol placement, decimal places and locale\n * as any other money and a bare share trims trailing zeros the way a plain\n * number does; the \"= \" prefix is added once, around the whole sentence, not\n * per share.\n */\n/**\n * An IP/CIDR as text: the dotted quad, plus `/prefix` when present, or a bare\n * `/prefix` when there is no address (`netmask of /24` before it resolves).\n */\nfunction formatIpCidr(data: IpCidrData): string {\n\tif (data.addr === undefined) return `/${data.prefix}`;\n\tconst dotted = formatIp(data.addr);\n\treturn data.prefix === undefined ? dotted : `${dotted}/${data.prefix}`;\n}\n\nfunction formatSplit(data: SplitData, locale: ILocale, settings: FormattingSettings): string {\n const prefix = locale.display.resultPrefix;\n const render = (share: SplitShare): string => {\n const v = data.unit !== undefined\n ? new Value(ValueType.Uom, share.value, data.unit)\n : new Value(ValueType.Number, share.value);\n v.exact = share.exact;\n const text = formatValue(v, settings);\n return text.startsWith(prefix) ? text.slice(prefix.length) : text;\n };\n\n const [base, high] = data.shares;\n const each = `${render(base)} each`;\n if (high === undefined) return `${prefix}${each}`;\n const shareWord = high.count === 1 ? \"share\" : \"shares\";\n return `${prefix}${each}, with ${high.count} ${shareWord} paying ${render(high)}`;\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const value = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale, us);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Split:\n return formatSplit(value.value as SplitData, locale, us);\n case ValueType.Chart:\n // A chart is drawn from its data by the host; the text answer is its label\n // (`sin(x) over [0, 6.28]`, or the series a sparkline came from).\n return `${locale.display.resultPrefix}${(value.value as ChartData).label}`;\n case ValueType.IpCidr:\n return `${locale.display.resultPrefix}${formatIpCidr(value.value as IpCidrData)}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["DEFAULT_FORMATTING_SETTINGS","formatNumber","value","locale","settings","decimalPlaces","sep","loc","formatted","dp","autoFormatIntegerOrFloat","formatUncertain","center","uncertainty","useGrouping","spreadMax","centerText","spreadText","formatHex","base","negative","sign","digits","radix","padding","hex","MAX_DISPLAYED_BIGINT_DIGITS","formatBigInt","magnitude","bits","log10","exponent","mantissa","formatString","formatBoolean","formatDatetime","d","format","isMidnight","dateStr","p2","n","year","month","day","datePart","time","formatMsDuration","ms","totalSeconds","hours","minutes","seconds","mm","ss","decimalMarkByLocale","decimalMark","mark","part","localiseFixedDecimal","fixed","match","integer","fraction","integerText","formatUom","unit","exact","isTimeSpan","currencyDisplay","CURRENCY_DISPLAY","moneyText","decimalToFixed","formatMatrixEntry","entry","formatSymbolic","formatMatrix","m","rowMajor","columnMajorToRowMajor","rows","r","cells","c","formatMatrixAligned","us","row","colWidth","width","cell","formatRange","min","max","formatPercentage","formatUnit","formatIpCidr","data","dotted","formatIp","formatSplit","prefix","render","share","v","Value","text","formatValue","high","each","shareWord","localeCode","getLocale","formatColour"],"mappings":"2QA8CO,IAAMA,CAAAA,CAAkD,CAC7D,WAAA,CAAa,CACX,aAAA,CAAe,CAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CACA,YAAA,CAAc,CACZ,sBAAA,CAAwB,OAC1B,CAAA,CACA,SAAA,CAAW,CACT,aAAA,CAAe,KAAA,CACf,YAAA,CAAc,CAChB,CAAA,CACA,uBAAA,CAAyB,CACvB,aAAA,CAAe,CACjB,CAAA,CACA,gBAAA,CAAkB,CAChB,aAAA,CAAe,CACjB,CAAA,CACA,UAAA,CAAY,CACV,MAAA,CAAQ,MACV,CACF,ECxDA,SAASC,CAAAA,CAAaC,CAAAA,CAAeC,CAAAA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A,CAAa1E,CAAAA,CAAM,MAAqBC,CAAAA,CAAQkF,CAAE,EAC3D,KAAA,CAAA,CAAsB,CACpB,IAAMJ,CAAAA,CAAI/E,CAAAA,CAAM,MAChB,OAAOwF,CAAAA,CAAYT,EAAE,GAAA,CAAKA,CAAAA,CAAE,IAAK9E,CAAM,CACzC,CACA,KAAA,EAAA,CACE,OAAO,GAAGA,CAAAA,CAAO,OAAA,CAAQ,YAAY,CAAA,EAAG6G,mBAAAA,CAAa9G,EAAM,KAAmB,CAAC,GACjF,KAAA,EAAA,CACE,OAAOiG,EAAYjG,CAAAA,CAAM,KAAA,CAAoBC,EAAQkF,CAAE,CAAA,CACzD,QAGE,OAAO,CAAA,EAAGlF,EAAO,OAAA,CAAQ,YAAY,GAAID,CAAAA,CAAM,KAAA,CAAoB,KAAK,CAAA,CAAA,CAC1E,KAAA,EAAA,CACE,OAAO,CAAA,EAAGC,CAAAA,CAAO,QAAQ,YAAY,CAAA,EAAG4F,EAAa7F,CAAAA,CAAM,KAAmB,CAAC,CAAA,CAAA,CACjF,KAAA,CAAA,CACE,OAAOyE,mBAAAA,CAAezE,CAAAA,CAAM,KAAqB,CAAA,CACnD,KAAA,CAAA,CACE,OAAO2F,CAAAA,CAAiB3F,CAAAA,CAAM,MAAiBC,CAAAA,CAAQkF,CAAE,EAC3D,KAAA,EAAA,CACE,OAAOS,EAAW5F,CAAAA,CAAM,KAAA,CAAiBA,EAAM,IAAI,CAAA,CACrD,QAKE,OAAOA,CAAAA,CAAM,MAAQ,MAAA,CAAOA,CAAAA,CAAM,KAAK,CAAA,CACzC,QACE,OAAO,CAAA,EAAA,EAAK,MAAA,CAAOA,EAAM,KAAK,CAAC,EACnC,CACF","file":"chunk-XBGK3TTU.cjs","sourcesContent":["/**\n * How a Datetime value is rendered.\n *\n * - `'long'`: the spelled-out form, \"Tuesday, March 10, 2026\" (the default).\n * - `'iso'`: \"2026-03-10\" (ISO 8601, with a `T`-separated time when present).\n * - `'dmy'`: \"10/03/2026\" (day first).\n * - `'mdy'`: \"03/10/2026\" (month first).\n *\n * The weekday and long month name in `'long'` are localised through the same\n * locale the number separators come from; the numeric forms are locale-neutral.\n */\nexport type DateOutputFormat = \"long\" | \"iso\" | \"dmy\" | \"mdy\";\n\n/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n /**\n * Optional so a host that built a `FormattingSettings` before this field\n * existed still compiles; a missing `dateResult` reads as `'long'`, the\n * historic output.\n */\n dateResult?: {\n format: DateOutputFormat;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n dateResult: {\n format: \"long\",\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type SplitData, type SplitShare, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { formatIp } from \"@solve-js/packages/ip/IpMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale, settings: FormattingSettings): string {\n const d = new Date(value);\n const format = settings.dateResult?.format ?? \"long\";\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n\n // The spelled-out default, localised through the locale's own names.\n if (format === \"long\") {\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n }\n\n // The numeric forms, built from the local calendar fields so they read the\n // same regardless of the JS runtime's own default locale.\n const p2 = (n: number) => String(n).padStart(2, \"0\");\n const year = d.getFullYear();\n const month = p2(d.getMonth() + 1);\n const day = p2(d.getDate());\n let datePart: string;\n if (format === \"iso\") datePart = `${year}-${month}-${day}`;\n else if (format === \"dmy\") datePart = `${day}/${month}/${year}`;\n else datePart = `${month}/${day}/${year}`; // mdy\n\n if (isMidnight) return `= ${datePart}`;\n const time = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;\n // ISO joins date and time with `T`; the slash forms with a space.\n return format === \"iso\" ? `= ${datePart}T${time}` : `= ${datePart} ${time}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\n/** The decimal mark each locale writes, looked up once per locale rather than on every value. */\nconst decimalMarkByLocale = new Map<string, string>();\n\nfunction decimalMark(loc: string): string {\n let mark = decimalMarkByLocale.get(loc);\n if (mark === undefined) {\n mark = new Intl.NumberFormat(loc).formatToParts(1.1).find((part) => part.type === \"decimal\")?.value ?? \".\";\n decimalMarkByLocale.set(loc, mark);\n }\n return mark;\n}\n\n/**\n * Write a fixed-decimal string (`\"1234567.50\"`) the way `loc` writes numbers:\n * its decimal mark, and its digit grouping when `useGrouping` is on.\n *\n * Every quantity and every money amount used to be rendered with a bare\n * `toFixed`, so a plain `52000` showed as `52,000` while `£52000` showed as\n * `£52000.00`, and the `enableSeperator` setting had no effect on the one\n * value type people most want grouped. The digits are taken from the string\n * rather than re-rendered from the double, because an exact money amount has\n * already been rounded from its decimal (see {@link formatUom}) and\n * re-rendering would undo that. `BigInt` carries the integer part through\n * `Intl` so grouping follows the locale's own rule (Indian lakhs included)\n * rather than a hand-written every-three-digits. Anything that is not plain\n * digits, an `Infinity` or an exponent form, is returned as it came.\n */\nfunction localiseFixedDecimal(fixed: string, loc: string, useGrouping: boolean): string {\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?$/.exec(fixed);\n if (!match) return fixed;\n const [, sign, integer, fraction] = match;\n const integerText = useGrouping ? BigInt(integer).toLocaleString(loc, { useGrouping: true }) : integer;\n if (fraction === undefined) return `${sign}${integerText}`;\n return `${sign}${integerText}${decimalMark(loc)}${fraction}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n // A fuel-consumption unit is stored slash-free (so it is not read as a rate)\n // but shown the way it is written.\n if (unit === \"l100km\") unit = \"l/100km\";\n if (unit === \"mps2\") unit = \"m/s²\";\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"months\", \"years\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = localiseFixedDecimal(value.toString(), loc, useGrouping);\n } else {\n // For other values, use the configured decimal places\n formatted = localiseFixedDecimal(value.toFixed(dp), loc, useGrouping);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Renders a per-person bill split: \"= $45.00 each\", or, when the division is\n * uneven, \"= $33.33 each, with 1 share paying $33.34\". Each share's amount is\n * rendered through the ordinary value formatter (a throwaway {@link Value}), so\n * a currency share honours the same symbol placement, decimal places and locale\n * as any other money and a bare share trims trailing zeros the way a plain\n * number does; the \"= \" prefix is added once, around the whole sentence, not\n * per share.\n */\n/**\n * An IP/CIDR as text: the dotted quad, plus `/prefix` when present, or a bare\n * `/prefix` when there is no address (`netmask of /24` before it resolves).\n */\nfunction formatIpCidr(data: IpCidrData): string {\n\tif (data.addr === undefined) return `/${data.prefix}`;\n\tconst dotted = formatIp(data.addr);\n\treturn data.prefix === undefined ? dotted : `${dotted}/${data.prefix}`;\n}\n\nfunction formatSplit(data: SplitData, locale: ILocale, settings: FormattingSettings): string {\n const prefix = locale.display.resultPrefix;\n const render = (share: SplitShare): string => {\n const v = data.unit !== undefined\n ? new Value(ValueType.Uom, share.value, data.unit)\n : new Value(ValueType.Number, share.value);\n v.exact = share.exact;\n const text = formatValue(v, settings);\n return text.startsWith(prefix) ? text.slice(prefix.length) : text;\n };\n\n const [base, high] = data.shares;\n const each = `${render(base)} each`;\n if (high === undefined) return `${prefix}${each}`;\n const shareWord = high.count === 1 ? \"share\" : \"shares\";\n return `${prefix}${each}, with ${high.count} ${shareWord} paying ${render(high)}`;\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const value = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale, us);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Split:\n return formatSplit(value.value as SplitData, locale, us);\n case ValueType.Chart:\n // A chart is drawn from its data by the host; the text answer is its label\n // (`sin(x) over [0, 6.28]`, or the series a sparkline came from).\n return `${locale.display.resultPrefix}${(value.value as ChartData).label}`;\n case ValueType.IpCidr:\n return `${locale.display.resultPrefix}${formatIpCidr(value.value as IpCidrData)}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
- import {a as a$1}from'./chunk-HFKDWQUL.js';import {c}from'./chunk-BDF4VCQX.js';var b=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function O(N){return b.has(N.toUpperCase())}var D={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},a=class a{constructor(){this.baseTables=new Map;}isCryptoCode(t){return Object.prototype.hasOwnProperty.call(a.CRYPTO_IDS,t.toUpperCase())}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:R,cleanup:l}=a$1(r,a.FETCH_TIMEOUT_MS,"Currency API fetch");try{let u=new URLSearchParams({base:n}),i=await fetch(`https://api.frankfurter.dev/v2/rates?${u.toString()}`,{signal:R});if(!i.ok)throw c.external(D.API_ERROR,`Currency API returned ${i.status}`,{status:i.status});let c$1=await i.json(),C=Array.isArray(c$1)?Object.fromEntries(c$1.filter(o=>{if(typeof o!="object"||o===null)return !1;let d=o;return typeof d.quote=="string"&&typeof d.rate=="number"}).map(o=>[o.quote.toUpperCase(),o.rate])):c$1.rates??{};if(C[s]===void 0)throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...C,[n]:1}}),C[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=a$1(r,a.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let R=this.isCryptoCode(t),l=this.isCryptoCode(e),u;if(R&&l){let i=a.CRYPTO_IDS[t],c$1=a.CRYPTO_IDS[e],C=await this.fetchCoinGeckoPrices([i,c$1],"usd",n),o=C[i]?.usd,d=C[c$1]?.usd;if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof d!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o/d;}else if(R){let i=a.CRYPTO_IDS[t],c$1=e.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o;}else {let i=a.CRYPTO_IDS[e],c$1=t.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});u=1/o;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:u}}),u}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=new URLSearchParams({ids:t.join(","),vs_currencies:e}),s=await fetch(`https://api.coingecko.com/api/v3/simple/price?${n.toString()}`,{signal:r});if(!s.ok)throw c.external(D.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let R of this.baseTables.values()){if(s-R.fetchedAt>a.RATE_FRESHNESS_MS)continue;let l=R.rates[r],u=R.rates[n];if(l&&u)return u/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>a.RATE_FRESHNESS_MS))for(let[R,l]of Object.entries(s.rates))e[`${n}:${R}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return O(t)||this.isCryptoCode(t)}};a.RATE_FRESHNESS_MS=900*1e3,a.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},a.FETCH_TIMEOUT_MS=1e4;var f=a,p=new f,g=p;
2
- export{f as a,p as b,g as c};//# sourceMappingURL=chunk-GP4H5OIT.js.map
3
- //# sourceMappingURL=chunk-GP4H5OIT.js.map
1
+ import {a as a$1}from'./chunk-HFKDWQUL.js';import {c}from'./chunk-57PSJQQW.js';var b=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function O(N){return b.has(N.toUpperCase())}var D={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},a=class a{constructor(){this.baseTables=new Map;}isCryptoCode(t){return Object.prototype.hasOwnProperty.call(a.CRYPTO_IDS,t.toUpperCase())}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:R,cleanup:l}=a$1(r,a.FETCH_TIMEOUT_MS,"Currency API fetch");try{let u=new URLSearchParams({base:n}),i=await fetch(`https://api.frankfurter.dev/v2/rates?${u.toString()}`,{signal:R});if(!i.ok)throw c.external(D.API_ERROR,`Currency API returned ${i.status}`,{status:i.status});let c$1=await i.json(),C=Array.isArray(c$1)?Object.fromEntries(c$1.filter(o=>{if(typeof o!="object"||o===null)return !1;let d=o;return typeof d.quote=="string"&&typeof d.rate=="number"}).map(o=>[o.quote.toUpperCase(),o.rate])):c$1.rates??{};if(C[s]===void 0)throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...C,[n]:1}}),C[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=a$1(r,a.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let R=this.isCryptoCode(t),l=this.isCryptoCode(e),u;if(R&&l){let i=a.CRYPTO_IDS[t],c$1=a.CRYPTO_IDS[e],C=await this.fetchCoinGeckoPrices([i,c$1],"usd",n),o=C[i]?.usd,d=C[c$1]?.usd;if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof d!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o/d;}else if(R){let i=a.CRYPTO_IDS[t],c$1=e.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o;}else {let i=a.CRYPTO_IDS[e],c$1=t.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof o!="number")throw c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});u=1/o;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:u}}),u}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=new URLSearchParams({ids:t.join(","),vs_currencies:e}),s=await fetch(`https://api.coingecko.com/api/v3/simple/price?${n.toString()}`,{signal:r});if(!s.ok)throw c.external(D.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let R of this.baseTables.values()){if(s-R.fetchedAt>a.RATE_FRESHNESS_MS)continue;let l=R.rates[r],u=R.rates[n];if(l&&u)return u/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>a.RATE_FRESHNESS_MS))for(let[R,l]of Object.entries(s.rates))e[`${n}:${R}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return O(t)||this.isCryptoCode(t)}};a.RATE_FRESHNESS_MS=900*1e3,a.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},a.FETCH_TIMEOUT_MS=1e4;var f=a,p=new f,g=p;
2
+ export{f as a,p as b,g as c};//# sourceMappingURL=chunk-XHQYHXRE.js.map
3
+ //# sourceMappingURL=chunk-XHQYHXRE.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","query","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","base","baseUpper","now","table","fromRate","toRate","snapshot","any","CurrencyExchangeService","currencyExchangeService","sharedCurrencyExchange"],"mappings":"+EAyBO,IAAMA,CAAAA,CAAsC,IAAI,GAAA,CAAI,CAC1D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CACP,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACjD,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CACd,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACxD,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAA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,CAAyBD","file":"chunk-GP4H5OIT.js","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n // An own-property check, not `in`: `in` also answers for everything on\n // Object.prototype, so a code spelt like an inherited name would pass.\n return Object.prototype.hasOwnProperty.call(CurrencyExchangeService.CRYPTO_IDS, code.toUpperCase());\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n // Built with URLSearchParams rather than interpolated. The code is\n // ISO-4217 by the time it gets here, but the query should be safe on\n // its own terms rather than by relying on a check that lives elsewhere.\n const query = new URLSearchParams({ base: fromUpper });\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?${query.toString()}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const query = new URLSearchParams({ ids: ids.join(\",\"), vs_currencies: vsCurrency });\n const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?${query.toString()}`, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
1
+ {"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","query","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","base","baseUpper","now","table","fromRate","toRate","snapshot","any","CurrencyExchangeService","currencyExchangeService","sharedCurrencyExchange"],"mappings":"+EAyBO,IAAMA,CAAAA,CAAsC,IAAI,GAAA,CAAI,CAC1D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CACP,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACjD,KAAA,CAAO,MAAO,KAAA,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AAA,CArTaE,CAAAA,CAiBa,iBAAA,CAAoB,GAAA,CAAU,IAjB3CA,CAAAA,CA4Ba,UAAA,CAAqC,CAC3D,GAAA,CAAK,SAAA,CAAW,GAAA,CAAK,UAAA,CAAY,GAAA,CAAK,QAAA,CAAU,GAAA,CAAK,QAAA,CACrD,GAAA,CAAK,SAAA,CAAW,IAAA,CAAM,WAAY,GAAA,CAAK,UACzC,CAAA,CA/BWA,CAAAA,CAoDa,gBAAA,CAAmB,GAAA,CApDtC,IAAMoC,CAAAA,CAANpC,CAAAA,CA4TMqC,CAAAA,CAA0B,IAAID,CAAAA,CAI9BE,CAAAA,CAAyBD","file":"chunk-XHQYHXRE.js","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n // An own-property check, not `in`: `in` also answers for everything on\n // Object.prototype, so a code spelt like an inherited name would pass.\n return Object.prototype.hasOwnProperty.call(CurrencyExchangeService.CRYPTO_IDS, code.toUpperCase());\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n // Built with URLSearchParams rather than interpolated. The code is\n // ISO-4217 by the time it gets here, but the query should be safe on\n // its own terms rather than by relying on a check that lives elsewhere.\n const query = new URLSearchParams({ base: fromUpper });\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?${query.toString()}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const query = new URLSearchParams({ ids: ids.join(\",\"), vs_currencies: vsCurrency });\n const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?${query.toString()}`, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
@@ -1,3 +1,3 @@
1
- import {a as a$1}from'./chunk-XEIDV5JP.js';import {g,D}from'./chunk-5TCSFTZD.js';import {Z,R,ua,sa}from'./chunk-UXR7JIPX.js';import {m}from'./chunk-IPSOWFCA.js';import {a}from'./chunk-LHLW7JLS.js';var x={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function P(t,e,o,r){let n=o.floatResult.enableSeperator,a=o.numberResult.decimalSeparatorLocale;if(r!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(a||"en-US",{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:n});return `${e.display.resultPrefix}${c}`}let i=o.floatResult.decimalPlaces,s=a$1(t,i,n,a);return `${e.display.resultPrefix}${s}`}function T(t,e,o,r){let n=r.floatResult.decimalPlaces,a=r.floatResult.enableSeperator,i=r.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(n,1),c=t.toLocaleString(i,{useGrouping:a,minimumFractionDigits:0,maximumFractionDigits:n}),l=Math.abs(e).toLocaleString(i,{useGrouping:a,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${l}`}function w(t,e,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let r=typeof t=="bigint"?t<0n:t<0,n=r?"-":"",a=c=>typeof t=="bigint"?(r?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${n}0b${a(2)}`;if(o==="oct")return `= ${n}0o${a(8)}`;let i=e.hexResult.enablePadding?e.hexResult.paddingZeros:0,s=a(16).toUpperCase().padStart(i,"0");return `= ${n}0x${s}`}var N=2e4;function U(t){let e=t<0n?-t:t;if(Number.isFinite(Number(e)))return `= ${t}`;let o=e.toString(16).length*4;if(o*Math.LN2/Math.LN10<=N)return `= ${t}`;let r=o*Math.LN2/Math.LN10,n=Math.floor(r),a=Math.pow(10,r-n);return `= ${t<0n?"-":""}~${a.toFixed(3)}e+${n} (an exact integer of about ${(n+1).toLocaleString("en-US")} digits, too large to print)`}function C(t){return `= ${t}`}function E(t){return `= ${t}`}function G(t,e,o){let r=new Date(t),n=o.dateResult?.format??"long",a=r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getMilliseconds()===0;if(n==="long"){let g=r.toLocaleDateString(e.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return a?`= ${g}`:`= ${g}, ${r.toLocaleTimeString(e.code)}`}let i=g=>String(g).padStart(2,"0"),s=r.getFullYear(),c=i(r.getMonth()+1),l=i(r.getDate()),u;if(n==="iso"?u=`${s}-${c}-${l}`:n==="dmy"?u=`${l}/${c}/${s}`:u=`${c}/${l}/${s}`,a)return `= ${u}`;let m=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return n==="iso"?`= ${u}T${m}`:`= ${u} ${m}`}function j(t){let e=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),r=Math.floor(o/3600),n=Math.floor(o%3600/60),a=o%60,i=String(n).padStart(2,"0");if(a===0)return `${e}${r}:${i}`;let s=String(a).padStart(2,"0");return `${e}${r}:${i}:${s}`}var L=new Map;function k(t){let e=L.get(t);return e===void 0&&(e=new Intl.NumberFormat(t).formatToParts(1.1).find(o=>o.type==="decimal")?.value??".",L.set(t,e)),e}function f(t,e,o){let r=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return t;let[,n,a,i]=r,s=o?BigInt(a).toLocaleString(e,{useGrouping:true}):a;return i===void 0?`${n}${s}`:`${n}${s}${k(e)}${i}`}function A(t,e,o,r,n){if(e==="ms")return `= ${j(t)}`;e==="l100km"&&(e="l/100km"),e==="mps2"&&(e="m/s\xB2");let a=r.unitOfMeasurementResult.decimalPlaces,i=r.floatResult.enableSeperator,s=r.numberResult.decimalSeparatorLocale||"en-US",l=e&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(e),u;l&&t===Math.floor(t)?u=f(t.toString(),s,i):u=f(t.toFixed(a),s,i);let m=e?ua[e.toUpperCase()]:void 0;if(m){let h=n?f(sa(n,a),s,i):u,y=m.spaced?" ":"";return `= ${m.position==="prefix"?`${m.symbol}${y}${h}`:`${h}${y}${m.symbol}`}`}return `= ${n?f(sa(n,a),s,i):u} ${e||""}`.trim()}function I(t,e){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return R(t);let o=e.floatResult.decimalPlaces,r=e.floatResult.enableSeperator,n=e.numberResult.decimalSeparatorLocale;return a$1(t,o,r,n)}function O(t,e,o){let r=Z(t),n=[];for(let a=0;a<t.rows;a++){let i=[];for(let s=0;s<t.cols;s++)i.push(I(r[a*t.cols+s],o));n.push(i.join(", "));}return `${e.display.resultPrefix}[${n.join("; ")}]`}function at(t,e){let o=e||x,r=Z(t),n=[];for(let i=0;i<t.rows;i++){let s=[];for(let c=0;c<t.cols;c++)s.push(I(r[i*t.cols+c],o));n.push(s);}let a=[];for(let i=0;i<t.cols;i++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,n[c][i].length);a.push(s);}return n.map(i=>`[ ${i.map((s,c)=>s.padStart(a[c])).join(" ")} ]`).join(`
2
- `)}function _(t,e,o){return `${o.display.resultPrefix}${t}:${e}`}function B(t,e,o){let r=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(r)}${e.display.percentageSuffix}`}function H(t,e){return `= ${t} ${e||""}`.trim()}function V(t){if(t.addr===void 0)return `/${t.prefix}`;let e=D(t.addr);return t.prefix===void 0?e:`${e}/${t.prefix}`}function Y(t,e,o){let r=e.display.resultPrefix,n=l=>{let u=t.unit!==void 0?new m(6,l.value,t.unit):new m(0,l.value);u.exact=l.exact;let m$1=W(u,o);return m$1.startsWith(r)?m$1.slice(r.length):m$1},[a,i]=t.shares,s=`${n(a)} each`;if(i===void 0)return `${r}${s}`;let c=i.count===1?"share":"shares";return `${r}${s}, with ${i.count} ${c} paying ${n(i)}`}function W(t,e){let o=e||x,r=o.numberResult.decimalSeparatorLocale||"en",n=a(r);switch(t.type){case 0:return t.uncertainty!==void 0?T(t.value,t.uncertainty,n,o):P(t.value,n,o,t.decimalPlaces);case 1:return w(t.value,o,t.unit);case 2:return U(t.value);case 3:return C(t.value);case 10:return E(t.value);case 4:return G(t.value,n,o);case 6:return A(t.value,t.unit,n,o,t.exact);case 7:return O(t.value,n,o);case 8:{let a=t.value;return _(a.min,a.max,n)}case 14:return `${n.display.resultPrefix}${g(t.value)}`;case 15:return Y(t.value,n,o);case 16:return `${n.display.resultPrefix}${t.value.label}`;case 17:return `${n.display.resultPrefix}${V(t.value)}`;case 9:return R(t.value);case 5:return B(t.value,n,o);case 11:return H(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}export{x as a,at as b,W as c};//# sourceMappingURL=chunk-RE6AIU6Y.js.map
3
- //# sourceMappingURL=chunk-RE6AIU6Y.js.map
1
+ import {a as a$1}from'./chunk-XEIDV5JP.js';import {g,D}from'./chunk-5TCSFTZD.js';import {Z,R,ua,sa}from'./chunk-RDYXH7ML.js';import {m}from'./chunk-NMU5E7W7.js';import {a}from'./chunk-LHLW7JLS.js';var x={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function P(t,e,o,r){let n=o.floatResult.enableSeperator,a=o.numberResult.decimalSeparatorLocale;if(r!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(a||"en-US",{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:n});return `${e.display.resultPrefix}${c}`}let i=o.floatResult.decimalPlaces,s=a$1(t,i,n,a);return `${e.display.resultPrefix}${s}`}function T(t,e,o,r){let n=r.floatResult.decimalPlaces,a=r.floatResult.enableSeperator,i=r.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(n,1),c=t.toLocaleString(i,{useGrouping:a,minimumFractionDigits:0,maximumFractionDigits:n}),l=Math.abs(e).toLocaleString(i,{useGrouping:a,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${l}`}function w(t,e,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let r=typeof t=="bigint"?t<0n:t<0,n=r?"-":"",a=c=>typeof t=="bigint"?(r?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${n}0b${a(2)}`;if(o==="oct")return `= ${n}0o${a(8)}`;let i=e.hexResult.enablePadding?e.hexResult.paddingZeros:0,s=a(16).toUpperCase().padStart(i,"0");return `= ${n}0x${s}`}var N=2e4;function U(t){let e=t<0n?-t:t;if(Number.isFinite(Number(e)))return `= ${t}`;let o=e.toString(16).length*4;if(o*Math.LN2/Math.LN10<=N)return `= ${t}`;let r=o*Math.LN2/Math.LN10,n=Math.floor(r),a=Math.pow(10,r-n);return `= ${t<0n?"-":""}~${a.toFixed(3)}e+${n} (an exact integer of about ${(n+1).toLocaleString("en-US")} digits, too large to print)`}function C(t){return `= ${t}`}function E(t){return `= ${t}`}function G(t,e,o){let r=new Date(t),n=o.dateResult?.format??"long",a=r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getMilliseconds()===0;if(n==="long"){let g=r.toLocaleDateString(e.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return a?`= ${g}`:`= ${g}, ${r.toLocaleTimeString(e.code)}`}let i=g=>String(g).padStart(2,"0"),s=r.getFullYear(),c=i(r.getMonth()+1),l=i(r.getDate()),u;if(n==="iso"?u=`${s}-${c}-${l}`:n==="dmy"?u=`${l}/${c}/${s}`:u=`${c}/${l}/${s}`,a)return `= ${u}`;let m=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return n==="iso"?`= ${u}T${m}`:`= ${u} ${m}`}function j(t){let e=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),r=Math.floor(o/3600),n=Math.floor(o%3600/60),a=o%60,i=String(n).padStart(2,"0");if(a===0)return `${e}${r}:${i}`;let s=String(a).padStart(2,"0");return `${e}${r}:${i}:${s}`}var L=new Map;function k(t){let e=L.get(t);return e===void 0&&(e=new Intl.NumberFormat(t).formatToParts(1.1).find(o=>o.type==="decimal")?.value??".",L.set(t,e)),e}function f(t,e,o){let r=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return t;let[,n,a,i]=r,s=o?BigInt(a).toLocaleString(e,{useGrouping:true}):a;return i===void 0?`${n}${s}`:`${n}${s}${k(e)}${i}`}function A(t,e,o,r,n){if(e==="ms")return `= ${j(t)}`;e==="l100km"&&(e="l/100km"),e==="mps2"&&(e="m/s\xB2");let a=r.unitOfMeasurementResult.decimalPlaces,i=r.floatResult.enableSeperator,s=r.numberResult.decimalSeparatorLocale||"en-US",l=e&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(e),u;l&&t===Math.floor(t)?u=f(t.toString(),s,i):u=f(t.toFixed(a),s,i);let m=e?ua[e.toUpperCase()]:void 0;if(m){let h=n?f(sa(n,a),s,i):u,y=m.spaced?" ":"";return `= ${m.position==="prefix"?`${m.symbol}${y}${h}`:`${h}${y}${m.symbol}`}`}return `= ${n?f(sa(n,a),s,i):u} ${e||""}`.trim()}function I(t,e){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return R(t);let o=e.floatResult.decimalPlaces,r=e.floatResult.enableSeperator,n=e.numberResult.decimalSeparatorLocale;return a$1(t,o,r,n)}function O(t,e,o){let r=Z(t),n=[];for(let a=0;a<t.rows;a++){let i=[];for(let s=0;s<t.cols;s++)i.push(I(r[a*t.cols+s],o));n.push(i.join(", "));}return `${e.display.resultPrefix}[${n.join("; ")}]`}function at(t,e){let o=e||x,r=Z(t),n=[];for(let i=0;i<t.rows;i++){let s=[];for(let c=0;c<t.cols;c++)s.push(I(r[i*t.cols+c],o));n.push(s);}let a=[];for(let i=0;i<t.cols;i++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,n[c][i].length);a.push(s);}return n.map(i=>`[ ${i.map((s,c)=>s.padStart(a[c])).join(" ")} ]`).join(`
2
+ `)}function _(t,e,o){return `${o.display.resultPrefix}${t}:${e}`}function B(t,e,o){let r=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(r)}${e.display.percentageSuffix}`}function H(t,e){return `= ${t} ${e||""}`.trim()}function V(t){if(t.addr===void 0)return `/${t.prefix}`;let e=D(t.addr);return t.prefix===void 0?e:`${e}/${t.prefix}`}function Y(t,e,o){let r=e.display.resultPrefix,n=l=>{let u=t.unit!==void 0?new m(6,l.value,t.unit):new m(0,l.value);u.exact=l.exact;let m$1=W(u,o);return m$1.startsWith(r)?m$1.slice(r.length):m$1},[a,i]=t.shares,s=`${n(a)} each`;if(i===void 0)return `${r}${s}`;let c=i.count===1?"share":"shares";return `${r}${s}, with ${i.count} ${c} paying ${n(i)}`}function W(t,e){let o=e||x,r=o.numberResult.decimalSeparatorLocale||"en",n=a(r);switch(t.type){case 0:return t.uncertainty!==void 0?T(t.value,t.uncertainty,n,o):P(t.value,n,o,t.decimalPlaces);case 1:return w(t.value,o,t.unit);case 2:return U(t.value);case 3:return C(t.value);case 10:return E(t.value);case 4:return G(t.value,n,o);case 6:return A(t.value,t.unit,n,o,t.exact);case 7:return O(t.value,n,o);case 8:{let a=t.value;return _(a.min,a.max,n)}case 14:return `${n.display.resultPrefix}${g(t.value)}`;case 15:return Y(t.value,n,o);case 16:return `${n.display.resultPrefix}${t.value.label}`;case 17:return `${n.display.resultPrefix}${V(t.value)}`;case 9:return R(t.value);case 5:return B(t.value,n,o);case 11:return H(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}export{x as a,at as b,W as c};//# sourceMappingURL=chunk-XX55RR4Q.js.map
3
+ //# sourceMappingURL=chunk-XX55RR4Q.js.map