solve-engine 2.25.0 → 2.26.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.
- package/dist/CalendarBackend-MdS3Bb4P.d.cts +181 -0
- package/dist/CalendarBackend-MdS3Bb4P.d.ts +181 -0
- package/dist/{Configuration-DnzYPmoK.d.cts → Configuration-BxriK9Kw.d.cts} +63 -4
- package/dist/{Configuration-DnzYPmoK.d.ts → Configuration-BxriK9Kw.d.ts} +63 -4
- package/dist/DateCalendar-B85t6Vk6.d.ts +90 -0
- package/dist/DateCalendar-CUGI1fT4.d.cts +90 -0
- package/dist/{EngineError-fR1K1rvx.d.cts → EngineError-C-kBwYlN.d.cts} +31 -4
- package/dist/{EngineError-fR1K1rvx.d.ts → EngineError-C-kBwYlN.d.ts} +31 -4
- package/dist/{FormattingSettings-bRKjU7wI.d.ts → FormattingSettings-ByO-4wiM.d.cts} +14 -0
- package/dist/{FormattingSettings-bRKjU7wI.d.cts → FormattingSettings-CvCzAfsz.d.ts} +14 -0
- package/dist/{Lexer-aB95pjoX.d.cts → Lexer-DhGhoAa2.d.cts} +13 -3
- package/dist/{Lexer-Bmctxl0n.d.ts → Lexer-DqtnZMC5.d.ts} +13 -3
- package/dist/{PackageCompatibility-CUVg8tmt.d.cts → PackageCompatibility-CNiTtC6S.d.cts} +1 -1
- package/dist/{PackageCompatibility-BludTs7v.d.ts → PackageCompatibility-fj_f7uqC.d.ts} +1 -1
- package/dist/{PackageRegistry-Dvn4i2QK.d.cts → PackageRegistry-BHBCFswo.d.cts} +328 -14
- package/dist/{PackageRegistry-DT-x32OM.d.ts → PackageRegistry-CNZUwWHJ.d.ts} +328 -14
- package/dist/{Parselet-BawfGuTF.d.cts → Parselet-DF3864la.d.cts} +19 -3
- package/dist/{Parselet-DqTbbtWA.d.ts → Parselet-Dgymjxzd.d.ts} +19 -3
- package/dist/{Token-CbP_OutD.d.cts → Token-D8f7yaz1.d.cts} +17 -0
- package/dist/{Token-CbP_OutD.d.ts → Token-D8f7yaz1.d.ts} +17 -0
- package/dist/{TokenNormalizer-CLBtiE8M.d.ts → TokenNormalizer-IF7nPRMp.d.ts} +1 -1
- package/dist/{TokenNormalizer-CjTDmHgB.d.cts → TokenNormalizer-Pe3_390t.d.cts} +1 -1
- package/dist/{ScopeManager-B636am7Y.d.ts → VMBuiltins-CZiZRKn-.d.ts} +91 -9
- package/dist/{ScopeManager-CdwX0VTw.d.cts → VMBuiltins-kv4rr0y5.d.cts} +91 -9
- package/dist/{VMCheckpoints-DDlxNssY.d.ts → VMCheckpoints-DXze6ypg.d.ts} +2 -2
- package/dist/{VMCheckpoints-CYqeq8IV.d.cts → VMCheckpoints-yun4ocSv.d.cts} +2 -2
- package/dist/{Value-Ds3Gy07C.d.cts → Value-BYHw-x7q.d.cts} +57 -1
- package/dist/{Value-Ds3Gy07C.d.ts → Value-BYHw-x7q.d.ts} +57 -1
- package/dist/{WorkerError-B1dF3VYT.d.cts → WorkerError-BLZyNq6M.d.cts} +1 -1
- package/dist/{WorkerError-dneODN-u.d.ts → WorkerError-CfBJYueR.d.ts} +1 -1
- package/dist/chunk-2SYYKQ4Q.cjs +2 -0
- package/dist/chunk-2SYYKQ4Q.cjs.map +1 -0
- package/dist/chunk-6EYKVQT3.cjs +2 -0
- package/dist/chunk-6EYKVQT3.cjs.map +1 -0
- package/dist/chunk-7RC6RBS6.cjs +2 -0
- package/dist/chunk-7RC6RBS6.cjs.map +1 -0
- package/dist/chunk-AZX4NTYN.cjs +3 -0
- package/dist/chunk-AZX4NTYN.cjs.map +1 -0
- package/dist/{chunk-JFZ5SLF7.js → chunk-BCR53EIL.js} +2 -2
- package/dist/{chunk-JFZ5SLF7.js.map → chunk-BCR53EIL.js.map} +1 -1
- package/dist/chunk-BLJ6E577.js +2 -0
- package/dist/chunk-BLJ6E577.js.map +1 -0
- package/dist/{chunk-4BAUQE6A.cjs → chunk-C5GEMKUY.cjs} +3 -3
- package/dist/{chunk-4BAUQE6A.cjs.map → chunk-C5GEMKUY.cjs.map} +1 -1
- package/dist/chunk-CL7DM2FX.js +2 -0
- package/dist/chunk-CL7DM2FX.js.map +1 -0
- package/dist/{chunk-BMXYR5LI.cjs → chunk-CQLCTKMX.cjs} +2 -2
- package/dist/{chunk-BMXYR5LI.cjs.map → chunk-CQLCTKMX.cjs.map} +1 -1
- package/dist/chunk-CQY23OF5.cjs +5 -0
- package/dist/chunk-CQY23OF5.cjs.map +1 -0
- package/dist/chunk-D4VBWPWN.js +2 -0
- package/dist/chunk-D4VBWPWN.js.map +1 -0
- package/dist/chunk-E4HAKNBQ.cjs +2 -0
- package/dist/chunk-E4HAKNBQ.cjs.map +1 -0
- package/dist/{chunk-XHQYHXRE.js → chunk-ESZNJQ2C.js} +3 -3
- package/dist/{chunk-XHQYHXRE.js.map → chunk-ESZNJQ2C.js.map} +1 -1
- package/dist/{chunk-IJMNVBIS.js → chunk-FAO6DQ74.js} +2 -2
- package/dist/chunk-FAO6DQ74.js.map +1 -0
- package/dist/{chunk-WGP4UUO5.cjs → chunk-FDKTESBC.cjs} +2 -2
- package/dist/{chunk-WGP4UUO5.cjs.map → chunk-FDKTESBC.cjs.map} +1 -1
- package/dist/{chunk-NEGZZB7F.cjs → chunk-G2V33LFM.cjs} +2 -2
- package/dist/{chunk-NEGZZB7F.cjs.map → chunk-G2V33LFM.cjs.map} +1 -1
- package/dist/chunk-GJZIJK2Q.cjs +2 -0
- package/dist/chunk-GJZIJK2Q.cjs.map +1 -0
- package/dist/chunk-GQM6ICDM.js +2 -0
- package/dist/chunk-GQM6ICDM.js.map +1 -0
- package/dist/chunk-GVL3ZMS7.cjs +2 -0
- package/dist/chunk-GVL3ZMS7.cjs.map +1 -0
- package/dist/{chunk-YBQPEWT7.cjs → chunk-GXO7TSXQ.cjs} +3 -3
- package/dist/chunk-GXO7TSXQ.cjs.map +1 -0
- package/dist/{chunk-OONQ3V3I.js → chunk-HANGBVEE.js} +2 -2
- package/dist/{chunk-OONQ3V3I.js.map → chunk-HANGBVEE.js.map} +1 -1
- package/dist/chunk-J4K72CQN.js +2 -0
- package/dist/chunk-J4K72CQN.js.map +1 -0
- package/dist/{chunk-72PYPENZ.js → chunk-LE6WZLJ4.js} +2 -2
- package/dist/{chunk-72PYPENZ.js.map → chunk-LE6WZLJ4.js.map} +1 -1
- package/dist/chunk-LMZDTQS5.js +3 -0
- package/dist/chunk-LMZDTQS5.js.map +1 -0
- package/dist/chunk-LQIRBP4Q.js +2 -0
- package/dist/chunk-LQIRBP4Q.js.map +1 -0
- package/dist/{chunk-RDYXH7ML.js → chunk-LTUYWJGO.js} +2 -2
- package/dist/{chunk-RDYXH7ML.js.map → chunk-LTUYWJGO.js.map} +1 -1
- package/dist/chunk-MCU7UYKG.js +3 -0
- package/dist/{chunk-ZDCZ5IDD.js.map → chunk-MCU7UYKG.js.map} +1 -1
- package/dist/chunk-MTN53APQ.js +5 -0
- package/dist/chunk-MTN53APQ.js.map +1 -0
- package/dist/chunk-OPKJ2WWB.cjs +3 -0
- package/dist/chunk-OPKJ2WWB.cjs.map +1 -0
- package/dist/chunk-QQHHZPEW.cjs +2 -0
- package/dist/chunk-QQHHZPEW.cjs.map +1 -0
- package/dist/chunk-RRUGQ6DM.js +2 -0
- package/dist/chunk-RRUGQ6DM.js.map +1 -0
- package/dist/chunk-S3ODNMJS.js +2 -0
- package/dist/chunk-S3ODNMJS.js.map +1 -0
- package/dist/{chunk-SAF3B3AX.cjs → chunk-SE6ZCGZ5.cjs} +2 -2
- package/dist/{chunk-SAF3B3AX.cjs.map → chunk-SE6ZCGZ5.cjs.map} +1 -1
- package/dist/chunk-TC23XEAV.js +2 -0
- package/dist/chunk-TC23XEAV.js.map +1 -0
- package/dist/{chunk-FYAMQFZZ.cjs → chunk-TMQ37JQY.cjs} +3 -3
- package/dist/{chunk-FYAMQFZZ.cjs.map → chunk-TMQ37JQY.cjs.map} +1 -1
- package/dist/chunk-TPPM4QSS.cjs +2 -0
- package/dist/chunk-TPPM4QSS.cjs.map +1 -0
- package/dist/{chunk-57PSJQQW.js → chunk-VB6QMU2W.js} +3 -3
- package/dist/chunk-VB6QMU2W.js.map +1 -0
- package/dist/chunk-VQO54ZMA.js +2 -0
- package/dist/chunk-VQO54ZMA.js.map +1 -0
- package/dist/{chunk-7DP57BA7.js → chunk-Y7XRA2EV.js} +2 -2
- package/dist/{chunk-7DP57BA7.js.map → chunk-Y7XRA2EV.js.map} +1 -1
- package/dist/{chunk-5IJD5L3O.cjs → chunk-YBQOQTVL.cjs} +2 -2
- package/dist/chunk-YBQOQTVL.cjs.map +1 -0
- package/dist/{chunk-EL2XUOWX.js → chunk-YG7UWQFV.js} +2 -2
- package/dist/{chunk-EL2XUOWX.js.map → chunk-YG7UWQFV.js.map} +1 -1
- package/dist/chunk-YS2OW75C.cjs +2 -0
- package/dist/chunk-YS2OW75C.cjs.map +1 -0
- package/dist/chunk-ZC2NPRLO.js +3 -0
- package/dist/chunk-ZC2NPRLO.js.map +1 -0
- package/dist/{chunk-FYTB7SDP.cjs → chunk-ZDJTDFTR.cjs} +2 -2
- package/dist/{chunk-FYTB7SDP.cjs.map → chunk-ZDJTDFTR.cjs.map} +1 -1
- package/dist/chunk-ZE5KKMBV.cjs +2 -0
- package/dist/chunk-ZE5KKMBV.cjs.map +1 -0
- package/dist/{chunk-GBCN7FNV.cjs → chunk-ZSLVLMO5.cjs} +2 -2
- package/dist/{chunk-GBCN7FNV.cjs.map → chunk-ZSLVLMO5.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +14 -12
- package/dist/engine.d.ts +14 -12
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +4 -3
- package/dist/format.d.ts +4 -3
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -13
- package/dist/index.d.ts +15 -13
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +12 -11
- package/dist/language.d.ts +12 -11
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +4 -4
- package/dist/lexer.d.ts +4 -4
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +3 -3
- package/dist/normalizer.d.ts +3 -3
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +11 -10
- package/dist/packages.d.ts +11 -10
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +5 -4
- package/dist/parser.d.ts +5 -4
- package/dist/parser.js +1 -1
- package/dist/{pipeline-69q2tsLE.d.cts → pipeline-BYkKNpql.d.cts} +1 -1
- package/dist/{pipeline-DTqGLPsV.d.ts → pipeline-Cl7KW8CB.d.ts} +1 -1
- package/dist/resolvers.d.cts +2 -2
- package/dist/resolvers.d.ts +2 -2
- package/dist/temporal.cjs +2 -0
- package/dist/temporal.cjs.map +1 -0
- package/dist/temporal.d.cts +201 -0
- package/dist/temporal.d.ts +201 -0
- package/dist/temporal.js +2 -0
- package/dist/temporal.js.map +1 -0
- package/dist/testing.cjs +2 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +12 -11
- package/dist/testing.d.ts +12 -11
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.cjs.map +1 -1
- package/dist/vm.d.cts +8 -56
- package/dist/vm.d.ts +8 -56
- package/dist/vm.js +1 -1
- package/dist/vm.js.map +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +35 -13
- package/dist/worker.d.ts +35 -13
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +12 -1
- package/dist/chunk-4BRTUFTH.js +0 -2
- package/dist/chunk-4BRTUFTH.js.map +0 -1
- package/dist/chunk-4NZXCHQL.cjs +0 -2
- package/dist/chunk-4NZXCHQL.cjs.map +0 -1
- package/dist/chunk-57PSJQQW.js.map +0 -1
- package/dist/chunk-5IJD5L3O.cjs.map +0 -1
- package/dist/chunk-634ILVMP.cjs +0 -2
- package/dist/chunk-634ILVMP.cjs.map +0 -1
- package/dist/chunk-63ZOOUOL.js +0 -2
- package/dist/chunk-63ZOOUOL.js.map +0 -1
- package/dist/chunk-77KI7AKJ.cjs +0 -2
- package/dist/chunk-77KI7AKJ.cjs.map +0 -1
- package/dist/chunk-7N3IJSWF.js +0 -5
- package/dist/chunk-7N3IJSWF.js.map +0 -1
- package/dist/chunk-DUYTXLO2.js +0 -2
- package/dist/chunk-DUYTXLO2.js.map +0 -1
- package/dist/chunk-IJMNVBIS.js.map +0 -1
- package/dist/chunk-JSM3O7EM.cjs +0 -2
- package/dist/chunk-JSM3O7EM.cjs.map +0 -1
- package/dist/chunk-MZMA32NE.js +0 -3
- package/dist/chunk-MZMA32NE.js.map +0 -1
- package/dist/chunk-N4SSR7Q6.js +0 -2
- package/dist/chunk-N4SSR7Q6.js.map +0 -1
- package/dist/chunk-NMU5E7W7.js +0 -2
- package/dist/chunk-NMU5E7W7.js.map +0 -1
- package/dist/chunk-OB2VX4IL.js +0 -2
- package/dist/chunk-OB2VX4IL.js.map +0 -1
- package/dist/chunk-RAPEZR5L.cjs +0 -2
- package/dist/chunk-RAPEZR5L.cjs.map +0 -1
- package/dist/chunk-SPOVFRZO.cjs +0 -5
- package/dist/chunk-SPOVFRZO.cjs.map +0 -1
- package/dist/chunk-SQHBOWES.cjs +0 -2
- package/dist/chunk-SQHBOWES.cjs.map +0 -1
- package/dist/chunk-UF5XMZTT.js +0 -2
- package/dist/chunk-UF5XMZTT.js.map +0 -1
- package/dist/chunk-UV3EUIBT.cjs +0 -3
- package/dist/chunk-UV3EUIBT.cjs.map +0 -1
- package/dist/chunk-VMSCRVNX.cjs +0 -2
- package/dist/chunk-VMSCRVNX.cjs.map +0 -1
- package/dist/chunk-XBGK3TTU.cjs +0 -3
- package/dist/chunk-XBGK3TTU.cjs.map +0 -1
- package/dist/chunk-XX55RR4Q.js +0 -3
- package/dist/chunk-XX55RR4Q.js.map +0 -1
- package/dist/chunk-YBQPEWT7.cjs.map +0 -1
- package/dist/chunk-ZDCZ5IDD.js +0 -3
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b,m,n}from'./chunk-J4K72CQN.js';import {c,r}from'./chunk-VB6QMU2W.js';function x(m,n,e){let r=Math.trunc(m),o=Math.trunc(n),a=Math.trunc(e);if(!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(a))return Number.NaN;let t=r+Math.floor(o/12),i=(o%12+12)%12+1,s=t-(i<=2?1:0),l=Math.floor(s/400),u=s-l*400,N=Math.floor((153*(i+(i>2?-3:9))+2)/5),c=u*365+Math.floor(u/4)-Math.floor(u/100)+N;return l*146097+c-719468+(a-1)}function F(m){if(!Number.isFinite(m))return {year:Number.NaN,month0:Number.NaN,day:Number.NaN};let n=Math.trunc(m)+719468,e=Math.floor(n/146097),r=n-e*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),a=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),t=Math.floor((5*a+2)/153),i=a-Math.floor((153*t+2)/5)+1,s=t<10?t+3:t-9;return {year:o+e*400+(s<=2?1:0),month0:s-1,day:i}}var P=Object.freeze({year:Number.NaN,month0:Number.NaN,day:Number.NaN,weekday:Number.NaN,hour:Number.NaN,minute:Number.NaN,second:Number.NaN,millisecond:Number.NaN}),Z=864e13,d=864e5;function D(m){return !Number.isFinite(m)||Math.abs(m)>Z?Number.NaN:Math.trunc(m)}function z(m,n,e,r,o,a,t){let i=Math.trunc(r)*36e5+Math.trunc(o)*6e4+Math.trunc(a)*1e3+Math.trunc(t);return {dayNumber:x(m,n,e)+Math.floor(i/d),timeOfDay:(i%d+d)%d}}var S=/^([+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?(?:[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,k=class{constructor(n,e={}){A(n),this.temporal=n;let r$1=e.timeZone??n.Now.timeZoneId(),o;try{o=n.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(r$1);}catch(a){throw c.config(r.TEMPORAL_TIME_ZONE_UNKNOWN,`The Temporal implementation does not know the time zone "${r$1}"`,{timeZone:r$1,cause:a instanceof Error?a.message:String(a)})}this.timeZone=o.timeZoneId,this.clock=e.now??(()=>n.Now.instant().epochMilliseconds);}now(){return this.clock()}fields(n){let e=this.zoned(n,this.timeZone);return e===null?P:{year:e.year,month0:e.month-1,day:e.day,weekday:e.dayOfWeek%7,hour:e.hour,minute:e.minute,second:e.second,millisecond:e.millisecond}}localMidnight(n,e,r){return this.wallClock(n,e,r,0,0,0,0)}localWallClock(n,e,r,o){let a=this.localMidnight(n,e,r),t=this.fields(a);return Number.isNaN(t.year)?Number.NaN:this.wallClock(t.year,t.month0,t.day,t.hour,o,t.second,t.millisecond)}addDays(n,e){let r=this.fields(n);return Number.isNaN(r.year)?Number.NaN:this.wallClock(r.year,r.month0,r.day+e,r.hour,r.minute,r.second,r.millisecond)}addMonths(n,e){let r=this.fields(n);if(Number.isNaN(r.year))return Number.NaN;let o=r.day,a=this.fields(this.wallClock(r.year,r.month0,1,r.hour,r.minute,r.second,r.millisecond));if(Number.isNaN(a.year))return Number.NaN;let t=this.fields(this.wallClock(a.year,a.month0+e,a.day,a.hour,a.minute,a.second,a.millisecond));if(Number.isNaN(t.year))return Number.NaN;let i=Math.min(o,b(t.year,t.month0));return this.wallClock(t.year,t.month0,i,t.hour,t.minute,t.second,t.millisecond)}utcOffsetMinutes(n){let e=this.zoned(n,this.timeZone);return e===null?Number.NaN:Math.trunc(e.offsetNanoseconds/6e10)||0}parseIso8601(n){let e=S.exec(n);if(e===null)return Number.NaN;let[,r,o,a,t,i,s,l,u]=e;if(r==="-000000")return Number.NaN;let N=Number(r),c=o===void 0?1:Number(o),f=a===void 0?1:Number(a),b=t===void 0?0:Number(t),h=i===void 0?0:Number(i),y=s===void 0?0:Number(s),I=l===void 0?0:Number(l.slice(0,3).padEnd(3,"0"));if(c<1||c>12||f<1||f>31||b>24||h>59||y>59||b===24&&(h!==0||y!==0||I!==0))return Number.NaN;let p=z(N,c-1,f,b,h,y,I);if(u===void 0&&t!==void 0)return this.resolve(p);let g=0;if(u!==void 0&&u!=="Z"&&u!=="z"){let _=u.slice(1).replace(":",""),w=Number(_.slice(0,2)),C=Number(_.slice(2,4));if(w>23||C>59)return Number.NaN;g=(u[0]==="-"?-1:1)*(w*60+C);}let O=p.dayNumber*d+p.timeOfDay-g*6e4;return Math.abs(O)>Z?Number.NaN:O}formatLongDate(n,e){let r=D(n);return Number.isNaN(r)?"Invalid Date":new Intl.DateTimeFormat(e,{timeZone:this.timeZone,weekday:"long",year:"numeric",month:"long",day:"numeric"}).format(r)}formatTimeOfDay(n,e){let r=D(n);return Number.isNaN(r)?"Invalid Date":new Intl.DateTimeFormat(e,{timeZone:this.timeZone,hour:"numeric",minute:"numeric",second:"numeric"}).format(r)}zoneOffsetMinutes(n,e){let r=Number.isFinite(e)?Math.trunc(e):e,o=this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(n),a=Math.floor((r+o.offsetNanoseconds/1e6)/1e3)*1e3;return Math.round((a-e)/6e4)||0}fieldsInZone(n,e){let r=Number.isFinite(e)?Math.trunc(e):e,o=this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(n);return {year:o.year,month0:o.month-1,day:o.day,hour:o.hour,minute:o.minute,second:o.second}}zone(){return this.timeZone}formatTimeInZone(n,e){return m(n,e)}formatDateInZone(n$1,e){return n(n$1,e)}zoned(n,e){let r=D(n);if(Number.isNaN(r))return null;try{return this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(e)}catch{return null}}wallClock(n,e,r,o,a,t,i){let s=n>=0&&n<=99?1900+Math.trunc(n):n;return this.resolve(z(s,e,r,o,a,t,i))}resolve(n){let e=F(n.dayNumber);if(Number.isNaN(e.year))return Number.NaN;let r=Math.floor(n.timeOfDay/36e5),o=Math.floor(n.timeOfDay/6e4)%60,a=Math.floor(n.timeOfDay/1e3)%60,t=n.timeOfDay%1e3;try{let s=this.temporal.PlainDateTime.from({year:e.year,month:e.month0+1,day:e.day,hour:r,minute:o,second:a,millisecond:t},{overflow:"reject"}).toZonedDateTime(this.timeZone,{disambiguation:"compatible"}).epochMilliseconds;return Math.abs(s)>Z?Number.NaN:s}catch{return Number.NaN}}};function A(m){let n=m,e=typeof n?.Now?.instant!="function"?"Now.instant":typeof n?.Now?.timeZoneId!="function"?"Now.timeZoneId":typeof n?.Instant?.fromEpochMilliseconds!="function"?"Instant.fromEpochMilliseconds":typeof n?.PlainDateTime?.from!="function"?"PlainDateTime.from":null;if(e!==null)throw c.config(r.TEMPORAL_IMPLEMENTATION_INVALID,`createTemporalCalendar needs a Temporal implementation (globalThis.Temporal on a runtime that ships it, or a polyfill's export); the value given has no ${e}`,{missing:e})}function q(m,n={}){return new k(m,n)}export{k as a,q as b};//# sourceMappingURL=chunk-D4VBWPWN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-D4VBWPWN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/temporal/CivilDays.ts","../src/temporal/TemporalCalendar.ts"],"names":["civilDayNumber","year","month0","day","y0","m0","d","y","m","shiftedYear","era","yearOfEra","dayOfYear","dayOfEra","civilFromDayNumber","days","z","monthFromMarch","month","NAN_FIELDS","MAX_INSTANT","MS_PER_DAY","clip","epochMs","normaliseWallClock","hour","minute","second","millisecond","time","ISO_DATE_TIME","TemporalCalendar","temporal","options","assertTemporalLike","requested","probe","error","ErrorFactory","CoreErrorCodes","minutesPastMidnight","anchored","a","f","months","f0","dayOfMonth","f1","f2","daysInMonth","text","yearText","monthText","dayText","hourText","minuteText","secondText","fractionText","zoneText","wall","offsetMinutes","digits","offsetHours","offsetMinutesPart","instant","locale","t","zone","wallSecond","timeInZone","dateInZone","windowed","civil","candidate","missing","createTemporalCalendar"],"mappings":"8EAkDO,SAASA,EAAeC,CAAAA,CAAcC,CAAAA,CAAgBC,CAAAA,CAAqB,CACjF,IAAMC,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMH,CAAI,EACpBI,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMH,CAAM,EACtBI,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAMH,CAAG,EACxB,GAAI,CAAC,MAAA,CAAO,QAAA,CAASC,CAAE,CAAA,EAAK,CAAC,MAAA,CAAO,QAAA,CAASC,CAAE,CAAA,EAAK,CAAC,OAAO,QAAA,CAASC,CAAC,EAAG,OAAO,MAAA,CAAO,GAAA,CAGvF,IAAMC,EAAIH,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMC,CAAAA,CAAK,EAAE,CAAA,CAC3BG,CAAAA,CAAAA,CAAMH,CAAAA,CAAK,EAAA,CAAM,IAAM,EAAA,CAAK,CAAA,CAG5BI,EAAcF,CAAAA,EAAKC,CAAAA,EAAK,EAAI,CAAA,CAAI,CAAA,CAAA,CAChCE,CAAAA,CAAM,IAAA,CAAK,MAAMD,CAAAA,CAAc,GAAG,CAAA,CAClCE,CAAAA,CAAYF,EAAcC,CAAAA,CAAM,GAAA,CAChCE,CAAAA,CAAY,IAAA,CAAK,OAAO,GAAA,EAAOJ,CAAAA,EAAKA,EAAI,CAAA,CAAI,EAAA,CAAK,IAAM,CAAA,EAAK,CAAC,CAAA,CAC7DK,CAAAA,CAAWF,EA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ACf,CACD,CACD,EAGA,SAAS9B,CAAAA,CAAmBF,CAAAA,CAAqD,CAChF,IAAMyC,CAAAA,CAAYzC,CAAAA,CACZ0C,CAAAA,CACL,OAAOD,CAAAA,EAAW,GAAA,EAAK,OAAA,EAAY,UAAA,CAAa,cAChD,OAAOA,CAAAA,EAAW,KAAK,UAAA,EAAe,UAAA,CAAa,iBACnD,OAAOA,CAAAA,EAAW,OAAA,EAAS,qBAAA,EAA0B,WAAa,+BAAA,CAClE,OAAOA,CAAAA,EAAW,aAAA,EAAe,MAAS,UAAA,CAAa,oBAAA,CACvD,IAAA,CACD,GAAIC,IAAY,IAAA,CACf,MAAMpC,EAAa,MAAA,CAClBC,CAAAA,CAAe,gCACf,CAAA,wJAAA,EAA2JmC,CAAO,CAAA,CAAA,CAClK,CAAE,QAAAA,CAAQ,CACX,CAEF,CAoBO,SAASC,CAAAA,CAAuB3C,CAAAA,CAAwBC,CAAAA,CAAmC,GAAsB,CACvH,OAAO,IAAIF,CAAAA,CAAiBC,CAAAA,CAAUC,CAAO,CAC9C","file":"chunk-D4VBWPWN.js","sourcesContent":["/**\n * The day arithmetic behind `Date`'s field normalisation, for the `Temporal`\n * backend.\n *\n * `Date` normalises a set of wall-clock fields before it resolves them in a\n * zone: month 13 rolls into the next year, day 0 into the month before, a\n * time past midnight into the next day, and only the final instant is\n * clipped to the range `Date` represents. That is the `MakeDay` and\n * `MakeTime` order of the ECMAScript specification, and a backend built on\n * another library has to follow it to answer what `Date` answers on the last\n * representable day and for a rolled-over literal. `Date` does this\n * arithmetic inside its own setters, where a second backend cannot reach it,\n * so it is written out here with nothing clipped.\n *\n * Under `temporal/` rather than `calendar/Gregorian.ts` because only the\n * `Temporal` backend needs it: the `Date` backend gets the same arithmetic\n * from `Date` itself, and keeping it here keeps it out of the root entry's\n * bundle. The unit spec measures it against `Date.UTC` and `setUTCFullYear`\n * wherever `Date` can represent the date.\n *\n * @module CivilDays\n */\n\n/** A calendar date as year, zero-based month and day, the shape the civil-day arithmetic exchanges. */\nexport interface CivilDate {\n\treadonly year: number;\n\t/** Zero-based month: 0 is January, 11 is December. */\n\treadonly month0: number;\n\t/** Day of the month, from 1. */\n\treadonly day: number;\n}\n\n/**\n * The day number of a calendar date, counted from 1 January 1970, by\n * arithmetic alone: no `Date`, so no clip to the range `Date` represents.\n *\n * This is the `MakeDay` step of the ECMAScript specification, which a\n * backend needs unclipped: `Date` normalises a set of fields (month 13, day\n * 0, a time past midnight) before it resolves them in a zone and clips the\n * result, so a wall-clock time on the last representable day is an instant,\n * not `NaN`, and a backend built on another library must follow the same\n * order. An overflowing month or day rolls into the adjacent year or month,\n * as {@link utcMs}'s do, and a fractional field is truncated, as `Date`\n * truncates it.\n *\n * @param year - The calendar year, read as written.\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @param day - Day of the month; overflow rolls into the adjacent month.\n * @returns Whole days since 1 January 1970, negative before it, or `NaN` when a field is not finite.\n */\nexport function civilDayNumber(year: number, month0: number, day: number): number {\n\tconst y0 = Math.trunc(year);\n\tconst m0 = Math.trunc(month0);\n\tconst d = Math.trunc(day);\n\tif (!Number.isFinite(y0) || !Number.isFinite(m0) || !Number.isFinite(d)) return Number.NaN;\n\t// Normalise the month into the year first, then count from the first of\n\t// that month, so a day of 0 or 40 is a plain offset from a real month.\n\tconst y = y0 + Math.floor(m0 / 12);\n\tconst m = ((m0 % 12) + 12) % 12 + 1;\n\t// The days-from-civil arithmetic, with the year taken to start in March\n\t// so a leap day is the last day of the cycle rather than an exception.\n\tconst shiftedYear = y - (m <= 2 ? 1 : 0);\n\tconst era = Math.floor(shiftedYear / 400);\n\tconst yearOfEra = shiftedYear - era * 400;\n\tconst dayOfYear = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5);\n\tconst dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;\n\treturn era * 146_097 + dayOfEra - 719_468 + (d - 1);\n}\n\n/**\n * The calendar date of a day number, the inverse of {@link civilDayNumber}.\n *\n * @param days - Whole days since 1 January 1970, negative before it.\n * @returns The date, or `NaN` in every field when `days` is not finite.\n */\nexport function civilFromDayNumber(days: number): CivilDate {\n\tif (!Number.isFinite(days)) return { year: Number.NaN, month0: Number.NaN, day: Number.NaN };\n\tconst z = Math.trunc(days) + 719_468;\n\tconst era = Math.floor(z / 146_097);\n\tconst dayOfEra = z - era * 146_097;\n\tconst yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36_524) - Math.floor(dayOfEra / 146_096)) / 365);\n\tconst dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));\n\tconst monthFromMarch = Math.floor((5 * dayOfYear + 2) / 153);\n\tconst day = dayOfYear - Math.floor((153 * monthFromMarch + 2) / 5) + 1;\n\tconst month = monthFromMarch < 10 ? monthFromMarch + 3 : monthFromMarch - 9;\n\tconst year = yearOfEra + era * 400 + (month <= 2 ? 1 : 0);\n\treturn { year, month0: month - 1, day };\n}\n","/**\n * The `Temporal` calendar backend: the engine's date questions answered\n * through a `Temporal` implementation the host supplies, in a time zone the\n * host chooses.\n *\n * `Temporal` is the JavaScript standard library's replacement for `Date`. It\n * ships unflagged in Node 26 and in current Chrome, Firefox and Deno, but not\n * in Safari nor in Node 22 and 24, and the smallest polyfill adds about twenty\n * kilobytes gzipped to a bundle. The engine therefore imports no `Temporal`\n * and no polyfill: this module is reached only through the\n * `solve-engine/temporal` entry, and the host hands it the implementation to\n * use, `globalThis.Temporal` on a runtime that has one or a polyfill's export.\n * A host that never imports the entry pays nothing for it.\n *\n * The backend answers exactly what the `Date` backend answers. That is a\n * design constraint rather than a hope: `Temporal` and `Date` differ in what\n * they do with an out-of-range instant (`RangeError` against `NaN`), a\n * fractional millisecond (a throw against truncation), a day past the end of\n * a month (a clamp or a throw against a roll into the next month) and a year\n * from 0 to 99 (read literally against read as the 1900s), and every one of\n * those is reproduced here the way `Date` does it, because the engine's\n * results are measured against `Date` and a host switching backends must see\n * no result move. The differential suite under `__tests__/temporal/` is what\n * holds that line.\n *\n * The one thing that does change is the zone. `Date` reads the process's own\n * zone and nothing else; this backend reads the zone it was constructed with,\n * so a document can be computed in Tokyo from a server in London, or in a\n * zone the reader picks. That is the capability the backend adds, and the\n * only observable difference.\n *\n * The named-zone display strings go through the same `Intl.DateTimeFormat`\n * helpers the `Date` backend uses (`calendar/IntlZone.ts`), and the zone-free\n * arithmetic through `calendar/Gregorian.ts`, so the two backends share one\n * implementation wherever an answer does not depend on which backend is in\n * use. The one piece of arithmetic `Date` keeps inside its own setters, the\n * normalisation of overflowing fields, is written out in `CivilDays.ts`.\n *\n * @module TemporalCalendar\n */\n\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"@solve-js/calendar/CalendarBackend\";\nimport { daysInMonth } from \"@solve-js/calendar/Gregorian\";\nimport { civilDayNumber, civilFromDayNumber } from \"./CivilDays\";\nimport { dateInZone, timeInZone } from \"@solve-js/calendar/IntlZone\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { CoreErrorCodes } from \"@solve-js/errors/ErrorCode\";\n\n/**\n * The part of a `Temporal.Instant` the backend reads: its epoch milliseconds,\n * and the zoned date-time it shows in a named zone.\n */\nexport interface TemporalInstantLike {\n\treadonly epochMilliseconds: number;\n\ttoZonedDateTimeISO(timeZone: string): TemporalZonedDateTimeLike;\n}\n\n/**\n * The part of a `Temporal.ZonedDateTime` the backend reads: the calendar\n * fields (a one-based month and an ISO weekday, Monday 1 to Sunday 7, both\n * translated at the boundary), the offset, and the instant.\n */\nexport interface TemporalZonedDateTimeLike {\n\treadonly year: number;\n\t/** One-based month, 1 is January, as `Temporal` counts. */\n\treadonly month: number;\n\treadonly day: number;\n\t/** ISO weekday: Monday is 1, Sunday is 7. */\n\treadonly dayOfWeek: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly second: number;\n\treadonly millisecond: number;\n\t/** The zone's offset from UTC at this instant, in nanoseconds, positive when ahead. */\n\treadonly offsetNanoseconds: number;\n\treadonly epochMilliseconds: number;\n\t/** The zone's canonical IANA identifier. */\n\treadonly timeZoneId: string;\n}\n\n/** The part of a `Temporal.PlainDateTime` the backend uses: resolving a wall-clock time to an instant in a zone. */\nexport interface TemporalPlainDateTimeLike {\n\ttoZonedDateTime(\n\t\ttimeZone: string,\n\t\toptions?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" },\n\t): TemporalZonedDateTimeLike;\n}\n\n/** The wall-clock fields a `Temporal.PlainDateTime` is built from, with a one-based month. */\nexport interface TemporalDateTimeFields {\n\tyear: number;\n\t/** One-based month, 1 is January. */\n\tmonth: number;\n\tday: number;\n\thour: number;\n\tminute: number;\n\tsecond: number;\n\tmillisecond: number;\n}\n\n/**\n * The subset of the `Temporal` namespace the backend uses, as a structural\n * type, so the engine compiles and ships with no `Temporal` type installed\n * and a host passes whichever implementation it has: `globalThis.Temporal`\n * on Node 26 or a current browser, or the export of a polyfill such as\n * `temporal-polyfill`. Both satisfy this shape as they are.\n */\nexport interface TemporalLike {\n\treadonly Now: {\n\t\tinstant(): TemporalInstantLike;\n\t\ttimeZoneId(): string;\n\t};\n\treadonly Instant: {\n\t\tfromEpochMilliseconds(epochMilliseconds: number): TemporalInstantLike;\n\t};\n\treadonly PlainDateTime: {\n\t\tfrom(fields: TemporalDateTimeFields, options?: { overflow?: \"constrain\" | \"reject\" }): TemporalPlainDateTimeLike;\n\t};\n}\n\n/** What {@link createTemporalCalendar} takes beside the implementation. */\nexport interface TemporalCalendarOptions {\n\t/**\n\t * The IANA time zone the engine computes dates in (`\"Asia/Tokyo\"`,\n\t * `\"UTC\"`). Defaults to the runtime's own zone, `Temporal.Now.timeZoneId()`,\n\t * which is what the `Date` backend reads. A zone the implementation does\n\t * not know is refused at construction with `TEMPORAL_TIME_ZONE_UNKNOWN`.\n\t */\n\ttimeZone?: string;\n\t/**\n\t * The clock `now()` reads, in epoch milliseconds. Defaults to\n\t * `Temporal.Now.instant()`. A test pins a date with this: a fake-timer\n\t * library replaces `Date.now`, which the `Date` backend reads, but not\n\t * `Temporal.Now`, so this backend needs telling separately.\n\t */\n\tnow?: () => number;\n}\n\n/** The fields the `Date` backend answers for an instant it cannot represent. */\nconst NAN_FIELDS: CalendarFields = Object.freeze({\n\tyear: Number.NaN, month0: Number.NaN, day: Number.NaN, weekday: Number.NaN,\n\thour: Number.NaN, minute: Number.NaN, second: Number.NaN, millisecond: Number.NaN,\n});\n\n/** The largest magnitude `Date` represents, in milliseconds either side of the epoch. */\nconst MAX_INSTANT = 8.64e15;\n\n/** Milliseconds in a day of wall-clock fields, before any zone is consulted. */\nconst MS_PER_DAY = 86_400_000;\n\n/**\n * An instant as `Date` would hold it: truncated to a whole millisecond, or\n * `NaN` when it is not finite or lies past the range `Date` represents. This\n * is `Date`'s own clip (its `TimeClip`), applied before an instant reaches\n * `Temporal`, which throws for both cases where `Date` answers `NaN`.\n */\nfunction clip(epochMs: number): number {\n\tif (!Number.isFinite(epochMs) || Math.abs(epochMs) > MAX_INSTANT) return Number.NaN;\n\treturn Math.trunc(epochMs);\n}\n\n/**\n * Wall-clock fields normalised the way `Date`'s `MakeDay` and `MakeTime`\n * normalise them, with nothing clipped: the day number of the date the\n * fields land on after any overflow rolls, and the time within that day.\n * Each field is truncated to an integer first, as `Date` truncates it.\n */\ninterface WallClock {\n\treadonly dayNumber: number;\n\treadonly timeOfDay: number;\n}\n\n/** `MakeDay` and `MakeTime`, then `MakeDate`, with a time past midnight carried into the day. */\nfunction normaliseWallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): WallClock {\n\tconst time = Math.trunc(hour) * 3_600_000 + Math.trunc(minute) * 60_000 + Math.trunc(second) * 1_000 + Math.trunc(millisecond);\n\tconst dayNumber = civilDayNumber(year, month0, day) + Math.floor(time / MS_PER_DAY);\n\treturn { dayNumber, timeOfDay: ((time % MS_PER_DAY) + MS_PER_DAY) % MS_PER_DAY };\n}\n\n/**\n * The ECMAScript date-time string format, as the `Date` constructor reads it:\n * a four-digit or six-digit signed year, an optional month and day, an\n * optional time to the millisecond (longer fractions are truncated), and an\n * optional `Z` or offset. The `T` and `Z` may be lower case, and an offset\n * may omit its colon; both are what the runtime's parser accepts.\n */\nconst ISO_DATE_TIME =\n\t/^([+-]\\d{6}|\\d{4})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:[Tt](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?)?([Zz]|[+-]\\d{2}:?\\d{2})?$/;\n\n/**\n * A {@link CalendarBackend} over a `Temporal` implementation, computing in\n * one named time zone. Build one with {@link createTemporalCalendar}.\n *\n * Every method answers what the `Date` backend answers for the same inputs\n * when the zone is the process's own; see the module comment for the\n * differences between `Temporal` and `Date` that are reproduced deliberately.\n * The local methods answer `NaN` for an instant or a date the backend cannot\n * represent and never throw; the four named-zone methods throw the runtime's\n * `RangeError` for a zone it does not know or an instant it cannot represent,\n * which is the contract the interface states.\n */\nexport class TemporalCalendar implements CalendarBackend {\n\t/** The IANA zone every local answer is computed in, in its canonical spelling. */\n\treadonly timeZone: string;\n\n\tprivate readonly temporal: TemporalLike;\n\tprivate readonly clock: () => number;\n\n\tconstructor(temporal: TemporalLike, options: TemporalCalendarOptions = {}) {\n\t\tassertTemporalLike(temporal);\n\t\tthis.temporal = temporal;\n\t\tconst requested = options.timeZone ?? temporal.Now.timeZoneId();\n\t\tlet probe: TemporalZonedDateTimeLike;\n\t\ttry {\n\t\t\tprobe = temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(requested);\n\t\t} catch (error) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tCoreErrorCodes.TEMPORAL_TIME_ZONE_UNKNOWN,\n\t\t\t\t`The Temporal implementation does not know the time zone \"${requested}\"`,\n\t\t\t\t{ timeZone: requested, cause: error instanceof Error ? error.message : String(error) },\n\t\t\t);\n\t\t}\n\t\t// The canonical spelling, so a zone given as `asia/tokyo` reads back as\n\t\t// the identifier the implementation itself uses.\n\t\tthis.timeZone = probe.timeZoneId;\n\t\tthis.clock = options.now ?? (() => temporal.Now.instant().epochMilliseconds);\n\t}\n\n\tnow(): number {\n\t\treturn this.clock();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return NAN_FIELDS;\n\t\treturn {\n\t\t\tyear: z.year,\n\t\t\tmonth0: z.month - 1,\n\t\t\tday: z.day,\n\t\t\t// ISO's Monday 1 to Sunday 7 becomes Date's Sunday 0 to Saturday 6.\n\t\t\tweekday: z.dayOfWeek % 7,\n\t\t\thour: z.hour,\n\t\t\tminute: z.minute,\n\t\t\tsecond: z.second,\n\t\t\tmillisecond: z.millisecond,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn this.wallClock(year, month0, day, 0, 0, 0, 0);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// `Date`'s sequence exactly: anchor at midnight, then set the minutes\n\t\t// FIELD, which reads the hour, second and millisecond back from the\n\t\t// anchored local time. On a day whose midnight falls in a\n\t\t// daylight-saving gap the anchor resolves to 1 am, and the hour it\n\t\t// reads back is 1, which is what makes the two backends agree there.\n\t\tconst anchored = this.localMidnight(year, month0, day);\n\t\tconst a = this.fields(anchored);\n\t\tif (Number.isNaN(a.year)) return Number.NaN;\n\t\treturn this.wallClock(a.year, a.month0, a.day, a.hour, minutesPastMidnight, a.second, a.millisecond);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\t// `setDate()`: the day field moves and the local time of day is held.\n\t\tconst f = this.fields(epochMs);\n\t\tif (Number.isNaN(f.year)) return Number.NaN;\n\t\treturn this.wallClock(f.year, f.month0, f.day + days, f.hour, f.minute, f.second, f.millisecond);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\t// The `Date` backend's three field writes, each resolved to an instant\n\t\t// and read back before the next, so that a wall-clock time landing in\n\t\t// a transition on an intermediate date shifts the same way it does\n\t\t// there: park on the 1st, move the month, then clamp the day.\n\t\tconst f0 = this.fields(epochMs);\n\t\tif (Number.isNaN(f0.year)) return Number.NaN;\n\t\tconst dayOfMonth = f0.day;\n\t\tconst f1 = this.fields(this.wallClock(f0.year, f0.month0, 1, f0.hour, f0.minute, f0.second, f0.millisecond));\n\t\tif (Number.isNaN(f1.year)) return Number.NaN;\n\t\tconst f2 = this.fields(this.wallClock(f1.year, f1.month0 + months, f1.day, f1.hour, f1.minute, f1.second, f1.millisecond));\n\t\tif (Number.isNaN(f2.year)) return Number.NaN;\n\t\tconst day = Math.min(dayOfMonth, daysInMonth(f2.year, f2.month0));\n\t\treturn this.wallClock(f2.year, f2.month0, day, f2.hour, f2.minute, f2.second, f2.millisecond);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return Number.NaN;\n\t\t// `getTimezoneOffset()` answers whole minutes, truncated toward zero,\n\t\t// which only shows for the local-mean-time offsets in force before a\n\t\t// zone adopted standard time (London's was -00:01:15 until 1847).\n\t\t// `|| 0` folds the -0 a small negative offset truncates to.\n\t\treturn Math.trunc(z.offsetNanoseconds / 60_000_000_000) || 0;\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// Only the format itself. The `Date` constructor falls back to a\n\t\t// legacy parser for a string the format rejects (one with a space\n\t\t// around it, say) and may guess an instant from it; the engine's own\n\t\t// gate admits only the format, so the two backends cannot disagree\n\t\t// through it, and outside it this backend answers NaN rather than guess.\n\t\tconst m = ISO_DATE_TIME.exec(text);\n\t\tif (m === null) return Number.NaN;\n\t\tconst [, yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, zoneText] = m;\n\t\t// An expanded year of `-000000` names no year, by the format's own rule.\n\t\tif (yearText === \"-000000\") return Number.NaN;\n\t\tconst year = Number(yearText);\n\t\tconst month = monthText === undefined ? 1 : Number(monthText);\n\t\tconst day = dayText === undefined ? 1 : Number(dayText);\n\t\tconst hour = hourText === undefined ? 0 : Number(hourText);\n\t\tconst minute = minuteText === undefined ? 0 : Number(minuteText);\n\t\tconst second = secondText === undefined ? 0 : Number(secondText);\n\t\t// Only the first three digits of a fraction are milliseconds; the rest\n\t\t// are dropped rather than rounded, as the runtime's parser does.\n\t\tconst millisecond = fractionText === undefined ? 0 : Number(fractionText.slice(0, 3).padEnd(3, \"0\"));\n\t\t// The runtime checks a day against 31, not against the month, and lets\n\t\t// 30 February roll into March; 24:00 is the end of the day and nothing\n\t\t// past it is a time.\n\t\tif (month < 1 || month > 12 || day < 1 || day > 31) return Number.NaN;\n\t\tif (hour > 24 || minute > 59 || second > 59) return Number.NaN;\n\t\tif (hour === 24 && (minute !== 0 || second !== 0 || millisecond !== 0)) return Number.NaN;\n\n\t\t// The year is taken literally: the format has no 1900s window for a\n\t\t// year from 0 to 99, unlike the constructor.\n\t\tconst wall = normaliseWallClock(year, month - 1, day, hour, minute, second, millisecond);\n\t\tif (zoneText === undefined && hourText !== undefined) {\n\t\t\t// A date-time with no offset is local time, by the format's own rule.\n\t\t\treturn this.resolve(wall);\n\t\t}\n\t\t// A date-only string is UTC midnight, and an offset is subtracted.\n\t\tlet offsetMinutes = 0;\n\t\tif (zoneText !== undefined && zoneText !== \"Z\" && zoneText !== \"z\") {\n\t\t\tconst digits = zoneText.slice(1).replace(\":\", \"\");\n\t\t\tconst offsetHours = Number(digits.slice(0, 2));\n\t\t\tconst offsetMinutesPart = Number(digits.slice(2, 4));\n\t\t\tif (offsetHours > 23 || offsetMinutesPart > 59) return Number.NaN;\n\t\t\toffsetMinutes = (zoneText[0] === \"-\" ? -1 : 1) * (offsetHours * 60 + offsetMinutesPart);\n\t\t}\n\t\tconst instant = wall.dayNumber * MS_PER_DAY + wall.timeOfDay - offsetMinutes * 60_000;\n\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\t// `toLocaleDateString()` on an invalid date, rather than the throw\n\t\t// `Intl` would raise.\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\t// `toLocaleTimeString()` with no options is the hour, minute and second\n\t\t// in the locale's own style.\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, hour: \"numeric\", minute: \"numeric\", second: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// A fault here is the caller's to see, as the contract states, so no\n\t\t// clip: a non-finite instant reaches `Temporal` and throws its\n\t\t// RangeError, as an unknown zone does.\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t// The `Date` backend reads the zone's wall clock to the second and\n\t\t// rounds the difference from the instant to whole minutes; the same\n\t\t// arithmetic on the exact offset keeps the two answers identical for\n\t\t// the pre-standard-time offsets that are not whole minutes.\n\t\tconst wallSecond = Math.floor((t + z.offsetNanoseconds / 1e6) / 1000) * 1000;\n\t\treturn Math.round((wallSecond - epochMs) / 60_000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\treturn { year: z.year, month0: z.month - 1, day: z.day, hour: z.hour, minute: z.minute, second: z.second };\n\t}\n\n\t/** The IANA zone this backend computes in, which is what `CalendarBackend.zone` documents. */\n\tzone(): string {\n\t\treturn this.timeZone;\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n\n\t/** The zoned date-time of an instant, or `null` where `Date` would answer `NaN`. */\n\tprivate zoned(epochMs: number, zone: string): TemporalZonedDateTimeLike | null {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return null;\n\t\ttry {\n\t\t\treturn this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t} catch {\n\t\t\t// Past the range the implementation represents in this zone.\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * The instant a set of local wall-clock fields names, with the fields\n\t * normalised the way `Date`'s constructor and setters normalise them\n\t * (month 12 is next January, day 0 the last of the month before, a year\n\t * from 0 to 99 the 1900s) before the zone is consulted.\n\t */\n\tprivate wallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): number {\n\t\t// The constructor's two-digit-year window, applied to the year as\n\t\t// written and before any overflow, as `Date` applies it.\n\t\tconst windowed = year >= 0 && year <= 99 ? 1900 + Math.trunc(year) : year;\n\t\treturn this.resolve(normaliseWallClock(windowed, month0, day, hour, minute, second, millisecond));\n\t}\n\n\t/**\n\t * Normalised wall-clock fields resolved to an instant in the backend's\n\t * zone, clipped to the range `Date` represents only then, as `Date` clips\n\t * last. `compatible` disambiguation is `Date`'s rule: a time in a\n\t * spring-forward gap moves later by the gap, and a time that occurs twice\n\t * on a fall-back day is its first occurrence.\n\t */\n\tprivate resolve(wall: WallClock): number {\n\t\tconst civil = civilFromDayNumber(wall.dayNumber);\n\t\tif (Number.isNaN(civil.year)) return Number.NaN;\n\t\tconst hour = Math.floor(wall.timeOfDay / 3_600_000);\n\t\tconst minute = Math.floor(wall.timeOfDay / 60_000) % 60;\n\t\tconst second = Math.floor(wall.timeOfDay / 1_000) % 60;\n\t\tconst millisecond = wall.timeOfDay % 1_000;\n\t\ttry {\n\t\t\tconst plain = this.temporal.PlainDateTime.from(\n\t\t\t\t{ year: civil.year, month: civil.month0 + 1, day: civil.day, hour, minute, second, millisecond },\n\t\t\t\t{ overflow: \"reject\" },\n\t\t\t);\n\t\t\tconst instant = plain.toZonedDateTime(this.timeZone, { disambiguation: \"compatible\" }).epochMilliseconds;\n\t\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t\t} catch {\n\t\t\t// Past the range the implementation represents: `Date` answers NaN.\n\t\t\treturn Number.NaN;\n\t\t}\n\t}\n}\n\n/** Refuse anything that is not a usable `Temporal` before a method can fail on it obscurely. */\nfunction assertTemporalLike(temporal: unknown): asserts temporal is TemporalLike {\n\tconst candidate = temporal as Partial<TemporalLike> | null | undefined;\n\tconst missing =\n\t\ttypeof candidate?.Now?.instant !== \"function\" ? \"Now.instant\" :\n\t\ttypeof candidate?.Now?.timeZoneId !== \"function\" ? \"Now.timeZoneId\" :\n\t\ttypeof candidate?.Instant?.fromEpochMilliseconds !== \"function\" ? \"Instant.fromEpochMilliseconds\" :\n\t\ttypeof candidate?.PlainDateTime?.from !== \"function\" ? \"PlainDateTime.from\" :\n\t\tnull;\n\tif (missing !== null) {\n\t\tthrow ErrorFactory.config(\n\t\t\tCoreErrorCodes.TEMPORAL_IMPLEMENTATION_INVALID,\n\t\t\t`createTemporalCalendar needs a Temporal implementation (globalThis.Temporal on a runtime that ships it, or a polyfill's export); the value given has no ${missing}`,\n\t\t\t{ missing },\n\t\t);\n\t}\n}\n\n/**\n * A calendar backend over the host's `Temporal`, for the engine's `calendar`\n * option.\n *\n * ```ts\n * import { createEngine } from \"solve-engine\";\n * import { createTemporalCalendar } from \"solve-engine/temporal\";\n *\n * const calendar = createTemporalCalendar(globalThis.Temporal, { timeZone: \"Asia/Tokyo\" });\n * const engine = createEngine({ calendar });\n * ```\n *\n * @param temporal - The `Temporal` implementation: `globalThis.Temporal` where the runtime ships one, or a polyfill's export.\n * @param options - The zone to compute in and, for a test, the clock to read; see {@link TemporalCalendarOptions}.\n * @returns A backend that computes every date in that zone and answers what the `Date` backend would in it.\n * @throws `TEMPORAL_IMPLEMENTATION_INVALID` when `temporal` lacks the members the backend uses, and\n * `TEMPORAL_TIME_ZONE_UNKNOWN` when the implementation does not know the zone asked for.\n */\nexport function createTemporalCalendar(temporal: TemporalLike, options: TemporalCalendarOptions = {}): TemporalCalendar {\n\treturn new TemporalCalendar(temporal, options);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function p(e,t,r,n=0,o=0,u=0){return Date.UTC(e,t,r,n,o,u)}function h(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function C(e,t,r){return Math.floor(Date.UTC(e,t,r)/864e5)}function F(e){let t=new Date(e);return {year:t.getUTCFullYear(),month0:t.getUTCMonth(),day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function U(e,t,r){let n=new Date(Date.UTC(e,t,r)),o=n.getUTCDay()===0?7:n.getUTCDay();n.setUTCDate(n.getUTCDate()+4-o);let u=Date.UTC(n.getUTCFullYear(),0,1),i=Math.floor((n.getTime()-u)/864e5);return Math.floor(i/7)+1}var d="UTCOFFSET:";function I(e){return `${d}${e}`}function D(e){return e.startsWith(d)}function y(e){return parseInt(e.slice(d.length),10)}function c(e,t,r){return D(e)?y(e):r.zoneOffsetMinutes(e,t)}function Z(e,t,r,n,o,u,i){let m=p(e,t,r,n,o,0),g=c(u,m,i),s=m-g*6e4,l=c(u,s,i);if(l===g)return s;let a=m-l*6e4,b=T=>T+c(u,T,i)*6e4===m;return b(s)?s:b(a)?a:Math.max(s,a)}function O(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return false}}function f(e,t){return new Intl.DateTimeFormat("en-US",{timeZone:e,...t})}function S(e,t){let r=f(e,{hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),n={};for(let o of r.formatToParts(t))n[o.type]=o.value;return {year:+n.year,month0:+n.month-1,day:+n.day,hour:+n.hour,minute:+n.minute,second:+n.second}}function _(e,t){return f(e,{hour:"numeric",minute:"2-digit",hour12:true}).format(t)}function w(e,t){return f(e,{year:"numeric",month:"long",day:"numeric"}).format(t)}function k(e,t,r){return new Intl.DateTimeFormat(r,{timeZone:e,weekday:"long",year:"numeric",month:"long",day:"numeric"}).format(t)}function E(e,t,r){return new Intl.DateTimeFormat(r,{timeZone:e,hour:"numeric",minute:"numeric",second:"numeric"}).format(t)}exports.a=p;exports.b=h;exports.c=C;exports.d=F;exports.e=U;exports.f=I;exports.g=D;exports.h=y;exports.i=c;exports.j=Z;exports.k=O;exports.l=S;exports.m=_;exports.n=w;exports.o=k;exports.p=E;//# sourceMappingURL=chunk-E4HAKNBQ.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-E4HAKNBQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/calendar/Gregorian.ts","../src/calendar/IntlZone.ts"],"names":["utcMs","year","month0","day","hour","minute","second","daysInMonth","dayNumber","utcFields","epochMs","d","isoWeekNumber","target","isoDay","yearStart","days","FIXED_OFFSET_PREFIX","encodeFixedOffset","offsetMinutes","isFixedOffset","zoneRef","decodeFixedOffsetMinutes","resolveOffsetMinutes","atMs","calendar","zonedWallClockToUtcMs","naiveUtcMs","naiveOffset","firstGuess","refinedOffset","secondGuess","shows","candidate","isSupportedZone","zone","formatter","options","zonedFields","dtf","parts","p","timeInZone","dateInZone","longDateInZone","locale","timeOfDayInZone"],"mappings":"aAmCO,SAASA,CAAAA,CAAMC,CAAAA,CAAcC,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAAO,CAAA,CAAGC,CAAAA,CAAS,CAAA,CAAGC,CAAAA,CAAS,CAAA,CAAW,CAC1G,OAAO,IAAA,CA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A,CAAAA,CAAQ,CACtC,QAAA,CAAUV,CAAAA,CAAM,IAAA,CAAM,SAAA,CAAW,MAAA,CAAQ,SAAA,CAAW,MAAA,CAAQ,SAC7D,CAAC,CAAA,CAAE,MAAA,CAAOzB,CAAO,CAClB","file":"chunk-E4HAKNBQ.cjs","sourcesContent":["import type { ZonedFields } from \"./CalendarBackend\";\n\n/**\n * Gregorian arithmetic that does not depend on a time zone, shared by every\n * {@link CalendarBackend} rather than implemented behind each one.\n *\n * A backend exists to answer the questions whose answer depends on a zone:\n * which local day an instant falls on, what the same wall-clock time a month\n * later is. Once the fields are known, the day number of a date, the ISO week\n * it falls in and the instant its fields name in UTC are pure functions of\n * those fields. Keeping them here, with one implementation, is what makes two\n * backends agree on them by construction.\n *\n * The arithmetic is `Date`'s own UTC methods, which read and write the number\n * with no zone consulted. That includes `Date`'s reading of a year from 0 to\n * 99 as the 1900s in `Date.UTC`, kept because the engine's results are\n * measured against it.\n *\n * @module Gregorian\n */\n\n/** Milliseconds in a UTC day, which has no daylight-saving transition to make it longer or shorter. */\nconst MS_PER_DAY = 86_400_000;\n\n/**\n * The instant a set of calendar fields names in UTC, in epoch milliseconds.\n *\n * @param year - The calendar year (0 to 99 read as the 1900s, as `Date.UTC` does).\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @param day - Day of the month; overflow rolls into the adjacent month.\n * @param hour - Hour of the day, default 0.\n * @param minute - Minute of the hour, default 0.\n * @param second - Second of the minute, default 0.\n * @returns Epoch milliseconds, or `NaN` when the fields are not finite.\n */\nexport function utcMs(year: number, month0: number, day: number, hour = 0, minute = 0, second = 0): number {\n\treturn Date.UTC(year, month0, day, hour, minute, second);\n}\n\n/**\n * Days in a calendar month, honouring the leap-year rule, century rule\n * included.\n *\n * Day zero of the following month is the last day of this one, which applies\n * the rule without restating it. Shared rather than a backend method because\n * the answer never depends on a zone, and the month clamp in a month step and\n * the count in `days in <period>` must not move between backends.\n *\n * @param year - The calendar year (0 to 99 read as the 1900s, as `Date.UTC` does).\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @returns 28 to 31.\n */\nexport function daysInMonth(year: number, month0: number): number {\n\treturn new Date(Date.UTC(year, month0 + 1, 0)).getUTCDate();\n}\n\n/**\n * A calendar date's day count from the epoch, for a difference between two\n * dates that no daylight-saving hour can tip onto the wrong day.\n *\n * @param year - The calendar year.\n * @param month0 - Zero-based month.\n * @param day - Day of the month.\n * @returns Whole days since 1 January 1970, negative before it.\n */\nexport function dayNumber(year: number, month0: number, day: number): number {\n\treturn Math.floor(Date.UTC(year, month0, day) / MS_PER_DAY);\n}\n\n/**\n * The calendar date and wall-clock time an instant has in UTC.\n *\n * The fixed-offset zones (`GMT+8`) are converted by shifting the instant by\n * the offset and reading it as UTC, which is what this is for.\n *\n * @param epochMs - The instant.\n * @returns Its UTC fields, each `NaN` for an unrepresentable instant.\n */\nexport function utcFields(epochMs: number): ZonedFields {\n\tconst d = new Date(epochMs);\n\treturn {\n\t\tyear: d.getUTCFullYear(),\n\t\tmonth0: d.getUTCMonth(),\n\t\tday: d.getUTCDate(),\n\t\thour: d.getUTCHours(),\n\t\tminute: d.getUTCMinutes(),\n\t\tsecond: d.getUTCSeconds(),\n\t};\n}\n\n/**\n * The ISO 8601 week number (1 to 53) of a calendar date.\n *\n * ISO weeks start on Monday and week 1 is the one containing the first\n * Thursday of the year, which is why this steps to the Thursday of the\n * date's week before counting. A naive \"day of year over seven\" disagrees\n * with every calendar application for the first and last days of a year.\n *\n * @param year - The calendar year.\n * @param month0 - Zero-based month.\n * @param day - Day of the month.\n * @returns The week number, 1 to 53.\n */\nexport function isoWeekNumber(year: number, month0: number, day: number): number {\n\t// A date-only copy in UTC, so no local hour can shift the day.\n\tconst target = new Date(Date.UTC(year, month0, day));\n\t// `getUTCDay()` counts Sunday as 0. Map to ISO's Monday 1 to Sunday 7,\n\t// then step to the Thursday of the same week.\n\tconst isoDay = target.getUTCDay() === 0 ? 7 : target.getUTCDay();\n\ttarget.setUTCDate(target.getUTCDate() + 4 - isoDay);\n\tconst yearStart = Date.UTC(target.getUTCFullYear(), 0, 1);\n\tconst days = Math.floor((target.getTime() - yearStart) / MS_PER_DAY);\n\treturn Math.floor(days / 7) + 1;\n}\n","import type { CalendarBackend, ZonedFields } from \"./CalendarBackend\";\nimport { utcMs } from \"./Gregorian\";\n\n/**\n * Named-zone reads through `Intl.DateTimeFormat`, shared by every backend.\n *\n * `Intl` is the one place every supported runtime keeps the IANA time zone\n * database, so it is what the `Date` backend answers a named-zone question\n * with, and it is also what writes a zoned wall-clock time out in a locale for\n * the `Temporal` backend: `Temporal`'s own `toLocaleString` is `Intl`\n * underneath, and calling `Intl` directly with the zone keeps the two backends\n * on one formatting path, so the string a timezone form shows cannot depend on\n * which backend produced it.\n *\n * Every function here throws the runtime's own `RangeError` for a zone name it\n * does not know or an instant it cannot represent, which is the contract the\n * backend's named-zone methods state.\n *\n * ## The zone reference, and why the encoding lives here\n * A \"zone reference\" is either a real IANA identifier (`\"Australia/Sydney\"`) or\n * the synthetic fixed-offset form `\"UTCOFFSET:<minutes>\"`, which the numeric\n * `GMT+N`/`UTC-N` spelling needs because it has no IANA identifier of its own\n * and no daylight-saving rule to consult. {@link encodeFixedOffset},\n * {@link isFixedOffset} and {@link decodeFixedOffsetMinutes} are the only code\n * that knows the encoding exists.\n *\n * The encoding and {@link zonedWallClockToUtcMs} were written in the time\n * package (`packages/time/timezones/ZoneMath.ts`, which still re-exports every\n * one of them, so nothing that imported them there changed). They moved here\n * because the zone-bound `Date` backend needs them and `calendar/` may not\n * import from `packages/`: a backend reaching into an optional package for its\n * own arithmetic is the cycle the layering rule in `engine/EngineContext.ts`\n * exists to prevent.\n *\n * @module IntlZone\n */\n\nconst FIXED_OFFSET_PREFIX = \"UTCOFFSET:\";\n\n/**\n * Encode a fixed UTC offset as a zone reference.\n *\n * @param offsetMinutes - Minutes ahead of UTC, negative behind it.\n * @returns The `\"UTCOFFSET:<minutes>\"` reference.\n */\nexport function encodeFixedOffset(offsetMinutes: number): string {\n\treturn `${FIXED_OFFSET_PREFIX}${offsetMinutes}`;\n}\n\n/**\n * Whether a zone reference is a fixed offset rather than a named IANA zone.\n *\n * @param zoneRef - The reference to test.\n * @returns True for the `\"UTCOFFSET:<minutes>\"` form.\n */\nexport function isFixedOffset(zoneRef: string): boolean {\n\treturn zoneRef.startsWith(FIXED_OFFSET_PREFIX);\n}\n\n/**\n * Read the minutes out of a fixed-offset zone reference.\n *\n * @param zoneRef - A reference {@link isFixedOffset} accepted.\n * @returns Minutes ahead of UTC, negative behind it.\n */\nexport function decodeFixedOffsetMinutes(zoneRef: string): number {\n\treturn parseInt(zoneRef.slice(FIXED_OFFSET_PREFIX.length), 10);\n}\n\n/**\n * The UTC offset a zone reference has AT a given instant, in minutes,\n * positive when ahead of UTC.\n *\n * A fixed offset is its own answer. A named zone is resolved through the\n * backend, so a `Temporal` backend answers with `Temporal`'s zone data rather\n * than the `Date` backend's `Intl` round trip.\n *\n * @param zoneRef - An IANA name or a fixed-offset reference.\n * @param atMs - The instant to read the offset at.\n * @param calendar - The backend that resolves a named zone.\n * @returns The offset in minutes.\n */\nexport function resolveOffsetMinutes(zoneRef: string, atMs: number, calendar: CalendarBackend): number {\n\tif (isFixedOffset(zoneRef)) return decodeFixedOffsetMinutes(zoneRef);\n\treturn calendar.zoneOffsetMinutes(zoneRef, atMs);\n}\n\n/**\n * The UTC instant a wall-clock reading names when read as local time in a\n * zone reference, in epoch milliseconds.\n *\n * Two passes, not one. The first offset has to be read at the naive instant\n * (the fields taken as if they were UTC), because the real instant is what is\n * being computed; that naive instant is wrong by the zone's own offset, so in a\n * zone far from UTC it can fall on the other side of a daylight-saving\n * transition from the reading itself. Measured: 22:30 on 4 April 2026 in\n * Auckland answered 10:30 UTC on a single pass, an hour late, because the naive\n * instant is thirteen hours on and lands past the transition at 14:00 UTC on\n * the 4th. Re-reading the offset at the first guess and using it when the two\n * disagree narrows the window from the size of the offset to the transition\n * itself.\n *\n * What remains is inherent to any offset-based approach without a full\n * transition-table walk: a wall clock a spring-forward skipped never happened,\n * and one a fall-back repeated happened twice, so the answer for those readings\n * is a choice rather than a fact. A `Temporal` backend's\n * `disambiguation: 'compatible'` may choose differently, and the\n * calendar-backends page says so.\n *\n * @param year - The calendar year.\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @param day - Day of the month; overflow rolls into the adjacent month.\n * @param hour - Hour of the day.\n * @param minute - Minute of the hour; overflow rolls into the adjacent hour.\n * @param zoneRef - The zone the reading is in.\n * @param calendar - The backend that resolves a named zone.\n * @returns Epoch milliseconds.\n */\nexport function zonedWallClockToUtcMs(\n\tyear: number, month0: number, day: number, hour: number, minute: number,\n\tzoneRef: string, calendar: CalendarBackend,\n): number {\n\tconst naiveUtcMs = utcMs(year, month0, day, hour, minute, 0);\n\tconst naiveOffset = resolveOffsetMinutes(zoneRef, naiveUtcMs, calendar);\n\tconst firstGuess = naiveUtcMs - naiveOffset * 60000;\n\tconst refinedOffset = resolveOffsetMinutes(zoneRef, firstGuess, calendar);\n\tif (refinedOffset === naiveOffset) return firstGuess;\n\n\t// The two offsets disagree, so the reading sits near a transition. Taking\n\t// the refined one on trust moved the answer the wrong way in any zone\n\t// behind UTC: asking for 00:30 on a spring-forward morning in New York\n\t// landed on the previous day. Read each candidate back instead, and keep\n\t// the one that really shows the wall clock that was asked for.\n\tconst secondGuess = naiveUtcMs - refinedOffset * 60000;\n\tconst shows = (candidate: number): boolean =>\n\t\tcandidate + resolveOffsetMinutes(zoneRef, candidate, calendar) * 60000 === naiveUtcMs;\n\tif (shows(firstGuess)) return firstGuess;\n\tif (shows(secondGuess)) return secondGuess;\n\n\t// Neither shows it, so the reading is one a spring-forward skipped: it\n\t// never happened. The later instant is the one past the transition, which\n\t// is the same choice `Temporal`'s `disambiguation: 'compatible'` makes,\n\t// so the two backends agree on a reading that is a choice either way.\n\treturn Math.max(firstGuess, secondGuess);\n}\n\n/**\n * Whether this runtime's `Intl` can format in a named zone.\n *\n * Asked once, at the point a host names a zone, so a backend that cannot\n * compute in the zone it was given refuses there rather than answering in\n * another one per line.\n *\n * @param zone - An IANA zone name.\n * @returns True when `Intl` accepts the name.\n */\nexport function isSupportedZone(zone: string): boolean {\n\ttry {\n\t\tnew Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** An `en-US` formatter for a zone, the style the timezone forms answer in. */\nfunction formatter(zone: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n\treturn new Intl.DateTimeFormat(\"en-US\", { timeZone: zone, ...options });\n}\n\n/**\n * The calendar date and wall-clock time a named zone shows for an instant.\n *\n * @param zone - An IANA zone name.\n * @param epochMs - The instant.\n * @returns The zone's fields, with a zero-based month.\n */\nexport function zonedFields(zone: string, epochMs: number): ZonedFields {\n\t// `h23` so midnight reads as hour 0 rather than 24.\n\tconst dtf = formatter(zone, {\n\t\thourCycle: \"h23\",\n\t\tyear: \"numeric\", month: \"2-digit\", day: \"2-digit\",\n\t\thour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\",\n\t});\n\tconst parts: Record<string, string> = {};\n\tfor (const p of dtf.formatToParts(epochMs)) parts[p.type] = p.value;\n\treturn {\n\t\tyear: +parts.year, month0: +parts.month - 1, day: +parts.day,\n\t\thour: +parts.hour, minute: +parts.minute, second: +parts.second,\n\t};\n}\n\n/**\n * The wall-clock time in a named zone, `1:00 AM`, in the `en-US` style the\n * timezone forms answer in.\n *\n * @param zone - An IANA zone name.\n * @param epochMs - The instant.\n * @returns The formatted time.\n */\nexport function timeInZone(zone: string, epochMs: number): string {\n\treturn formatter(zone, { hour: \"numeric\", minute: \"2-digit\", hour12: true }).format(epochMs);\n}\n\n/**\n * The calendar date in a named zone, `July 31, 2026`, in the `en-US` style\n * the timezone forms answer in.\n *\n * @param zone - An IANA zone name.\n * @param epochMs - The instant.\n * @returns The formatted date.\n */\nexport function dateInZone(zone: string, epochMs: number): string {\n\treturn formatter(zone, { year: \"numeric\", month: \"long\", day: \"numeric\" }).format(epochMs);\n}\n\n/**\n * The spelled-out date a named zone shows for an instant, in a locale:\n * `Tuesday, March 10, 2026` in `en`.\n *\n * The zone-bound counterpart of `CalendarBackend.formatLongDate`, which reads\n * the backend's own zone. Separate from {@link dateInZone} because that one is\n * pinned to `en-US` for the timezone forms, while this follows the locale the\n * engine was asked to display in.\n *\n * @param zone - An IANA zone name.\n * @param epochMs - The instant.\n * @param locale - The BCP-47 tag to spell the date in.\n * @returns The formatted date.\n */\nexport function longDateInZone(zone: string, epochMs: number, locale: string): string {\n\treturn new Intl.DateTimeFormat(locale, {\n\t\ttimeZone: zone, weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\",\n\t}).format(epochMs);\n}\n\n/**\n * The time of day a named zone shows for an instant, in a locale:\n * `9:30:00 AM` in `en`.\n *\n * The zone-bound counterpart of `CalendarBackend.formatTimeOfDay`. The three\n * fields are all `numeric` because that is what `toLocaleTimeString()` with no\n * options requests, and the two spellings have to agree: measured, `en-GB`\n * gives `09:30:05` both ways, where a `2-digit` minute and second would give\n * `9:30:05`.\n *\n * @param zone - An IANA zone name.\n * @param epochMs - The instant.\n * @param locale - The BCP-47 tag to write the time in.\n * @returns The formatted time.\n */\nexport function timeOfDayInZone(zone: string, epochMs: number, locale: string): string {\n\treturn new Intl.DateTimeFormat(locale, {\n\t\ttimeZone: zone, hour: \"numeric\", minute: \"numeric\", second: \"numeric\",\n\t}).format(epochMs);\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-HFKDWQUL.js';import {c}from'./chunk-
|
|
2
|
-
export{f as a,p as b,g as c};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-HFKDWQUL.js';import {c}from'./chunk-VB6QMU2W.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-ESZNJQ2C.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-ESZNJQ2C.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,CA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,CAAwB,iBAAA,CAAA,CACpD,IAAA,GAAW,CAACF,CAAAA,CAAMoB,CAAI,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQa,CAAAA,CAAM,KAAK,CAAA,CACnDG,EAAS,CAAA,EAAGN,CAAI,CAAA,CAAA,EAAI9B,CAAI,CAAA,CAAE,CAAA,CAAIoB,EAC9BiB,CAAAA,CAAM,IAAA,CAGV,OAAOA,CAAAA,CAAMD,CAAAA,CAAW,IAC1B,CAKA,QAAA,EAAoB,CAClB,OAAO,IAAA,CAAK,WAAA,EAAY,GAAM,IAChC,CAMA,WAAA,CAAYV,CAAAA,CAAevB,CAAAA,CAAcC,CAAAA,CAA2B,CAClE,IAAMgB,EAAO,IAAA,CAAK,WAAA,CAAYjB,CAAAA,CAAMC,CAAE,CAAA,CACtC,OAAIgB,IAAS,IAAA,CAAa,IAAA,CACnBM,CAAAA,CAAQN,CACjB,CAmBA,UAAA,CAAWpB,EAAuB,CAChC,OAAOD,CAAAA,CAAUC,CAAI,CAAA,EAAK,IAAA,CAAK,YAAA,CAAaA,CAAI,CAClD,CACF,CAAA,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
|
+
{"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,CA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,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-ESZNJQ2C.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,2 +1,2 @@
|
|
|
1
|
-
var R={NUMBER:"NUMBER",BIGINT:"BIGINT",STRING:"STRING",IDENT:"IDENT",PLUS:"PLUS",MINUS:"MINUS",PLUS_EQUALS:"PLUS_EQUALS",MINUS_EQUALS:"MINUS_EQUALS",STAR:"STAR",SLASH:"SLASH",PLUS_MINUS:"PLUS_MINUS",CARET:"CARET",PERCENT:"PERCENT",LSHIFT:"LSHIFT",RSHIFT:"RSHIFT",URSHIFT:"URSHIFT",LPAREN:"LPAREN",RPAREN:"RPAREN",LBRACKET:"LBRACKET",RBRACKET:"RBRACKET",LBRACE:"LBRACE",RBRACE:"RBRACE",COMMA:"COMMA",DOT:"DOT",COLON:"COLON",SEMICOLON:"SEMICOLON",EQUALS:"EQUALS",DOLLAR:"DOLLAR",POUND:"POUND",EURO:"EURO",YEN:"YEN",RUBLE:"RUBLE",WON:"WON",QUESTION:"QUESTION",BANG:"BANG",BIT_AND:"BIT_AND",BIT_OR:"BIT_OR",BIT_NOT:"BIT_NOT",KEYWORD:"KEYWORD",EOF:"EOF",ERROR:"ERROR",WS:"WS",NEWLINE:"NEWLINE",DATETIME_LITERAL:"DATETIME_LITERAL",DURATION:"DURATION",UNIT:"UNIT",ROLL:"ROLL",PI:"PI",E:"E",MOD:"MOD",AND_CONJ:"AND_CONJ",OF:"OF",INCREASE_BY:"INCREASE_BY",DECREASE_BY:"DECREASE_BY",OF_WHAT_IS:"OF_WHAT_IS",ON_WHAT_IS:"ON_WHAT_IS",OFF_WHAT_IS:"OFF_WHAT_IS",NOW:"NOW",TODAY:"TODAY",TOMORROW:"TOMORROW",YESTERDAY:"YESTERDAY",DURATION_DAY:"DURATION_DAY",DURATION_WEEK:"DURATION_WEEK",DURATION_MONTH:"DURATION_MONTH",DURATION_YEAR:"DURATION_YEAR",DURATION_HOUR:"DURATION_HOUR",DURATION_MINUTE:"DURATION_MINUTE",DURATION_SECOND:"DURATION_SECOND",FUNC:"FUNC",CONVERT:"CONVERT",TO:"TO",BEST:"BEST",NEXT:"NEXT",LAST:"LAST",UNTIL:"UNTIL",SINCE:"SINCE",BETWEEN:"BETWEEN",SPLIT:"SPLIT",SPLIT_WAYS:"SPLIT_WAYS",WAYS:"WAYS",PEOPLE:"PEOPLE",FROM:"FROM",INCREASE:"INCREASE",DECREASE:"DECREASE",UNICODE_MATH:"UNICODE_MATH",TIMES_BY:"TIMES_BY",MULTIPLY_BY:"MULTIPLY_BY",DIVIDE_BY:"DIVIDE_BY",NEQ:"NEQ",IN:"IN",BIT_XOR:"BIT_XOR",EQUALITY:"EQUALITY",GTE:"GTE",LTE:"LTE",LT:"LT",GT:"GT",LOGICAL_AND:"LOGICAL_AND",LOGICAL_OR:"LOGICAL_OR",OR:"OR",TRUE:"TRUE",FALSE:"FALSE",IF:"IF",THEN:"THEN",ELSE:"ELSE",AS:"AS",CONVERTER_NAME:"CONVERTER_NAME",ROUNDED:"ROUNDED",TO_NEAREST:"TO_NEAREST",DECIMAL_PLACES:"DECIMAL_PLACES",AVERAGE_OF:"AVERAGE_OF",MEDIAN_OF:"MEDIAN_OF",TOTAL_OF:"TOTAL_OF",COUNT_OF:"COUNT_OF",LARGER_OF:"LARGER_OF",SMALLER_OF:"SMALLER_OF",HALF_OF:"HALF_OF",MIDPOINT_BETWEEN:"MIDPOINT_BETWEEN",REMAINDER_OF:"REMAINDER_OF",NTH_ROOT:"NTH_ROOT",LOG_PHRASE:"LOG_PHRASE",LOG_BASE:"LOG_BASE",GCD_OF:"GCD_OF",LCM_OF:"LCM_OF",SQUARE_ROOT_OF:"SQUARE_ROOT_OF",CUBE_ROOT_OF:"CUBE_ROOT_OF",RANDOM_NUMBER:"RANDOM_NUMBER",IS_TO:"IS_TO",IS:"IS",PCT_ON:"PCT_ON",PCT_OFF:"PCT_OFF",PCT_UP:"PCT_UP",PCT_DOWN:"PCT_DOWN",OF_WHAT:"OF_WHAT",OFF_WHAT:"OFF_WHAT",ON_WHAT:"ON_WHAT",CLAMP:"CLAMP",MAP:"MAP",REDUCE:"REDUCE",SUM_FN:"SUM_FN",PROD_FN:"PROD_FN",EXPAND_FN:"EXPAND_FN",FACTOR_FN:"FACTOR_FN",SOLVE_FN:"SOLVE_FN",DER_FN:"DER_FN",INTEGRAL_FN:"INTEGRAL_FN",TAYLOR_FN:"TAYLOR_FN",JACOBIAN_FN:"JACOBIAN_FN",CONJ_FN:"CONJ_FN",RE_FN:"RE_FN",IM_FN:"IM_FN",CANCEL_FN:"CANCEL_FN",APART_FN:"APART_FN",IMAGINARY:"IMAGINARY",THEREFORE:"THEREFORE",TIME_IN:"TIME_IN",DATE_IN:"DATE_IN",TIME_DIFFERENCE_BETWEEN:"TIME_DIFFERENCE_BETWEEN",CITY_NAME:"CITY_NAME",BACKTICK_OPEN:"BACKTICK_OPEN",INLINE_SOLVE_START:"INLINE_SOLVE_START",COMMENT:"COMMENT",HEX_COLOUR:"HEX_COLOUR",TAG:"TAG",COLOUR_CALL:"COLOUR_CALL",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",FLOAT:"FLOAT",GLOBAL:"GLOBAL",OVER:"OVER",RATE_AT:"RATE_AT",AFTER:"AFTER",PRESENT_VALUE_OF:"PRESENT_VALUE_OF",ANNUAL_RETURN_ON:"ANNUAL_RETURN_ON",FOR_DURATION:"FOR_DURATION",COMPOUNDING:"COMPOUNDING",INVESTED:"INVESTED",RETURNED:"RETURNED",COMPOUND_INTEREST_ON:"COMPOUND_INTEREST_ON",INTEREST_ON:"INTEREST_ON",DAILY_REPAYMENT_ON:"DAILY_REPAYMENT_ON",MONTHLY_REPAYMENT_ON:"MONTHLY_REPAYMENT_ON",ANNUAL_REPAYMENT_ON:"ANNUAL_REPAYMENT_ON",TOTAL_REPAYMENT_ON:"TOTAL_REPAYMENT_ON",DAILY_LOAN_INTEREST_ON:"DAILY_LOAN_INTEREST_ON",MONTHLY_LOAN_INTEREST_ON:"MONTHLY_LOAN_INTEREST_ON",ANNUAL_LOAN_INTEREST_ON:"ANNUAL_LOAN_INTEREST_ON",TOTAL_LOAN_INTEREST_ON:"TOTAL_LOAN_INTEREST_ON",TAX_ON:"TAX_ON",TAX_OFF:"TAX_OFF",TAX_IN_PHRASE:"TAX_IN_PHRASE",WHAT_IS:"WHAT_IS",WHAT_WAS:"WHAT_WAS",VALUE_OF:"VALUE_OF",WORTH_IN:"WORTH_IN",SAVINGS_HOW_LONG:"SAVINGS_HOW_LONG",SAVINGS_HOW_MUCH:"SAVINGS_HOW_MUCH",ASSUMING:"ASSUMING",IN_YEAR_DOLLARS:"IN_YEAR_DOLLARS",INGREDIENT_NAME:"INGREDIENT_NAME",WORKDAYS_IN:"WORKDAYS_IN",WEEKDAY_ON:"WEEKDAY_ON",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",TO_DATE:"TO_DATE",TO_TIMESTAMP:"TO_TIMESTAMP",WEEKDAY_IN:"WEEKDAY_IN",MONTH_ON:"MONTH_ON",MONTH_IN:"MONTH_IN",WEEK_ON:"WEEK_ON",DAYS_IN_PERIOD:"DAYS_IN_PERIOD",IN_TWO_UNITS:"IN_TWO_UNITS",PER_UNIT:"PER_UNIT",AT_RATE:"AT_RATE",WEEK_IN:"WEEK_IN",BETWEEN_UNIT:"BETWEEN_UNIT",WORKDAYS_AFTER:"WORKDAYS_AFTER",WORKDAYS_BEFORE:"WORKDAYS_BEFORE",WORKDAYS_BETWEEN:"WORKDAYS_BETWEEN",IS_WEEKEND:"IS_WEEKEND",IS_WORKDAY:"IS_WORKDAY",VIDEO_TIMECODE:"VIDEO_TIMECODE",FRAME_COUNT:"FRAME_COUNT",AT:"AT",CURRENCY_SYMBOL:"CURRENCY_SYMBOL",PREV:"PREV",LINE_REF:"LINE_REF",SUM_RANGE_CALL:"SUM_RANGE_CALL",AVERAGE_RANGE_CALL:"AVERAGE_RANGE_CALL",TOTAL_ABOVE:"TOTAL_ABOVE",SUM_ABOVE:"SUM_ABOVE",AVERAGE_ABOVE:"AVERAGE_ABOVE",GOAL_SEEK:"GOAL_SEEK"},I=0,T=new Map,O=new Map;function A(E){let _=T.get(E);if(_!==void 0)return _;let N=I++;return T.set(E,N),O.set(N,E),N}function L(E){return A(E)}function S(E){return O.get(E)??`UNKNOWN_${E}`}function D(){for(let E of Object.values(R))A(E);}export{R as a,A as b,L as c,S as d,D as e};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var R={NUMBER:"NUMBER",BIGINT:"BIGINT",STRING:"STRING",IDENT:"IDENT",PLUS:"PLUS",MINUS:"MINUS",PLUS_EQUALS:"PLUS_EQUALS",MINUS_EQUALS:"MINUS_EQUALS",STAR:"STAR",SLASH:"SLASH",PLUS_MINUS:"PLUS_MINUS",CARET:"CARET",PERCENT:"PERCENT",LSHIFT:"LSHIFT",RSHIFT:"RSHIFT",URSHIFT:"URSHIFT",LPAREN:"LPAREN",RPAREN:"RPAREN",LBRACKET:"LBRACKET",RBRACKET:"RBRACKET",LBRACE:"LBRACE",RBRACE:"RBRACE",COMMA:"COMMA",DOT:"DOT",COLON:"COLON",SEMICOLON:"SEMICOLON",EQUALS:"EQUALS",DOLLAR:"DOLLAR",POUND:"POUND",EURO:"EURO",YEN:"YEN",RUBLE:"RUBLE",WON:"WON",QUESTION:"QUESTION",BANG:"BANG",BIT_AND:"BIT_AND",BIT_OR:"BIT_OR",BIT_NOT:"BIT_NOT",KEYWORD:"KEYWORD",EOF:"EOF",ERROR:"ERROR",WS:"WS",NEWLINE:"NEWLINE",DATETIME_LITERAL:"DATETIME_LITERAL",DURATION:"DURATION",UNIT:"UNIT",ROLL:"ROLL",PI:"PI",E:"E",MOD:"MOD",AND_CONJ:"AND_CONJ",OF:"OF",INCREASE_BY:"INCREASE_BY",DECREASE_BY:"DECREASE_BY",OF_WHAT_IS:"OF_WHAT_IS",ON_WHAT_IS:"ON_WHAT_IS",OFF_WHAT_IS:"OFF_WHAT_IS",NOW:"NOW",TODAY:"TODAY",TOMORROW:"TOMORROW",YESTERDAY:"YESTERDAY",DURATION_DAY:"DURATION_DAY",DURATION_WEEK:"DURATION_WEEK",DURATION_MONTH:"DURATION_MONTH",DURATION_YEAR:"DURATION_YEAR",DURATION_HOUR:"DURATION_HOUR",DURATION_MINUTE:"DURATION_MINUTE",DURATION_SECOND:"DURATION_SECOND",FUNC:"FUNC",CONVERT:"CONVERT",TO:"TO",BEST:"BEST",NEXT:"NEXT",LAST:"LAST",UNTIL:"UNTIL",SINCE:"SINCE",BETWEEN:"BETWEEN",SPLIT:"SPLIT",SPLIT_WAYS:"SPLIT_WAYS",WAYS:"WAYS",PEOPLE:"PEOPLE",FROM:"FROM",INCREASE:"INCREASE",DECREASE:"DECREASE",UNICODE_MATH:"UNICODE_MATH",TIMES_BY:"TIMES_BY",MULTIPLY_BY:"MULTIPLY_BY",DIVIDE_BY:"DIVIDE_BY",NEQ:"NEQ",IN:"IN",BIT_XOR:"BIT_XOR",EQUALITY:"EQUALITY",GTE:"GTE",LTE:"LTE",LT:"LT",GT:"GT",LOGICAL_AND:"LOGICAL_AND",LOGICAL_OR:"LOGICAL_OR",OR:"OR",TRUE:"TRUE",FALSE:"FALSE",IF:"IF",THEN:"THEN",ELSE:"ELSE",AS:"AS",CONVERTER_NAME:"CONVERTER_NAME",ROUNDED:"ROUNDED",TO_NEAREST:"TO_NEAREST",DECIMAL_PLACES:"DECIMAL_PLACES",AVERAGE_OF:"AVERAGE_OF",MEDIAN_OF:"MEDIAN_OF",TOTAL_OF:"TOTAL_OF",COUNT_OF:"COUNT_OF",LARGER_OF:"LARGER_OF",SMALLER_OF:"SMALLER_OF",HALF_OF:"HALF_OF",MIDPOINT_BETWEEN:"MIDPOINT_BETWEEN",REMAINDER_OF:"REMAINDER_OF",NTH_ROOT:"NTH_ROOT",LOG_PHRASE:"LOG_PHRASE",LOG_BASE:"LOG_BASE",GCD_OF:"GCD_OF",LCM_OF:"LCM_OF",SQUARE_ROOT_OF:"SQUARE_ROOT_OF",CUBE_ROOT_OF:"CUBE_ROOT_OF",RANDOM_NUMBER:"RANDOM_NUMBER",IS_TO:"IS_TO",IS:"IS",PCT_ON:"PCT_ON",PCT_OFF:"PCT_OFF",PCT_UP:"PCT_UP",PCT_DOWN:"PCT_DOWN",OF_WHAT:"OF_WHAT",OFF_WHAT:"OFF_WHAT",ON_WHAT:"ON_WHAT",CLAMP:"CLAMP",MAP:"MAP",REDUCE:"REDUCE",SUM_FN:"SUM_FN",PROD_FN:"PROD_FN",EXPAND_FN:"EXPAND_FN",FACTOR_FN:"FACTOR_FN",SOLVE_FN:"SOLVE_FN",DER_FN:"DER_FN",INTEGRAL_FN:"INTEGRAL_FN",TAYLOR_FN:"TAYLOR_FN",JACOBIAN_FN:"JACOBIAN_FN",CONJ_FN:"CONJ_FN",RE_FN:"RE_FN",IM_FN:"IM_FN",CANCEL_FN:"CANCEL_FN",APART_FN:"APART_FN",IMAGINARY:"IMAGINARY",THEREFORE:"THEREFORE",TIME_IN:"TIME_IN",DATE_IN:"DATE_IN",TIME_DIFFERENCE_BETWEEN:"TIME_DIFFERENCE_BETWEEN",CITY_NAME:"CITY_NAME",BACKTICK_OPEN:"BACKTICK_OPEN",INLINE_SOLVE_START:"INLINE_SOLVE_START",COMMENT:"COMMENT",HEX_COLOUR:"HEX_COLOUR",TAG:"TAG",COLOUR_CALL:"COLOUR_CALL",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",FLOAT:"FLOAT",GLOBAL:"GLOBAL",OVER:"OVER",RATE_AT:"RATE_AT",AFTER:"AFTER",PRESENT_VALUE_OF:"PRESENT_VALUE_OF",ANNUAL_RETURN_ON:"ANNUAL_RETURN_ON",FOR_DURATION:"FOR_DURATION",COMPOUNDING:"COMPOUNDING",INVESTED:"INVESTED",RETURNED:"RETURNED",COMPOUND_INTEREST_ON:"COMPOUND_INTEREST_ON",INTEREST_ON:"INTEREST_ON",DAILY_REPAYMENT_ON:"DAILY_REPAYMENT_ON",MONTHLY_REPAYMENT_ON:"MONTHLY_REPAYMENT_ON",ANNUAL_REPAYMENT_ON:"ANNUAL_REPAYMENT_ON",TOTAL_REPAYMENT_ON:"TOTAL_REPAYMENT_ON",DAILY_LOAN_INTEREST_ON:"DAILY_LOAN_INTEREST_ON",MONTHLY_LOAN_INTEREST_ON:"MONTHLY_LOAN_INTEREST_ON",ANNUAL_LOAN_INTEREST_ON:"ANNUAL_LOAN_INTEREST_ON",TOTAL_LOAN_INTEREST_ON:"TOTAL_LOAN_INTEREST_ON",TAX_ON:"TAX_ON",TAX_OFF:"TAX_OFF",TAX_IN_PHRASE:"TAX_IN_PHRASE",WHAT_IS:"WHAT_IS",WHAT_WAS:"WHAT_WAS",VALUE_OF:"VALUE_OF",WORTH_IN:"WORTH_IN",SAVINGS_HOW_LONG:"SAVINGS_HOW_LONG",SAVINGS_HOW_MUCH:"SAVINGS_HOW_MUCH",ASSUMING:"ASSUMING",IN_YEAR_DOLLARS:"IN_YEAR_DOLLARS",INGREDIENT_NAME:"INGREDIENT_NAME",WORKDAYS_IN:"WORKDAYS_IN",WEEKDAY_ON:"WEEKDAY_ON",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",TO_DATE:"TO_DATE",TO_TIMESTAMP:"TO_TIMESTAMP",WEEKDAY_IN:"WEEKDAY_IN",MONTH_ON:"MONTH_ON",MONTH_IN:"MONTH_IN",WEEK_ON:"WEEK_ON",DAYS_IN_PERIOD:"DAYS_IN_PERIOD",IN_TWO_UNITS:"IN_TWO_UNITS",PER_UNIT:"PER_UNIT",AT_RATE:"AT_RATE",WEEK_IN:"WEEK_IN",BETWEEN_UNIT:"BETWEEN_UNIT",WORKDAYS_AFTER:"WORKDAYS_AFTER",WORKDAYS_BEFORE:"WORKDAYS_BEFORE",WORKDAYS_BETWEEN:"WORKDAYS_BETWEEN",IS_WEEKEND:"IS_WEEKEND",IS_WORKDAY:"IS_WORKDAY",VIDEO_TIMECODE:"VIDEO_TIMECODE",FRAME_COUNT:"FRAME_COUNT",AT:"AT",CURRENCY_SYMBOL:"CURRENCY_SYMBOL",PREV:"PREV",LINE_REF:"LINE_REF",SUM_RANGE_CALL:"SUM_RANGE_CALL",AVERAGE_RANGE_CALL:"AVERAGE_RANGE_CALL",TOTAL_ABOVE:"TOTAL_ABOVE",SUM_ABOVE:"SUM_ABOVE",AVERAGE_ABOVE:"AVERAGE_ABOVE",GOAL_SEEK:"GOAL_SEEK"},I=0,T=new Map,O=new Map;function A(E){let _=T.get(E);if(_!==void 0)return _;let N=I++;return T.set(E,N),O.set(N,E),N}function L(E){return A(E)}function S(E){return O.get(E)??`UNKNOWN_${E}`}function D(){for(let E of Object.values(R))A(E);}export{R as a,A as b,L as c,S as d,D as e};//# sourceMappingURL=chunk-FAO6DQ74.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-FAO6DQ74.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lexer/Token.ts"],"names":["TokenTypes","_nextTokenTypeId","_tokenTypeNameToId","_tokenTypeIdToName","registerTokenType","name","existing","id","tokenTypeId","tokenTypeName","registerAllTokenTypes"],"mappings":"AAyDO,IAAMA,CAAAA,CAAa,CACxB,MAAA,CAAQ,QAAA,CACR,MAAA,CAAQ,QAAA,CACR,MAAA,CAAQ,QAAA,CACR,KAAA,CAAO,OAAA,CACP,IAAA,CAAM,MAAA,CACN,KAAA,CAAO,OAAA,CAGP,WAAA,CAAa,aAAA,CACb,YA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A,CAOZ,cAAA,CAAgB,gBAAA,CAChB,WAAA,CAAa,aAAA,CAIb,EAAA,CAAI,IAAA,CAQJ,eAAA,CAAiB,iBAAA,CAIjB,IAAA,CAAM,MAAA,CAIN,QAAA,CAAU,WAIV,cAAA,CAAgB,gBAAA,CAChB,kBAAA,CAAoB,oBAAA,CAKpB,WAAA,CAAa,aAAA,CACb,SAAA,CAAW,WAAA,CACX,aAAA,CAAe,eAAA,CAMf,SAAA,CAAW,WACb,CAAA,CAcIC,CAAAA,CAAmB,CAAA,CAGjBC,CAAAA,CAAqB,IAAI,GAAA,CAGzBC,CAAAA,CAAqB,IAAI,IAOxB,SAASC,CAAAA,CAAkBC,CAAAA,CAAsB,CACvD,IAAMC,CAAAA,CAAWJ,CAAAA,CAAmB,GAAA,CAAIG,CAAI,CAAA,CAC5C,GAAIC,CAAAA,GAAa,OAAW,OAAOA,CAAAA,CACnC,IAAMC,CAAAA,CAAKN,CAAAA,EAAAA,CACX,OAAAC,CAAAA,CAAmB,GAAA,CAAIG,CAAAA,CAAME,CAAE,CAAA,CAC/BJ,CAAAA,CAAmB,GAAA,CAAII,CAAAA,CAAIF,CAAI,CAAA,CACxBE,CACR,CAQO,SAASC,CAAAA,CAAYH,CAAAA,CAAsB,CACjD,OAAOD,CAAAA,CAAkBC,CAAI,CAC9B,CAMO,SAASI,CAAAA,CAAcF,CAAAA,CAAoB,CACjD,OAAOJ,CAAAA,CAAmB,IAAII,CAAE,CAAA,EAAK,CAAA,QAAA,EAAWA,CAAE,CAAA,CACnD,CAMO,SAASG,CAAAA,EAA8B,CAC7C,IAAA,IAAWL,CAAAA,IAAQ,MAAA,CAAO,MAAA,CAAOL,CAAU,CAAA,CAC1CI,CAAAA,CAAkBC,CAAI,EAExB","file":"chunk-FAO6DQ74.js","sourcesContent":["/**\n * Lexer token produced by {@link ExpressionLexer} and consumed by parsers.\n *\n * Each token carries:\n * - `type`: string name (e.g. \"NUMBER\", \"PLUS\") for diagnostics and parselet lookup\n * - `typeId`: integer ID for O(1) comparison in parser hot paths\n * - `value`/`text`: the token's semantic value and raw source text\n * - `offset`/`line`/`col`: source position for error messages and highlighting\n */\nexport interface Token {\n\t/** String token type (e.g., \"NUMBER\", \"PLUS\", \"IDENT\"). Used by ParseletRegistry string-keyed maps and error messages. */\n\ttype: string;\n\t/** Integer token type ID for fast comparison in Parser hot path.\n\t * Populated by the Lexer via registerTokenType(). Use tokenTypeId(type) to get a type's ID. */\n\ttypeId: number;\n\tvalue: string;\n\ttext: string;\n\toffset: number;\n\tlineBreaks: number;\n\tline: number;\n\tcol: number;\n\t/**\n\t * End offset of the source text this token was fused from, exclusive.\n\t *\n\t * Only set on tokens the normalizer built by fusing several lexer tokens\n\t * into one, and only there because those are the tokens whose `value` no\n\t * longer describes the text they came from. `10 frames` fuses into a\n\t * FRAME_COUNT whose value is `10`, so `offset + value.length` would cover\n\t * two characters of a nine-character phrase.\n\t *\n\t * Evaluation never reads this. It exists so that a consumer painting a line\n\t * (see `LanguageService.getSemanticTokens`) can highlight a fused phrase as\n\t * the one thing the parser will see rather than as its parts.\n\t */\n\tsourceEnd?: number;\n\n\t/**\n\t * Why a fused token stands for something the engine refuses to read, when\n\t * it does.\n\t *\n\t * Set by a normaliser rule that has decided a run is not what it is spelled\n\t * like and will not be read as arithmetic either: a date literal naming no\n\t * real day. The parselet for the fused type turns it into an Error value.\n\t *\n\t * Carried here rather than packed into `value`, because `value` is what a\n\t * parse error and the editor's per-keystroke token API print, and a reader\n\t * shown `{\"code\":\"...\",\"message\":\"...\"}` is being shown the engine's\n\t * internals. `value` stays the text the reader typed.\n\t */\n\tfault?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Canonical token type name constants.\n * All token types used by the lexer, parser, and VM are defined here.\n * Custom/plugin token types should be registered via {@link registerTokenType}.\n */\nexport const TokenTypes = {\n NUMBER: \"NUMBER\",\n BIGINT: \"BIGINT\",\n STRING: \"STRING\",\n IDENT: \"IDENT\",\n PLUS: \"PLUS\",\n MINUS: \"MINUS\",\n // Compound assignment for running totals: `total += 100`, `total -= 40`.\n // Handled by the engine's compound-assignment interception, not a parselet.\n PLUS_EQUALS: \"PLUS_EQUALS\",\n MINUS_EQUALS: \"MINUS_EQUALS\",\n STAR: \"STAR\",\n SLASH: \"SLASH\",\n // The uncertainty operator, `±` (U+00B1) or the ASCII `+/-`. The symbol is\n // lexed directly (ExpressionLexer.ts, alongside `×`/`÷`), and the ASCII\n // spelling is fused from PLUS SLASH MINUS by a normalizer rule (see\n // packages/uncertainty/). Registered here rather than left to be lazily\n // minted so its id is stable, the same reasoning as the algebra verbs below.\n PLUS_MINUS: \"PLUS_MINUS\",\n CARET: \"CARET\",\n PERCENT: \"PERCENT\",\n LSHIFT: \"LSHIFT\",\n RSHIFT: \"RSHIFT\",\n URSHIFT: \"URSHIFT\",\n LPAREN: \"LPAREN\",\n RPAREN: \"RPAREN\",\n LBRACKET: \"LBRACKET\",\n RBRACKET: \"RBRACKET\",\n LBRACE: \"LBRACE\",\n RBRACE: \"RBRACE\",\n COMMA: \"COMMA\",\n DOT: \"DOT\",\n COLON: \"COLON\",\n SEMICOLON: \"SEMICOLON\",\n EQUALS: \"EQUALS\",\n DOLLAR: \"DOLLAR\",\n POUND: \"POUND\",\n EURO: \"EURO\",\n YEN: \"YEN\",\n RUBLE: \"RUBLE\",\n WON: \"WON\",\n QUESTION: \"QUESTION\",\n BANG: \"BANG\",\n BIT_AND: \"BIT_AND\",\n BIT_OR: \"BIT_OR\",\n BIT_NOT: \"BIT_NOT\",\n KEYWORD: \"KEYWORD\",\n EOF: \"EOF\",\n ERROR: \"ERROR\",\n WS: \"WS\",\n NEWLINE: \"NEWLINE\",\n DATETIME_LITERAL: \"DATETIME_LITERAL\",\n DURATION: \"DURATION\",\n UNIT: \"UNIT\",\n ROLL: \"ROLL\",\n PI: \"PI\",\n E: \"E\",\n MOD: \"MOD\",\n // The English word \"and\", which is NOT the same thing as \"+\" even though it\n // adds. It used to map straight onto PLUS in the locale keyword map, which\n // made \"3 and 4\" evaluate to 7 correctly and then quietly broke every phrase\n // that uses \"and\" as a list separator: \"average of 36, 42, 19 and 81\" parsed\n // its last argument as \"19 + 81\" and returned 178/3 rather than 178/4.\n //\n // Giving it its own type lets a parselet tell the two apart. It is still an\n // infix addition (see ArithmeticPackage.ts) so \"3 and 4\" is unchanged, but it\n // binds at BindingPower.Conjunction, looser than both Sum and Conditional, so\n // a phrase parselet can parse an argument at Conjunction and get \"1 + 2\"\n // whole while still stopping at \"and\", and so \"5 > 3 and 2 > 1\" reads as the\n // conjunction of two comparisons rather than \"5 > (3 and 2) > 1\".\n AND_CONJ: \"AND_CONJ\",\n OF: \"OF\",\n INCREASE_BY: \"INCREASE_BY\",\n DECREASE_BY: \"DECREASE_BY\",\n // Percentage solve-for-unknown (packages/percentage/), \"N% of what is\n // X\" solves N% * base = X for base. Fused as a full 3-word phrase (see\n // PercentagePackage.ts's `phrases` field) rather than a bare \"what\"\n // keyword, \"what\" is common enough as a variable name to be worth the\n // same phrase-fusion treatment this codebase gives \"total\"/\"average\"/etc.\n OF_WHAT_IS: \"OF_WHAT_IS\",\n // Sibling solve-for-unknown forms accounting for a +/-1 offset, \"N% on\n // what is X\" (increase) / \"N% off what is X\" (decrease). Same\n // phrase-fusion reasoning as OF_WHAT_IS above.\n ON_WHAT_IS: \"ON_WHAT_IS\",\n OFF_WHAT_IS: \"OFF_WHAT_IS\",\n NOW: \"NOW\",\n TODAY: \"TODAY\",\n TOMORROW: \"TOMORROW\",\n YESTERDAY: \"YESTERDAY\",\n DURATION_DAY: \"DURATION_DAY\",\n DURATION_WEEK: \"DURATION_WEEK\",\n DURATION_MONTH: \"DURATION_MONTH\",\n DURATION_YEAR: \"DURATION_YEAR\",\n DURATION_HOUR: \"DURATION_HOUR\",\n DURATION_MINUTE: \"DURATION_MINUTE\",\n DURATION_SECOND: \"DURATION_SECOND\",\n FUNC: \"FUNC\",\n CONVERT: \"CONVERT\",\n TO: \"TO\",\n BEST: \"BEST\",\n NEXT: \"NEXT\",\n LAST: \"LAST\",\n UNTIL: \"UNTIL\",\n SINCE: \"SINCE\",\n BETWEEN: \"BETWEEN\",\n // Bill split (finance package). Retyped from the ordinary words \"split\",\n // \"ways\" and \"people\" by BillSplitNormalizerRule, but only inside the full\n // split shape, so those words stay usable as variable names and prose\n // everywhere else (the same contextual-claim discipline as the recurring\n // schedule and at-rate rules).\n // The verb-first `split <amount> between N` form (prefix).\n SPLIT: \"SPLIT\",\n // The amount-first `<amount> split N ways` form (infix). A separate,\n // infix-only token so implicit multiplication does not read it as the start\n // of a new value and insert a `*` before it, which the dual-role SPLIT would.\n SPLIT_WAYS: \"SPLIT_WAYS\",\n WAYS: \"WAYS\",\n PEOPLE: \"PEOPLE\",\n FROM: \"FROM\",\n INCREASE: \"INCREASE\",\n DECREASE: \"DECREASE\",\n UNICODE_MATH: \"UNICODE_MATH\",\n TIMES_BY: \"TIMES_BY\",\n MULTIPLY_BY: \"MULTIPLY_BY\",\n DIVIDE_BY: \"DIVIDE_BY\",\n NEQ: \"NEQ\",\n IN: \"IN\",\n BIT_XOR: \"BIT_XOR\",\n EQUALITY: \"EQUALITY\",\n GTE: \"GTE\",\n LTE: \"LTE\",\n LT: \"LT\",\n GT: \"GT\",\n LOGICAL_AND: \"LOGICAL_AND\",\n LOGICAL_OR: \"LOGICAL_OR\",\n OR: \"OR\",\n TRUE: \"TRUE\",\n FALSE: \"FALSE\",\n IF: \"IF\",\n THEN: \"THEN\",\n ELSE: \"ELSE\",\n AS: \"AS\",\n CONVERTER_NAME: \"CONVERTER_NAME\",\n // Rounding (packages/converters/). \"rounded\" is a bare keyword: it is a\n // past participle with no plausible use as a :variableName, the same\n // accepted-risk category as \"between\"/\"from\". TO_NEAREST and\n // DECIMAL_PLACES are fused, since \"to\" already means percentage change.\n ROUNDED: \"ROUNDED\",\n TO_NEAREST: \"TO_NEAREST\",\n DECIMAL_PLACES: \"DECIMAL_PLACES\",\n // Fused two-word phrase tokens (see MathPhrasesPackage.ts's `phrases`\n // field), deliberately NOT bare single-word keywords: \"average\"\n // \"total\", \"count\", etc. are common variable names, and this codebase\n // has a tested policy that colon-prefixed variable names can't be\n // keyword-shaped words (see VariableParselet.ts's doc comment). Fusing\n // the full \"<word> of\"/\"<word> between\" phrase means the bare word\n // itself never becomes its own token type, so \":total = ...\" keeps\n // working exactly as before.\n AVERAGE_OF: \"AVERAGE_OF\",\n MEDIAN_OF: \"MEDIAN_OF\",\n TOTAL_OF: \"TOTAL_OF\",\n COUNT_OF: \"COUNT_OF\",\n LARGER_OF: \"LARGER_OF\",\n SMALLER_OF: \"SMALLER_OF\",\n HALF_OF: \"HALF_OF\",\n MIDPOINT_BETWEEN: \"MIDPOINT_BETWEEN\",\n REMAINDER_OF: \"REMAINDER_OF\",\n NTH_ROOT: \"NTH_ROOT\",\n LOG_PHRASE: \"LOG_PHRASE\",\n LOG_BASE: \"LOG_BASE\",\n GCD_OF: \"GCD_OF\",\n LCM_OF: \"LCM_OF\",\n SQUARE_ROOT_OF: \"SQUARE_ROOT_OF\",\n CUBE_ROOT_OF: \"CUBE_ROOT_OF\",\n RANDOM_NUMBER: \"RANDOM_NUMBER\",\n IS_TO: \"IS_TO\",\n // Bare \"is\", the trigger for the solve-for-the-unknown percentage family\n // (packages/percentage/IsWhatParselet.ts). Safe as a bare keyword: it is a\n // verb, not a plausible :variableName, and the \"is to\" proportion phrase is\n // fused earlier so it still wins.\n IS: \"IS\",\n PCT_ON: \"PCT_ON\",\n PCT_OFF: \"PCT_OFF\",\n // Successive percentage change (packages/percentage/UpDownParselet.ts):\n // `X up N%` grows, `X down N%` shrinks, chainable with `then` and\n // repeatable with `N times`. Retyped from a bare `up`/`down` IDENT only\n // when a percentage immediately follows (PercentUpDownNormalizerRule), so\n // prose that merely mentions the words is untouched. Declared here rather\n // than minted lazily for the same reason as the algebra verbs below: a\n // normalizer rule and its parselet must agree on the id.\n PCT_UP: \"PCT_UP\",\n PCT_DOWN: \"PCT_DOWN\",\n OF_WHAT: \"OF_WHAT\",\n OFF_WHAT: \"OFF_WHAT\",\n ON_WHAT: \"ON_WHAT\",\n // CLAMP stays a bare single-word keyword: \"clamp X between Y and Z\" has\n // the value X between the trigger and \"between\", so it can't be\n // phrase-fused like the others above (same structural reason\n // ClampParselet.ts is hand-written instead of PhrasePattern-based).\n // Matches this codebase's existing accepted risk for \"between\"/\"from\"/\n // \"next\"/\"last\"/\"best\", also bare, also can't be used as `:name`.\n CLAMP: \"CLAMP\",\n // map/reduce/sum/prod (packages/mapreduce/), bare single-word keywords\n // each with its own dedicated parselet (custom argument grammar: a bare\n // builtin/user-function name, an inline transform expression, or\n // `name=collection` zipped pairs, none of which fit the ordinary\n // FunctionCallParselet path, so these can't just reuse the generic FUNC\n // token type the way sqrt/abs/... do).\n MAP: \"MAP\",\n REDUCE: \"REDUCE\",\n SUM_FN: \"SUM_FN\",\n PROD_FN: \"PROD_FN\",\n // The algebra verbs (packages/symbolic/), fused from an ordinary IDENT only\n // when immediately followed by `(`, so `factor`/`solve`/`expand` stay usable\n // as variable names. Declared here rather than left to be minted on first use\n // by `tokenTypeId()`, which is what {@link registerAllTokenTypes} exists for:\n // a lazily-minted id depends on what else happened to be minted before it, so\n // in a single-process run the id a normalizer rule produces can stop matching\n // the id the parselet was registered under. Every token type a built-in\n // package relies on belongs in this table.\n EXPAND_FN: \"EXPAND_FN\",\n FACTOR_FN: \"FACTOR_FN\",\n SOLVE_FN: \"SOLVE_FN\",\n DER_FN: \"DER_FN\",\n INTEGRAL_FN: \"INTEGRAL_FN\",\n TAYLOR_FN: \"TAYLOR_FN\",\n JACOBIAN_FN: \"JACOBIAN_FN\",\n CONJ_FN: \"CONJ_FN\",\n RE_FN: \"RE_FN\",\n IM_FN: \"IM_FN\",\n CANCEL_FN: \"CANCEL_FN\",\n APART_FN: \"APART_FN\",\n // The imaginary-literal suffix, fused from a number followed immediately by\n // `i`. Same registration reasoning as the verbs above.\n IMAGINARY: \"IMAGINARY\",\n // `=>`, \"therefore\"/solve operator. The algebra itself lives in symbolic/;\n // packages/symbolic/ carries the grammar surface for the named operations.\n // A genuine 2-char lexer token (ExpressionLexer.ts's TWO_CHAR_OPS table),\n // same mechanism as ==/!=/>=/<=, not a normalizer-level fusion, \"=\" then\n // \">\" is the opposite char order from GTE's \">=\", so there's no collision.\n THEREFORE: \"THEREFORE\",\n // Timezone query phrases (see TimePackage.ts's `phrases` field). Same\n // phrase-fusion reasoning as above: \"time\"/\"date\"/\"difference\" are\n // common variable names, so the fused trigger is the full phrase.\n // CITY_NAME is the fused-token type for multi-word city/country names\n // (e.g. \"new york\"). See timezones/CityZones.ts's MULTI_WORD_CITY_ZONES.\n TIME_IN: \"TIME_IN\",\n DATE_IN: \"DATE_IN\",\n TIME_DIFFERENCE_BETWEEN: \"TIME_DIFFERENCE_BETWEEN\",\n CITY_NAME: \"CITY_NAME\",\n BACKTICK_OPEN: \"BACKTICK_OPEN\",\n INLINE_SOLVE_START: \"INLINE_SOLVE_START\",\n // Comment marker, `#` or `//` to end of line. Emitted by\n // ExpressionLexer.tokenizeComment()/tokenizeOperator() but never reaches\n // a parselet: ExpressionEngine.prepareExpression() filters COMMENT\n // tokens out of the stream before normalization/parsing (see\n // ExpressionEngine.ts's \"Filter COMMENT tokens\" comments). Listed here\n // for discoverability even though tokenTypeId() would lazily register\n // it anyway on first use.\n COMMENT: \"COMMENT\",\n // A `#hex` colour literal (`#ff0000`), recognised by the lexer where `#`\n // would otherwise be a heading/comment; the colour package's parselet turns\n // it into a colour value. See ExpressionLexer.matchHexColourEnd().\n HEX_COLOUR: \"HEX_COLOUR\",\n // A bounded mid-line `#tag` annotation (`1200 #housing`). Stripped from\n // evaluation by the tags package's strip rule, or consumed by its aggregate\n // rule (`total of #housing`). A line-start `#` is a heading, and `# ` (space)\n // or `//` is still a free-text comment.\n TAG: \"TAG\",\n // A colour function call fused by the colour package's normalizer, e.g.\n // `rgb(`/`lighten(`. Carries the function name; see ColourCallParselet.\n COLOUR_CALL: \"COLOUR_CALL\",\n // Vector types (referenced in locale keywordMap as vec2→VEC2, etc.)\n VEC2: \"VEC2\",\n VEC3: \"VEC3\",\n VEC4: \"VEC4\",\n FLOAT: \"FLOAT\",\n GLOBAL: \"GLOBAL\",\n // ── Finance (packages/finance/) ──\n // OVER/RATE_AT are bare single-word keywords (not phrase-fused): both are\n // prepositions with near-zero plausibility as a variable name (nobody\n // writes \":over = 5\" or \":at = 3\"), the same accepted-risk category as\n // this codebase's existing bare \"between\"/\"from\"/\"next\"/\"last\"/\"best\"\n // keywords (see VariableParselet.ts's doc comment). RATE_AT is deliberately\n // NOT named \"AT\", that name is already reserved (dormant) for a future\n // \"@\" symbol token in TokenNormalizer.NON_WORD_NAMES; reusing it here would\n // create an unintended coupling if \"@\" is ever wired up.\n OVER: \"OVER\",\n RATE_AT: \"RATE_AT\",\n // The investment grammar's connectives (packages/finance/), same\n // accepted-risk category as OVER/RATE_AT above. \"after\"/\"for\" are\n // prepositions; \"compounding\", \"invested\" and \"returned\" are participles,\n // and none is a plausible `:variableName`.\n //\n // \"after\" and \"for\" are the pivots Soulver's own documented syntax uses,\n // `$1,000 after 3 years at 7%` and `$1,000 for 3 years at 7% compounding\n // monthly`. This package originally substituted \"over\" for both and said so\n // in CompoundInterestParselet.ts's doc comment; the documented spellings now\n // work as well, and \"over\" is kept so nothing that already parsed stops.\n AFTER: \"AFTER\",\n PRESENT_VALUE_OF: \"PRESENT_VALUE_OF\",\n ANNUAL_RETURN_ON: \"ANNUAL_RETURN_ON\",\n FOR_DURATION: \"FOR_DURATION\",\n COMPOUNDING: \"COMPOUNDING\",\n INVESTED: \"INVESTED\",\n RETURNED: \"RETURNED\",\n // Fused phrase tokens (see FinancePackage.ts's `phrases` field)\n // deliberately NOT bare single-word keywords: \"interest\", \"tax\", \"vat\",\n // \"repayment\", \"principal\" etc. are all common, plausible variable names\n // (a shipped playground example uses \":total = :subtotal + :tax\". See\n // MathPhrasesPackage.ts's doc comment for the regression this caused\n // once already). Fusing the full \"<word> on\"/\"<word> off\" phrase means\n // the bare leading word itself never becomes its own token type, so\n // \":tax = ...\" keeps working exactly as before.\n COMPOUND_INTEREST_ON: \"COMPOUND_INTEREST_ON\",\n INTEREST_ON: \"INTEREST_ON\",\n DAILY_REPAYMENT_ON: \"DAILY_REPAYMENT_ON\",\n MONTHLY_REPAYMENT_ON: \"MONTHLY_REPAYMENT_ON\",\n ANNUAL_REPAYMENT_ON: \"ANNUAL_REPAYMENT_ON\",\n TOTAL_REPAYMENT_ON: \"TOTAL_REPAYMENT_ON\",\n DAILY_LOAN_INTEREST_ON: \"DAILY_LOAN_INTEREST_ON\",\n MONTHLY_LOAN_INTEREST_ON: \"MONTHLY_LOAN_INTEREST_ON\",\n ANNUAL_LOAN_INTEREST_ON: \"ANNUAL_LOAN_INTEREST_ON\",\n TOTAL_LOAN_INTEREST_ON: \"TOTAL_LOAN_INTEREST_ON\",\n TAX_ON: \"TAX_ON\",\n TAX_OFF: \"TAX_OFF\",\n TAX_IN_PHRASE: \"TAX_IN_PHRASE\",\n // Inflation-adjusted value (packages/finance/) -- fused phrase\n // tokens (see FinancePackage.ts's `phrases` field), same reasoning\n // as the tax/interest phrases above: \"what\"/\"was\"/\"value\"/\"worth\"\n // are all plausible variable names, so only the full phrases are\n // ever claimed as keywords, never the bare leading word.\n WHAT_IS: \"WHAT_IS\",\n WHAT_WAS: \"WHAT_WAS\",\n VALUE_OF: \"VALUE_OF\",\n WORTH_IN: \"WORTH_IN\",\n // Savings goals (finance). Fused whole-phrase triggers, so \"how\", \"much\",\n // \"save\" and \"reach\" stay ordinary variable names, the same reason as the\n // other finance phrases above.\n SAVINGS_HOW_LONG: \"SAVINGS_HOW_LONG\",\n SAVINGS_HOW_MUCH: \"SAVINGS_HOW_MUCH\",\n // Bare single-word keyword (not phrase-fused) -- \"assuming\" has\n // near-zero plausibility as a variable name, the same accepted-risk\n // category as this codebase's existing bare \"over\"/\"at\" keywords\n // (see the OVER/RATE_AT comment above). Registered so its bare word\n // is a recognized phrase-starter (`canStartPhrase`), which suppresses\n // implicit-multiply insertion between the futureYear NUMBER and this\n // word in \"value of $X in <year> assuming N% inflation\" -- without\n // this, \"<year> assuming\" was silently rewritten to \"<year> *\n // assuming\" before parsing ever ran.\n ASSUMING: \"ASSUMING\",\n // Fused by a custom NormalizerRule (not `phrases`), carrying the\n // year as its value -- see\n // finance/normalizer/InYearDollarsNormalizerRule.ts.\n IN_YEAR_DOLLARS: \"IN_YEAR_DOLLARS\",\n // Cooking/UoM (packages/uom/) -- fused ingredient name (single- or\n // multi-word, e.g. \"butter\"/\"olive oil\") carrying the matched name\n // as its value. NOT a bare-word phrase-trie keyword -- see\n // uom/normalizer/IngredientNameNormalizerRule.ts's doc comment for\n // why this is a context-sensitive NormalizerRule instead (so a bare\n // `:butter = 5` variable definition is completely unaffected).\n INGREDIENT_NAME: \"INGREDIENT_NAME\",\n // ── Datetime, workdays/weekdays/timestamps (packages/datetime/) ──\n // Fused phrase tokens (see DatetimePackage.ts's `phrases` field)\n // deliberately NOT bare single-word keywords: \"workdays\"/\"weekday\"/\n // \"timestamp\"/\"date\" are all plausible variable names, same\n // reasoning/regression risk as MathPhrasesPackage.ts's \"total\" note and\n // FinancePackage.ts's \"tax\" note above. Fusing the full phrase means the\n // bare leading word itself never becomes its own token type, so e.g.\n // \":timestamp = 5\" keeps working.\n WORKDAYS_IN: \"WORKDAYS_IN\",\n WEEKDAY_ON: \"WEEKDAY_ON\",\n CURRENT_TIMESTAMP: \"CURRENT_TIMESTAMP\",\n TO_DATE: \"TO_DATE\",\n TO_TIMESTAMP: \"TO_TIMESTAMP\",\n // Natural-question forms over the same date fields, \"what day is it in\n // 30 days\", \"what month is it on 25/12/2026\", \"what week is it\". Each is\n // a fully-fused phrase for the same reason as WEEKDAY_ON above: claiming\n // bare \"day\"/\"month\"/\"week\" as keywords would break \":day = 5\" and\n // collide with the UNIT tokens of the same name.\n WEEKDAY_IN: \"WEEKDAY_IN\",\n MONTH_ON: \"MONTH_ON\",\n MONTH_IN: \"MONTH_IN\",\n WEEK_ON: \"WEEK_ON\",\n DAYS_IN_PERIOD: \"DAYS_IN_PERIOD\",\n IN_TWO_UNITS: \"IN_TWO_UNITS\",\n PER_UNIT: \"PER_UNIT\",\n AT_RATE: \"AT_RATE\",\n WEEK_IN: \"WEEK_IN\",\n // `<unit> between <date> and <date>`, fused UNIT+BETWEEN, exactly like\n // UNTIL_UNIT/SINCE_UNIT above.\n BETWEEN_UNIT: \"BETWEEN_UNIT\",\n // Business-day arithmetic in words, \"N working/business days after|from|\n // before <date>\" (infix, the count is the left operand) and \"working/\n // business days between <date> and <date>\" (prefix). Full phrases for the\n // same reason as WORKDAYS_IN above: \"working\"/\"business\" are ordinary words,\n // so only the complete phrase is claimed, never the bare leading word. See\n // WorkdayOffsetParselet.ts / WorkdaysBetweenParselet.ts.\n WORKDAYS_AFTER: \"WORKDAYS_AFTER\",\n WORKDAYS_BEFORE: \"WORKDAYS_BEFORE\",\n WORKDAYS_BETWEEN: \"WORKDAYS_BETWEEN\",\n // Postfix day-type predicates, \"<date> is a weekend\" / \"is a workday\".\n IS_WEEKEND: \"IS_WEEKEND\",\n IS_WORKDAY: \"IS_WORKDAY\",\n // ── Time, video timecode (packages/time/) ──\n // Fused from a raw `HH:MM:SS:FF` token sequence (see\n // packages/time/normalizer/VideoTimecodeNormalizerRule.ts) and from\n // `NUMBER frames` (see FrameCountNormalizerRule.ts), not a bare-keyword\n // collision risk the way the datetime tokens above are, since neither\n // fusion claims a plain English word as its own token type.\n VIDEO_TIMECODE: \"VIDEO_TIMECODE\",\n FRAME_COUNT: \"FRAME_COUNT\",\n // \"@\". See ExpressionLexer.ts's OP_MAP entry for why this was\n // previously dormant/unproduced despite being anticipated by name here\n // and in TokenNormalizer.ts's NON_WORD_NAMES.\n AT: \"AT\",\n // Generic token for every currency symbol added AFTER the original\n // DOLLAR/POUND/EURO/YEN/RUBLE/WON set (each of which kept its own\n // specific token type for backward compatibility). See\n // uom/CurrencyAliases.ts's CURRENCY_SYMBOL_ALIASES and\n // ExpressionLexer.ts's dispatch for the full symbol list. One shared\n // type avoids needing a new TokenTypes entry + TokenCategoryMap entry +\n // CurrencyPackage.ts prefixParselets entry per additional symbol.\n CURRENCY_SYMBOL: \"CURRENCY_SYMBOL\",\n // ── Cross-line data access (packages/lines/) ──\n // \"prev\" -- bare keyword (nothing to phrase-fuse against, same shape as\n // CLAMP -- accepted collision risk per that package's own precedent).\n PREV: \"PREV\",\n // \"line1\" / \"line 1\" / \"l1\" -- fused by LineRefNormalizerRule (never a\n // bare lexer keyword, so \":line = 5\"/\":l = 5\" stay untouched). Carries\n // the parsed line number as its .value.\n LINE_REF: \"LINE_REF\",\n // \"sum(\" / \"total(\" -- fused ONLY when immediately followed by LPAREN\n // (see LineRefNormalizerRule's lookahead guard), so \":sum = 100\" and\n // MathPhrases' \"total of X, Y\" (no paren after \"of\") are unaffected.\n SUM_RANGE_CALL: \"SUM_RANGE_CALL\",\n AVERAGE_RANGE_CALL: \"AVERAGE_RANGE_CALL\",\n // \"total above\" / \"sum above\" / \"average above\" -- phrase-fused (see\n // LinesPackage.ts's `phrases` field), a deliberate departure from\n // Numi/Numbr's bare \"total\"/\"sum\" wording to avoid the exact bare-\n // keyword collision this codebase already regressed on once.\n TOTAL_ABOVE: \"TOTAL_ABOVE\",\n SUM_ABOVE: \"SUM_ABOVE\",\n AVERAGE_ABOVE: \"AVERAGE_ABOVE\",\n // ── Goal seek (packages/goalseek/) ──\n // \"solve line 4 for rate = 900\" -- fused by GoalSeekNormalizerRule when the\n // bare word \"solve\" is immediately followed by a LINE_REF (never a bare\n // lexer keyword, so \":solve = 2\" and the existing \"solve(...)\" call form\n // both stay untouched, since neither is \"solve\" directly before a LINE_REF).\n GOAL_SEEK: \"GOAL_SEEK\",\n} as const;\n\n/**\n * A token's kind, as a string.\n *\n * Deliberately open rather than an enum: a package registers its own token\n * types at runtime, and a closed set would make that impossible.\n */\nexport type TokenType = (typeof TokenTypes)[keyof typeof TokenTypes];\n\n// ── Integer Token Type ID System ──────────────────────────────────────────────\n// Enables O(1) integer comparison in Parser hot path instead of string hashing.\n\n/** Auto-incrementing integer ID for each token type. */\nlet _nextTokenTypeId = 0;\n\n/** String → integer ID lookup. Populated lazily via registerTokenType(). */\nconst _tokenTypeNameToId = new Map<string, number>();\n\n/** Integer ID → string lookup. For debug/error messages. */\nconst _tokenTypeIdToName = new Map<number, string>();\n\n/**\n * Register a token type name and get back its integer ID.\n * Idempotent, returns existing ID if already registered.\n * Call once per token type at module initialization time.\n */\nexport function registerTokenType(name: string): number {\n\tconst existing = _tokenTypeNameToId.get(name);\n\tif (existing !== undefined) return existing;\n\tconst id = _nextTokenTypeId++;\n\t_tokenTypeNameToId.set(name, id);\n\t_tokenTypeIdToName.set(id, name);\n\treturn id;\n}\n\n/**\n * Get the integer ID for a token type name.\n * Lazily registers unknown token types on first access, enabling plugin providers\n * to define custom token types (VEC2, VEC3, etc.) without pre-registration.\n * All built-in TokenTypes are pre-registered via registerAllTokenTypes().\n */\nexport function tokenTypeId(name: string): number {\n\treturn registerTokenType(name); // registerTokenType is idempotent\n}\n\n/**\n * Get the string name for a token type ID (for error messages and debugging).\n * Returns `UNKNOWN_${id}` if the ID is not registered.\n */\nexport function tokenTypeName(id: number): string {\n\treturn _tokenTypeIdToName.get(id) ?? `UNKNOWN_${id}`;\n}\n\n/**\n * Bootstrap all known token types from TokenTypes at module load.\n * Call this once after TokenTypes is defined.\n */\nexport function registerAllTokenTypes(): void {\n\tfor (const name of Object.values(TokenTypes)) {\n\t\tregisterTokenType(name);\n\t}\n}\n"]}
|