solve-engine 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/{PackageCompatibility-C2IQZ_w3.d.cts → PackageCompatibility-BET0iFb9.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-Cl7GF_Iu.d.ts → PackageCompatibility-CHQ4kDT8.d.ts} +1 -1
  3. package/dist/{PackageRegistry-CZO1IbS-.d.cts → PackageRegistry-DzmG-Rvu.d.cts} +29 -0
  4. package/dist/{PackageRegistry-CK_JoX50.d.ts → PackageRegistry-YmfowYr1.d.ts} +29 -0
  5. package/dist/chunk-35RNQ2OQ.js +5 -0
  6. package/dist/chunk-35RNQ2OQ.js.map +1 -0
  7. package/dist/{chunk-Q7HPPLMG.js → chunk-55B4PSPM.js} +2 -2
  8. package/dist/{chunk-Q7HPPLMG.js.map → chunk-55B4PSPM.js.map} +1 -1
  9. package/dist/{chunk-YFX53MZF.js → chunk-5CWVWMIY.js} +2 -2
  10. package/dist/chunk-5CWVWMIY.js.map +1 -0
  11. package/dist/{chunk-3PDDKWTJ.js → chunk-5EX2FCM3.js} +3 -3
  12. package/dist/{chunk-3PDDKWTJ.js.map → chunk-5EX2FCM3.js.map} +1 -1
  13. package/dist/chunk-7EMZOBGW.cjs +3 -0
  14. package/dist/chunk-7EMZOBGW.cjs.map +1 -0
  15. package/dist/chunk-ERMNQ5QJ.js +2 -0
  16. package/dist/chunk-ERMNQ5QJ.js.map +1 -0
  17. package/dist/{chunk-RC4M6HBX.cjs → chunk-LZSSAH5D.cjs} +2 -2
  18. package/dist/chunk-LZSSAH5D.cjs.map +1 -0
  19. package/dist/chunk-SPOECHDG.cjs +5 -0
  20. package/dist/chunk-SPOECHDG.cjs.map +1 -0
  21. package/dist/{chunk-3Y56PSQD.cjs → chunk-VOTTSM4L.cjs} +3 -3
  22. package/dist/{chunk-3Y56PSQD.cjs.map → chunk-VOTTSM4L.cjs.map} +1 -1
  23. package/dist/chunk-W64AWQCX.js +3 -0
  24. package/dist/chunk-W64AWQCX.js.map +1 -0
  25. package/dist/{chunk-EEUA3OJ6.cjs → chunk-XZYZS4BP.cjs} +2 -2
  26. package/dist/{chunk-EEUA3OJ6.cjs.map → chunk-XZYZS4BP.cjs.map} +1 -1
  27. package/dist/chunk-Z4BXU65Y.cjs +2 -0
  28. package/dist/chunk-Z4BXU65Y.cjs.map +1 -0
  29. package/dist/constants.cjs +1 -1
  30. package/dist/constants.js +1 -1
  31. package/dist/engine.cjs +1 -1
  32. package/dist/engine.d.cts +2 -2
  33. package/dist/engine.d.ts +2 -2
  34. package/dist/engine.js +1 -1
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.d.cts +3 -3
  37. package/dist/index.d.ts +3 -3
  38. package/dist/index.js +1 -1
  39. package/dist/language.d.cts +2 -2
  40. package/dist/language.d.ts +2 -2
  41. package/dist/normalizer.cjs +1 -1
  42. package/dist/normalizer.js +1 -1
  43. package/dist/packages.cjs +1 -1
  44. package/dist/packages.d.cts +1 -1
  45. package/dist/packages.d.ts +1 -1
  46. package/dist/packages.js +1 -1
  47. package/dist/testing.cjs +2 -2
  48. package/dist/testing.d.cts +2 -2
  49. package/dist/testing.d.ts +2 -2
  50. package/dist/testing.js +1 -1
  51. package/dist/worker.cjs +2 -2
  52. package/dist/worker.d.cts +1 -1
  53. package/dist/worker.d.ts +1 -1
  54. package/dist/worker.js +1 -1
  55. package/package.json +1 -1
  56. package/dist/chunk-4IIFFJTJ.js +0 -5
  57. package/dist/chunk-4IIFFJTJ.js.map +0 -1
  58. package/dist/chunk-5SDSIRPL.js +0 -2
  59. package/dist/chunk-5SDSIRPL.js.map +0 -1
  60. package/dist/chunk-AYTEPHRO.js +0 -3
  61. package/dist/chunk-AYTEPHRO.js.map +0 -1
  62. package/dist/chunk-FPGYRFJY.cjs +0 -5
  63. package/dist/chunk-FPGYRFJY.cjs.map +0 -1
  64. package/dist/chunk-HDGARCI2.cjs +0 -2
  65. package/dist/chunk-HDGARCI2.cjs.map +0 -1
  66. package/dist/chunk-KKMLFYVW.cjs +0 -3
  67. package/dist/chunk-KKMLFYVW.cjs.map +0 -1
  68. package/dist/chunk-RC4M6HBX.cjs.map +0 -1
  69. package/dist/chunk-YFX53MZF.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import {a,d as d$1}from'./chunk-Q3PSTNSY.js';import {a as a$1}from'./chunk-TVE2DNPU.js';import {c}from'./chunk-IJMNVBIS.js';import {c as c$1}from'./chunk-YAZ4DUJJ.js';var A=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(67),e.emitIndex(1);}};var O=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(68),e.emitIndex(1);}};function L(t,o){let r=t.peek();if(!r||r.type!=="IDENT"&&r.type!=="UNIT")throw c$1.parsing("SYMBOLIC_REQUIRES_VARIABLE_NAME",`${o} needs the name of an unknown here, as in ${o}(x^2, x).`,{found:r?.type??"end of input"});return t.consume(),r.value}function x(t,o){t.emitOpcode(13),t.emitString(o);}function N(t,o,r){let e=new d$1(o.pluginIndexMap);t.parseExpression(a.Lowest,e),t.setBuilder(o);let n=e.build();if(n.hasAsync)throw c$1.parsing("SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS",`${r}'s expression must be synchronous (no weather/stocks/currency calls).`);return n}function I(t,o,r){let e=t.emitAnonymousBody([r],o);t.emitOpcode(159),t.emitIndex(e);}var R=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"solve"),m=o.match("EQUALS")?N(o,e,"solve"):null;o.consume("COMMA");let l=o.peek();if(!l||l.type!=="IDENT"&&l.type!=="UNIT")throw c$1.parsing("SOLVE_REQUIRES_VARIABLE_NAME","solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).",{found:l?.type??"end of input"});o.consume(),I(e,n,l.value),m?I(e,m,l.value):(e.emitOpcode(10),e.emitNumber(0)),x(e,l.value),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(69),e.emitIndex(3);}};var g=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"der");o.consume("COMMA");let m=L(o,"der");I(e,n,m),x(e,m),o.match("COMMA")?o.parseExpression(a.Lowest,e):(e.emitOpcode(10),e.emitNumber(1)),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(70),e.emitIndex(3);}};var C=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"integral");o.consume("COMMA");let m=L(o,"integral");I(e,n,m),x(e,m),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(71),e.emitIndex(2);}};var M=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"taylor");o.consume("COMMA");let m=L(o,"taylor");I(e,n,m),x(e,m),o.consume("EQUALS"),o.parseExpression(a.Lowest,e),o.consume("COMMA"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(72),e.emitIndex(4);}};var S=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=0;do o.parseExpression(a.Lowest,e),n++;while(o.match("COMMA"));o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(73),e.emitIndex(n);}};var k=class{constructor(){this.category="Symbolic";}parse(o,r,e){e.emitOpcode(10),e.emitNumber(Number(r.value)),e.emitOpcode(51),e.emitIndex(74),e.emitIndex(1);}};var w=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(75),e.emitIndex(1);}};var v=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(76),e.emitIndex(1);}};var U=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(77),e.emitIndex(1);}};var F=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(78),e.emitIndex(1);}};var h=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(79),e.emitIndex(1);}};function V(t=75){return {name:"symbolic:imaginary-literal",priority:t,startTokenTypes:["NUMBER"],match(o,r){let e=o[r];if(!e||e.type!=="NUMBER")return null;let n=o[r+1];return !n||n.type!=="IDENT"||n.value!=="i"||n.offset!==e.offset+e.value.length||o[r+2]?.type==="LPAREN"?null:{consumed:2,replacement:[new a$1("IMAGINARY",c("IMAGINARY"),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:imaginary-literal"}}}}var ie={expand:"EXPAND_FN",factor:"FACTOR_FN",solve:"SOLVE_FN",der:"DER_FN",derivative:"DER_FN",integral:"INTEGRAL_FN",taylor:"TAYLOR_FN",jacobian:"JACOBIAN_FN",conj:"CONJ_FN",re:"RE_FN",im:"IM_FN",cancel:"CANCEL_FN",apart:"APART_FN"};function $(t=80){return {name:"symbolic:call",priority:t,startTokenTypes:["IDENT"],match(o,r){let e=o[r];if(!e||e.type!=="IDENT")return null;let n=ie[e.value.toLowerCase()];return !n||o[r+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new a$1(n,c(n),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:call"}}}}var j=[{word:"expand",tokenType:"EXPAND_FN",builtinIndex:67,example:"expand((x+1)*(x+2))",expected:"x^2+3x+2",docPage:"algebra.md"},{word:"factor",tokenType:"FACTOR_FN",builtinIndex:68,example:"factor(x^2-4)",expected:"(x-2)*(x+2)",docPage:"algebra.md"},{word:"solve",tokenType:"SOLVE_FN",builtinIndex:69,example:"solve(x^2-4=0, x)",expected:"= [-2, 2]",docPage:"algebra.md"},{word:"der",tokenType:"DER_FN",builtinIndex:70,example:"der(x^3, x)",expected:"3x^2",docPage:"calculus.md"},{word:"integral",tokenType:"INTEGRAL_FN",builtinIndex:71,example:"integral(x^2, x)",expected:"1/3x^3",docPage:"calculus.md"},{word:"taylor",tokenType:"TAYLOR_FN",builtinIndex:72,example:"taylor(exp(x), x=0, 3)",expected:"1/6x^3+0.5x^2+x+1",docPage:"calculus.md"},{word:"jacobian",tokenType:"JACOBIAN_FN",builtinIndex:73,example:"jacobian(x*y, x+y)",expected:"= [y, x; 1, 1]",docPage:"calculus.md"},{word:"conj",tokenType:"CONJ_FN",builtinIndex:75,example:"conj(2+3i)",expected:"2-3i",docPage:"complex.md"},{word:"re",tokenType:"RE_FN",builtinIndex:76,example:"re(2+3i)",expected:"= 2",docPage:"complex.md"},{word:"im",tokenType:"IM_FN",builtinIndex:77,example:"im(2+3i)",expected:"= 3",docPage:"complex.md"},{word:"cancel",tokenType:"CANCEL_FN",builtinIndex:78,example:"cancel((x^2-1)/(x-1))",expected:"x+1",docPage:"algebra.md"},{word:"apart",tokenType:"APART_FN",builtinIndex:79,example:"apart((3x+5)/(x^2-1))",expected:"4/(x-1)-1/(x+1)",docPage:"algebra.md"}],le={name:"solve-symbolic",normalizerRules:[$(),V()],prefixParselets:{EXPAND_FN:new A,FACTOR_FN:new O,SOLVE_FN:new R,DER_FN:new g,INTEGRAL_FN:new C,TAYLOR_FN:new M,JACOBIAN_FN:new S,IMAGINARY:new k,CONJ_FN:new w,RE_FN:new v,IM_FN:new U,CANCEL_FN:new F,APART_FN:new h},tokenCategories:{EXPAND_FN:"keyword",FACTOR_FN:"keyword",SOLVE_FN:"keyword",DER_FN:"keyword",INTEGRAL_FN:"keyword",TAYLOR_FN:"keyword",JACOBIAN_FN:"keyword",IMAGINARY:"number",CONJ_FN:"keyword",RE_FN:"keyword",IM_FN:"keyword",CANCEL_FN:"keyword",APART_FN:"keyword"}},ae=new Set(j.map(t=>t.tokenType));function se(t){return t.some(o=>ae.has(o.type))}var ce=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function H(t){let o=t.trim();if(o.length>=2&&o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),!ce.test(o))return null;let r=new Date(o).getTime();return Number.isNaN(r)?null:r}function Eo(t){let o=new Date(t),r=E=>String(E).padStart(2,"0"),e=o.getFullYear(),n=r(o.getMonth()+1),m=r(o.getDate()),l=r(o.getHours()),s=r(o.getMinutes()),c=r(o.getSeconds()),p=-o.getTimezoneOffset(),y=p>=0?"+":"-",a=Math.abs(p),f=r(Math.floor(a/60)),u=r(a%60);return `${e}-${n}-${m}T${l}:${s}:${c}${y}${f}:${u}`}var pe=1e12;function Ao(t){return Math.abs(t)>=pe?t:t*1e3}var D="DATETIME_LITERAL",J=c(D),Y=/^\d+$/,ue=/^\d{1,2}\.\d{1,2}$/,de=/^\.(\d{2}|\d{4})$/,d=/^\d{1,2}$/;function fe(t){for(let o=0;o<t.length-1;o++){let r=t[o];if((r.sourceEnd??r.offset+r.text.length)!==t[o+1].offset)return false}return true}function b(t){if(t.length===4)return Number(t);if(t.length===2){let o=Number(t);return o<=68?2e3+o:1900+o}return null}function P(t,o,r,e,n){if(o<1||o>12||t<1||t>31)return null;let m=new Date(r,o-1,t);if(m.getFullYear()!==r||m.getMonth()!==o-1||m.getDate()!==t)return null;let l=e[0],s=e.map(p=>p.value).join(""),c=new a$1(D,J,String(m.getTime()),s,l.offset,0,l.line,l.col);return {consumed:e.length,replacement:[c],ruleName:n}}var Ne=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?/,Ie=new Set(["NUMBER","MINUS","PLUS","COLON","IDENT"]),xe=16;function ye(t,o,r){let e=t[o];if(e.sourceEnd!==void 0)return null;let n=e.text,m=e.offset+e.text.length,l=[e];for(let f=o+1;f<t.length&&l.length<xe;f++){let u=t[f];if(u.sourceEnd!==void 0||u.offset!==m||!Ie.has(u.type))break;n+=u.text,m=u.offset+u.text.length,l.push(u);}let s=Ne.exec(n);if(s===null)return null;let c=0,p=0;for(let f of l)if(p+=f.text.length,c++,p>=s[0].length)break;if(p!==s[0].length)return null;let y=H(s[0]);if(y===null)return null;let a=new a$1(D,J,String(y),s[0],e.offset,0,e.line,e.col,e.offset+s[0].length);return {consumed:c,replacement:[a],ruleName:r}}function Te(t,o,r,e){if(e==="YMD")return t.length!==4||!d.test(o)||!d.test(r)?null:{year:Number(t),month:Number(o),day:Number(r)};if(!d.test(t)||!d.test(o))return null;let n=b(r);return n===null?null:e==="DMY"?{day:Number(t),month:Number(o),year:n}:{day:Number(o),month:Number(t),year:n}}function Mo(t=()=>"auto"){return {name:"datetime:date-literal",priority:70,startTokenTypes:["NUMBER"],match(o,r){let e=o[r];if(e.type!=="NUMBER")return null;if(ue.test(e.value)){let a=o[r+1];if(a&&a.type==="NUMBER"&&de.test(a.value)){let[f,u]=e.value.split("."),E=b(a.value.slice(1));if(E!==null){let z=P(Number(f),Number(u),E,[e,a],"datetime:date-literal:dot");if(z)return z}}return null}if(e.value.length===4&&Y.test(e.value)){let a=ye(o,r,"datetime:date-literal:iso-timestamp");if(a)return a}if(!Y.test(e.value))return null;let n=o[r+1];if(!n||n.type!=="SLASH"&&n.type!=="MINUS")return null;let m=o[r+2],l=o[r+3],s=o[r+4];if(!m||m.type!=="NUMBER"||!Y.test(m.value)||!l||l.type!==n.type||!s||s.type!=="NUMBER"||!Y.test(s.value))return null;let c=[e,n,m,l,s];if(!fe(c))return null;let p=t();if(p!=="auto"){let a=Te(e.value,m.value,s.value,p);return a===null?null:P(a.day,a.month,a.year,c,`datetime:date-literal:${p.toLowerCase()}`)}if(n.type==="SLASH"){if(!d.test(e.value)||!d.test(m.value))return null;let a=b(s.value);return a===null?null:P(Number(e.value),Number(m.value),a,c,"datetime:date-literal:european")}if(e.value.length===4)return !d.test(m.value)||!d.test(s.value)?null:P(Number(s.value),Number(m.value),Number(e.value),c,"datetime:date-literal:iso");if(!d.test(e.value)||!d.test(m.value))return null;let y=b(s.value);return y===null?null:P(Number(m.value),Number(e.value),y,c,"datetime:date-literal:us")}}}export{le as a,se as b,H as c,Eo as d,Ao as e,D as f,P as g,Mo as h};//# sourceMappingURL=chunk-ERMNQ5QJ.js.map
2
+ //# sourceMappingURL=chunk-ERMNQ5QJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/packages/symbolic/parselets/ExpandParselet.ts","../src/packages/symbolic/parselets/FactorParselet.ts","../src/packages/symbolic/parselets/VariableArgument.ts","../src/packages/symbolic/parselets/SolveParselet.ts","../src/packages/symbolic/parselets/DerParselet.ts","../src/packages/symbolic/parselets/IntegralParselet.ts","../src/packages/symbolic/parselets/TaylorParselet.ts","../src/packages/symbolic/parselets/JacobianParselet.ts","../src/packages/symbolic/parselets/ImaginaryParselet.ts","../src/packages/symbolic/parselets/ConjParselet.ts","../src/packages/symbolic/parselets/ReParselet.ts","../src/packages/symbolic/parselets/ImParselet.ts","../src/packages/symbolic/parselets/CancelParselet.ts","../src/packages/symbolic/parselets/ApartParselet.ts","../src/packages/symbolic/normalizer/ImaginaryLiteralNormalizerRule.ts","../src/packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts","../src/packages/symbolic/SymbolicPackage.ts","../src/packages/datetime/Iso8601.ts","../src/packages/datetime/normalizer/DateLiteralNormalizerRule.ts"],"names":["ExpandParselet","parser","_token","builder","BindingPower","FactorParselet","readVariableName","verb","token","ErrorFactory","emitVariableName","name","parseBoundExpression","inner","BytecodeBuilder","program","emitBoundExpression","index","SolveParselet","left","right","variable","DerParselet","expression","IntegralParselet","TaylorParselet","JacobianParselet","count","ImaginaryParselet","_parser","ConjParselet","ReParselet","ImParselet","CancelParselet","ApartParselet","imaginaryLiteralNormalizerRule","priority","tokens","pos","number","suffix","LexerToken","tokenTypeId","SYMBOLIC_WORD_TO_TOKEN_TYPE","symbolicCallNormalizerRule","tokenType","SYMBOLIC_FUNCTIONS","SYMBOLIC_PACKAGE","SYMBOLIC_TOKEN_TYPES","fn","containsSymbolicCall","ISO8601_PATTERN","parseIso8601","s","trimmed","ms","formatIso8601Local","epochMs","d","pad","n","year","month","day","hours","minutes","seconds","offsetMinutesTotal","sign","absOffset","offsetHours","offsetMinutes","MS_TIMESTAMP_THRESHOLD","unixTimestampToEpochMs","DATETIME_LITERAL_TYPE","DATETIME_LITERAL_TYPE_ID","PLAIN_INTEGER","DOT_DAY_MONTH","DOT_LEADING_YEAR","DAY_OR_MONTH","writtenAsOneRun","i","resolveYear","digits","yy","buildDateToken","sourceTokens","ruleName","date","first","text","t","fusedToken","ISO_TIMESTAMP","ISO_TOKEN_TYPES","ISO_MAX_TOKENS","fuseIsoTimestamp","runEnd","window","next","matched","consumed","covered","resolveOrderedGroups","g0","g1","g2","order","dateLiteralNormalizerRule","getInputOrder","t0","t1","dayText","monthText","match","timestamp","sep1","sep2","t2","resolved"],"mappings":"uKAoBO,IAAMA,CAAAA,CAAN,KAA+C,CAA/C,WAAA,EAAA,CACN,IAAA,CAAS,QAAA,CAAW,WAAA,CAEpB,KAAA,CAAMC,CAAAA,CAAgBC,CAAAA,CAAeC,CAAAA,CAAgC,CACpEF,EAAO,OAAA,CAAQ,QAAQ,CAAA,CACvBA,CAAAA,CAAO,eAAA,CAAgBG,CAAAA,CAAa,MAAA,CAAQD,CAAO,EACnDF,CAAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,CAEvBE,CAAAA,CAAQ,UAAA,CAAA,EAA8B,CAAA,CACtCA,CAAAA,CAAQ,UAAU,EAAuB,CAAA,CACzCA,CAAAA,CAAQ,SAAA,CAAU,CAAC,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AAA,CAAMyB,CAAAA,CAAc,gCAAgC,CAChH,CAGA,GAAIwB,EAAG,KAAA,CAAM,MAAA,GAAW,CAAA,CACtB,OAAI,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,CAAAA,CAAG,KAAK,CAAA,EAAK,CAAChC,CAAAA,CAAa,IAAA,CAAKuC,CAAAA,CAAG,KAAK,CAAA,CAAU,IAAA,CAElEjC,EAAe,MAAA,CAAOiC,CAAAA,CAAG,KAAK,CAAA,CAAG,MAAA,CAAOP,CAAAA,CAAG,KAAK,CAAA,CAAG,OAAOD,CAAAA,CAAG,KAAK,CAAA,CAAGxB,CAAAA,CAAc,2BAA2B,CAAA,CAEvH,GAAI,CAACP,EAAa,IAAA,CAAK+B,CAAAA,CAAG,KAAK,CAAA,EAAK,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,CAAAA,CAAG,KAAK,CAAA,CAAG,OAAO,IAAA,CACzE,IAAMlD,CAAAA,CAAOqB,CAAAA,CAAYoC,CAAAA,CAAG,KAAK,EACjC,OAAIzD,CAAAA,GAAS,IAAA,CAAa,IAAA,CAEnBwB,CAAAA,CAAe,MAAA,CAAO0B,CAAAA,CAAG,KAAK,EAAG,MAAA,CAAOD,CAAAA,CAAG,KAAK,CAAA,CAAGjD,CAAAA,CAAMyB,CAAAA,CAAc,0BAA0B,CAC1G,CACF,CACF","file":"chunk-ERMNQ5QJ.js","sourcesContent":["import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_EXPAND } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `expand(expr)`, multiplying out every product and power.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class ExpandParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_EXPAND);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_FACTOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `factor(expr)`, writing a polynomial as a product of irreducible factors over the rationals.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class FactorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_FACTOR);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { Parser } from \"@solve-js/parser/Parser\";\nimport { BytecodeBuilder, type BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Reads a bare variable name argument and returns it, consuming the token.\n *\n * Shared by every algebra verb that takes \"which unknown\" as an argument.\n * Compiling the name as an ordinary variable read would require it to already\n * have a value, which is precisely what differentiating or solving with respect\n * to it says it does not.\n *\n * Requiring `IDENT` or `UNIT` here gives the same reserved-word protection\n * `VariableParselet` relies on: a keyword always lexes as its own token type,\n * so it can never reach this position and be taken for a variable name.\n *\n * @param parser - The parser, positioned at the name.\n * @param verb - The calling verb's name, for the error message.\n * @returns The name as written.\n * @throws {EngineError} `SYMBOLIC_REQUIRES_VARIABLE_NAME` when the next token is\n * not a bare name.\n */\nexport function readVariableName(parser: Parser, verb: string): string {\n\tconst token = parser.peek();\n\tif (!token || (token.type !== \"IDENT\" && token.type !== \"UNIT\")) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n\t\t\t`${verb} needs the name of an unknown here, as in ${verb}(x^2, x).`,\n\t\t\t{ found: token?.type ?? \"end of input\" },\n\t\t);\n\t}\n\tparser.consume();\n\treturn token.value;\n}\n\n/** Emits an already-read unknown's name as the String argument the algebra builtins read it as. */\nexport function emitVariableName(builder: BytecodeBuilder, name: string): void {\n\tbuilder.emitOpcode(OpCode.PUSH_STRING);\n\tbuilder.emitString(name);\n}\n\n/**\n * Parses an algebra verb's expression argument into its own independent\n * program, rather than emitting it inline.\n *\n * The verb names its unknown AFTER the expression (`der(x^2, x)`), so the\n * expression has to be held rather than emitted: only once the name is known\n * can it be paired with {@link emitBoundExpression}, which is what makes the\n * name shadow any document value it happens to share. Compiled into an\n * isolated builder exactly like a user-defined function body or a map/reduce\n * transform, and `parseExpression` leaves `parser.builder` pointing at the\n * isolated one with no automatic restore, so the caller's builder is put back\n * before returning.\n *\n * @param parser - The parser, positioned at the start of the expression.\n * @param builder - The builder to restore afterwards.\n * @param verb - The calling verb's name, for the error message.\n * @returns The compiled expression, to be handed to {@link emitBoundExpression}.\n */\nexport function parseBoundExpression(parser: Parser, builder: BytecodeBuilder, verb: string): BytecodeProgram {\n\tconst inner = new BytecodeBuilder(builder.pluginIndexMap);\n\tparser.parseExpression(BindingPower.Lowest, inner);\n\tparser.setBuilder(builder);\n\tconst program = inner.build();\n\tif (program.hasAsync) {\n\t\t// Same v1 restriction every other deferred body carries (user-defined\n\t\t// functions, map/reduce transforms): a reentrant execution cannot\n\t\t// suspend and resume the outer expression around an async result.\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS\",\n\t\t\t`${verb}'s expression must be synchronous (no weather/stocks/currency calls).`,\n\t\t);\n\t}\n\treturn program;\n}\n\n/**\n * Emits a held expression so that it evaluates with `name` bound to itself.\n *\n * This is what makes `der(x^2, x)` mean the derivative of a square rather than\n * the derivative of a constant on a page that also says `:x = 5`. Naming `x` as\n * the verb's argument declares it bound, so within the expression it is an\n * unknown and nothing else, exactly the way a function's parameter shadows a\n * document variable of the same name inside its body. Before this, the\n * expression was compiled inline and its `x` was an ordinary variable read, so\n * the verb received 25 and answered 0 with no indication that it had not been\n * asked the question the user wrote.\n *\n * @param builder - The builder to emit into.\n * @param program - The expression, from {@link parseBoundExpression}.\n * @param name - The unknown the verb named, bound for the expression's evaluation.\n */\nexport function emitBoundExpression(builder: BytecodeBuilder, program: BytecodeProgram, name: string): void {\n\tconst index = builder.emitAnonymousBody([name], program);\n\tbuilder.emitOpcode(OpCode.BIND_UNKNOWN);\n\tbuilder.emitIndex(index);\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { SYMBOLIC_BUILTIN_SOLVE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `solve(equation, variable)`, for example `solve(x^2-4=0, x)`.\n *\n * Two things here cannot go through the ordinary function-call grammar, which\n * is why this is a hand-written parselet.\n *\n * The first argument contains a bare `=`, which no infix parselet consumes, so\n * an ordinary argument list would fail to parse it. This reads the two sides\n * separately and lets a missing right-hand side default to zero, so\n * `solve(x^2-4, x)` means the same as `solve(x^2-4=0, x)`.\n *\n * The second argument is a *name*, not a value. Compiling it as a `LOAD_VAR`\n * would demand that the variable already exist, which is exactly what solving\n * for it says it does not. Emitting it as a `PUSH_STRING` instead means the\n * builtin receives a plain String value and the VM needs no change at all.\n *\n * Both sides of the equation are held until that name has been read, so each\n * evaluates with the unknown bound to itself rather than to whatever value the\n * document may already have given it. See {@link emitBoundExpression}: with\n * `:x = 5` above it, `solve(x^2-4=0, x)` was solving `21 = 0` and reporting,\n * accurately for the question it was asked and uselessly for the one written,\n * that there is no solution.\n */\nexport class SolveParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst left = parseBoundExpression(parser, builder, \"solve\");\n\t\tconst right = parser.match(\"EQUALS\") ? parseBoundExpression(parser, builder, \"solve\") : null;\n\n\t\tparser.consume(\"COMMA\");\n\t\t// Requiring IDENT or UNIT here is the same protection VariableParselet\n\t\t// relies on: a reserved word always lexes as its own token type, so it\n\t\t// can never reach this position and be mistaken for a variable name.\n\t\tconst variable = parser.peek();\n\t\tif (!variable || (variable.type !== \"IDENT\" && variable.type !== \"UNIT\")) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"SOLVE_REQUIRES_VARIABLE_NAME\",\n\t\t\t\t`solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).`,\n\t\t\t\t{ found: variable?.type ?? \"end of input\" },\n\t\t\t);\n\t\t}\n\t\tparser.consume();\n\n\t\temitBoundExpression(builder, left, variable.value);\n\t\tif (right) {\n\t\t\temitBoundExpression(builder, right, variable.value);\n\t\t} else {\n\t\t\t// No `=` written, so the equation is \"this expression equals zero\".\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(0);\n\t\t}\n\t\temitVariableName(builder, variable.value);\n\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_SOLVE);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_DER } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `der(expr, variable)` and `der(expr, variable, order)`, the symbolic\n * derivative. `derivative` is accepted as the same thing.\n *\n * The variable is emitted as a string rather than compiled as a variable read,\n * for the reason given in {@link readVariableName}, and `expr` is held until\n * that name is known so it can be evaluated with the name bound. See\n * {@link emitBoundExpression}.\n */\nexport class DerParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"der\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"der\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\n\t\t// The order is optional and defaults to a first derivative.\n\t\tif (parser.match(\"COMMA\")) {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t} else {\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(1);\n\t\t}\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_DER);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_INTEGRAL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `integral(expr, variable)`, the indefinite integral, without a constant of\n * integration. `expr` is held until the variable is read so that the named\n * unknown shadows any document value of the same name, see\n * {@link emitBoundExpression}.\n */\nexport class IntegralParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"integral\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"integral\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_INTEGRAL);\n\t\tbuilder.emitIndex(2);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_TAYLOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `taylor(expr, variable = point, degree)`, matching Calca's own spelling.\n *\n * The `variable = point` argument is why this needs a hand-written parselet:\n * `EQUALS` has no infix parselet, so an ordinary argument list cannot parse it.\n * Reading the name and the point separately also means the name never has to\n * exist as a variable, and `expr` is held until the name is known so that the\n * name shadows any document value it shares (see {@link emitBoundExpression}).\n * The expansion point is an ordinary value expression and is not shadowed: it\n * is a number, not the unknown.\n */\nexport class TaylorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"taylor\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"taylor\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"EQUALS\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"COMMA\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_TAYLOR);\n\t\tbuilder.emitIndex(4);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_JACOBIAN } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `jacobian(f1, f2, ...)`, the matrix of partial derivatives.\n *\n * Variadic, and the variables are not named: they are taken from the union of\n * the functions' own unknowns, sorted, which is what Calca does. Row `i` is the\n * gradient of the `i`-th function.\n */\nexport class JacobianParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tlet count = 0;\n\t\tdo {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t\tcount++;\n\t\t} while (parser.match(\"COMMA\"));\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_JACOBIAN);\n\t\tbuilder.emitIndex(count);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_IMAGINARY } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * An imaginary literal, `3i`, fused by\n * `normalizer/ImaginaryLiteralNormalizerRule.ts`.\n *\n * The token carries the numeric part as its value; this pushes that number and\n * lets the builtin turn it into an exact imaginary value. Going through a\n * builtin rather than a dedicated opcode keeps the VM dispatch table untouched,\n * the same choice every other algebra verb made.\n */\nexport class ImaginaryParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(_parser: Parser, token: Token, builder: BytecodeBuilder): void {\n\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\tbuilder.emitNumber(Number(token.value));\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IMAGINARY);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CONJ } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `conj(z)`, the complex conjugate.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ConjParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CONJ);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_RE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `re(z)`, the real part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ReParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_RE);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_IM } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `im(z)`, the imaginary part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ImParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IM);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CANCEL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `cancel(expr)`, reducing a quotient of polynomials to lowest terms.\n *\n * The simplifier already cancels a common factor automatically; this is the\n * explicit form, for when the intent is to reduce a fraction rather than to\n * evaluate something that happens to contain one.\n */\nexport class CancelParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CANCEL);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_APART } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `apart(expr)`, splitting a rational function into partial fractions.\n *\n * The inverse of putting a sum of fractions over a common denominator, and the\n * step that makes a rational function integrable.\n */\nexport class ApartParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_APART);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * Fuses `3i` into a single imaginary literal, but only when the `i` is written\n * flush against the number.\n *\n * `i` is not claimed as a keyword, and deliberately so. It is one of the most\n * common variable names there is, and this engine's whole trigger-word policy\n * exists to avoid taking words a person would reasonably assign to. `:i = 5`\n * has to keep working, and after this rule it does: the rule only fires on a\n * number immediately followed by the letter, which is the same shape the\n * magnitude suffixes use, and `2.5k` set that precedent.\n *\n * Adjacency is checked by source offset rather than by token order, so `3i` is\n * an imaginary literal while `3 i` and `3 * i` are a number multiplied by a\n * variable named `i`. That is the distinction that keeps both readings\n * available, and it is the reason a bare `i` on its own is still a variable.\n * Write `1i` for the imaginary unit alone.\n */\nexport function imaginaryLiteralNormalizerRule(priority = 75): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:imaginary-literal\",\n\t\tpriority,\n\t\tstartTokenTypes: [\"NUMBER\"],\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst number = tokens[pos];\n\t\t\tif (!number || number.type !== \"NUMBER\") return null;\n\n\t\t\tconst suffix = tokens[pos + 1];\n\t\t\tif (!suffix || suffix.type !== \"IDENT\" || suffix.value !== \"i\") return null;\n\n\t\t\t// Flush against the number, with no space between them.\n\t\t\tif (suffix.offset !== number.offset + number.value.length) return null;\n\n\t\t\t// A following `(` would make this a call, as in `3i(x)`, which is not a\n\t\t\t// shape this claims.\n\t\t\tif (tokens[pos + 2]?.type === \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 2,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(\n\t\t\t\t\t\t\"IMAGINARY\",\n\t\t\t\t\t\ttokenTypeId(\"IMAGINARY\"),\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.offset,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnumber.line,\n\t\t\t\t\t\tnumber.col,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:imaginary-literal\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * The algebra verbs, mapped to the token type each becomes when it is being\n * called.\n *\n * Kept in one place so {@link SYMBOLIC_FUNCTIONS} in `SymbolicPackage.ts` and\n * this rule cannot disagree about which words the package claims.\n */\nexport const SYMBOLIC_WORD_TO_TOKEN_TYPE: Readonly<Record<string, string>> = {\n\texpand: \"EXPAND_FN\",\n\tfactor: \"FACTOR_FN\",\n\tsolve: \"SOLVE_FN\",\n\tder: \"DER_FN\",\n\tderivative: \"DER_FN\",\n\tintegral: \"INTEGRAL_FN\",\n\ttaylor: \"TAYLOR_FN\",\n\tjacobian: \"JACOBIAN_FN\",\n\tconj: \"CONJ_FN\",\n\tre: \"RE_FN\",\n\tim: \"IM_FN\",\n\tcancel: \"CANCEL_FN\",\n\tapart: \"APART_FN\",\n};\n\n/**\n * Fuses an algebra verb into its own token type, but only when the bare word is\n * immediately followed by `(`.\n *\n * None of these words may be a plain `keywordMap` entry, and the reason is\n * concrete rather than stylistic. A `keywordMap` entry makes the lexer emit a\n * reserved token type everywhere the word appears, which would break\n * `:factor = 1.5` and `:solve = 2` as ordinary variable names. `solve` is also\n * the product's own name and `factor` is an everyday English noun, so both are\n * words a user will reasonably assign to.\n *\n * Mirrors `packages/mapreduce/normalizer/MapReduceCallNormalizerRule.ts`, which\n * exists for exactly this reason for `map`/`reduce`/`sum`/`prod`.\n *\n * @param priority - Rule ordering within the normalizer, defaulting to the same\n * band the map/reduce call rule uses.\n * @returns The normalizer rule.\n */\nexport function symbolicCallNormalizerRule(priority = 80): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:call\",\n\t\tpriority,\n\t\tstartTokenTypes: [\"IDENT\"],\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst token = tokens[pos];\n\t\t\tif (!token || token.type !== \"IDENT\") return null;\n\t\t\tconst tokenType = SYMBOLIC_WORD_TO_TOKEN_TYPE[token.value.toLowerCase()];\n\t\t\tif (!tokenType) return null;\n\t\t\tif (tokens[pos + 1]?.type !== \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(tokenType, tokenTypeId(tokenType), token.value, token.value, token.offset, 0, token.line, token.col),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:call\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { ExpandParselet } from \"./parselets/ExpandParselet\";\nimport { FactorParselet } from \"./parselets/FactorParselet\";\nimport { SolveParselet } from \"./parselets/SolveParselet\";\nimport { DerParselet } from \"./parselets/DerParselet\";\nimport { IntegralParselet } from \"./parselets/IntegralParselet\";\nimport { TaylorParselet } from \"./parselets/TaylorParselet\";\nimport { JacobianParselet } from \"./parselets/JacobianParselet\";\nimport { ImaginaryParselet } from \"./parselets/ImaginaryParselet\";\nimport { ConjParselet } from \"./parselets/ConjParselet\";\nimport { ReParselet } from \"./parselets/ReParselet\";\nimport { ImParselet } from \"./parselets/ImParselet\";\nimport { CancelParselet } from \"./parselets/CancelParselet\";\nimport { ApartParselet } from \"./parselets/ApartParselet\";\nimport { imaginaryLiteralNormalizerRule } from \"./normalizer/ImaginaryLiteralNormalizerRule\";\nimport { symbolicCallNormalizerRule } from \"./normalizer/SymbolicCallNormalizerRule\";\nimport {\n\tSYMBOLIC_BUILTIN_EXPAND,\n\tSYMBOLIC_BUILTIN_FACTOR,\n\tSYMBOLIC_BUILTIN_SOLVE,\n\tSYMBOLIC_BUILTIN_DER,\n\tSYMBOLIC_BUILTIN_INTEGRAL,\n\tSYMBOLIC_BUILTIN_TAYLOR,\n\tSYMBOLIC_BUILTIN_JACOBIAN,\n\tSYMBOLIC_BUILTIN_CONJ,\n\tSYMBOLIC_BUILTIN_RE,\n\tSYMBOLIC_BUILTIN_IM,\n\tSYMBOLIC_BUILTIN_CANCEL,\n\tSYMBOLIC_BUILTIN_APART,\n} from \"./SymbolicBuiltinIndex\";\n\n/**\n * One algebra verb's whole surface, in a single row.\n *\n * Everything a verb needs in order to work is listed here rather than being\n * spread across the normalizer, the parselet registry, the builtin table and\n * the docs, so `__tests__/engine/SymbolicSurfaceParity.spec.ts` can check the\n * pieces actually agree. Shipping a verb whose index has no implementation, or\n * whose parselet is registered under a token type the normalizer never mints,\n * then becomes a failing test rather than a silent dead feature.\n */\nexport interface SymbolicFunctionSurface {\n\t/** The bare word a user types. */\n\treadonly word: string;\n\t/** The token type the normalizer fuses it into when it is followed by `(`. */\n\treadonly tokenType: string;\n\t/** The `CALL_BUILTIN` index its parselet emits. */\n\treadonly builtinIndex: number;\n\t/** A working example, executed by the parity spec through every public entry point. */\n\treadonly example: string;\n\t/** That example's expected formatted result. */\n\treadonly expected: string;\n\t/** The documentation page under `docs/src/content/docs/syntax/` that must show it. */\n\treadonly docPage: string;\n}\n\n/** Every algebra verb this package registers. */\nexport const SYMBOLIC_FUNCTIONS: readonly SymbolicFunctionSurface[] = [\n\t{\n\t\tword: \"expand\",\n\t\ttokenType: \"EXPAND_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_EXPAND,\n\t\texample: \"expand((x+1)*(x+2))\",\n\t\texpected: \"x^2+3x+2\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"factor\",\n\t\ttokenType: \"FACTOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_FACTOR,\n\t\texample: \"factor(x^2-4)\",\n\t\texpected: \"(x-2)*(x+2)\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"solve\",\n\t\ttokenType: \"SOLVE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_SOLVE,\n\t\texample: \"solve(x^2-4=0, x)\",\n\t\texpected: \"= [-2, 2]\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"der\",\n\t\ttokenType: \"DER_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_DER,\n\t\texample: \"der(x^3, x)\",\n\t\texpected: \"3x^2\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"integral\",\n\t\ttokenType: \"INTEGRAL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_INTEGRAL,\n\t\texample: \"integral(x^2, x)\",\n\t\texpected: \"1/3x^3\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"taylor\",\n\t\ttokenType: \"TAYLOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_TAYLOR,\n\t\texample: \"taylor(exp(x), x=0, 3)\",\n\t\texpected: \"1/6x^3+0.5x^2+x+1\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"jacobian\",\n\t\ttokenType: \"JACOBIAN_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_JACOBIAN,\n\t\texample: \"jacobian(x*y, x+y)\",\n\t\texpected: \"= [y, x; 1, 1]\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"conj\",\n\t\ttokenType: \"CONJ_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CONJ,\n\t\texample: \"conj(2+3i)\",\n\t\texpected: \"2-3i\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"re\",\n\t\ttokenType: \"RE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_RE,\n\t\texample: \"re(2+3i)\",\n\t\texpected: \"= 2\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"im\",\n\t\ttokenType: \"IM_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_IM,\n\t\texample: \"im(2+3i)\",\n\t\texpected: \"= 3\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"cancel\",\n\t\ttokenType: \"CANCEL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CANCEL,\n\t\texample: \"cancel((x^2-1)/(x-1))\",\n\t\texpected: \"x+1\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"apart\",\n\t\ttokenType: \"APART_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_APART,\n\t\texample: \"apart((3x+5)/(x^2-1))\",\n\t\texpected: \"4/(x-1)-1/(x+1)\",\n\t\tdocPage: \"algebra.md\",\n\t},\n];\n\n/**\n * Symbolic algebra verbs: multiplying out, and (in later phases) factoring,\n * solving and calculus.\n *\n * The algebra itself lives in `symbolic/`, which is pure mathematics over the\n * expression tree. This package is only the grammar surface: which words become\n * which tokens, and which parselet emits which builtin call.\n *\n * None of these words is a bare `keywordMap` entry. See\n * `normalizer/SymbolicCallNormalizerRule.ts` for why that matters.\n */\nexport const SYMBOLIC_PACKAGE: IEnginePackage = {\n\tname: \"solve-symbolic\",\n\tnormalizerRules: [symbolicCallNormalizerRule(), imaginaryLiteralNormalizerRule()],\n\tprefixParselets: {\n\t\tEXPAND_FN: new ExpandParselet(),\n\t\tFACTOR_FN: new FactorParselet(),\n\t\tSOLVE_FN: new SolveParselet(),\n\t\tDER_FN: new DerParselet(),\n\t\tINTEGRAL_FN: new IntegralParselet(),\n\t\tTAYLOR_FN: new TaylorParselet(),\n\t\tJACOBIAN_FN: new JacobianParselet(),\n\t\tIMAGINARY: new ImaginaryParselet(),\n\t\tCONJ_FN: new ConjParselet(),\n\t\tRE_FN: new ReParselet(),\n\t\tIM_FN: new ImParselet(),\n\t\tCANCEL_FN: new CancelParselet(),\n\t\tAPART_FN: new ApartParselet(),\n\t},\n\ttokenCategories: {\n\t\tEXPAND_FN: \"keyword\",\n\t\tFACTOR_FN: \"keyword\",\n\t\tSOLVE_FN: \"keyword\",\n\t\tDER_FN: \"keyword\",\n\t\tINTEGRAL_FN: \"keyword\",\n\t\tTAYLOR_FN: \"keyword\",\n\t\tJACOBIAN_FN: \"keyword\",\n\t\tIMAGINARY: \"number\",\n\t\tCONJ_FN: \"keyword\",\n\t\tRE_FN: \"keyword\",\n\t\tIM_FN: \"keyword\",\n\t\tCANCEL_FN: \"keyword\",\n\t\tAPART_FN: \"keyword\",\n\t},\n};\n\n/** The token types the algebra verbs fuse into, for the engine's own \"is this line symbolic\" check. */\nconst SYMBOLIC_TOKEN_TYPES: ReadonlySet<string> = new Set(SYMBOLIC_FUNCTIONS.map(fn => fn.tokenType));\n\n/**\n * Whether a normalized token list calls an algebra verb.\n *\n * `engine/ExpressionEngine.ts` uses this to evaluate such a line in\n * symbolic-tolerant mode without requiring a trailing `=>`, since asking to\n * expand or factor something is already a statement that its unknowns are meant\n * to stay unknown.\n *\n * @param tokens - The normalized tokens for one line.\n * @returns True when any token is an algebra verb.\n */\nexport function containsSymbolicCall(tokens: readonly { type: string }[]): boolean {\n\treturn tokens.some(token => SYMBOLIC_TOKEN_TYPES.has(token.type));\n}\n","/**\n * ISO8601 string <-> epoch-ms helpers backing the datetime package's\n * `<ISO8601 string> to date` and `<date/time> as iso8601` features.\n *\n * SCOPE, revised in 1.0.0: {@link parseIso8601} is now reached by BOTH input\n * shapes. A quoted string literal (`\"2019-04-01T15:30:00+11:00\" to date`)\n * always came here; the bare, unquoted form now does too, fused into one\n * DATETIME_LITERAL by `normalizer/DateLiteralNormalizerRule.ts` before the\n * parser sees it.\n *\n * This file used to record that the bare form was out of scope because it is\n * ambiguous with arithmetic (`2019 - 04 - 01` reads as two subtractions) and\n * would need a dedicated lexer change. The date half of that ambiguity was\n * already settled by the normalizer rule, and the differential run against\n * 1.0.0-beta.6 showed what leaving the other half cost: a bare\n * `2019-04-01T15:30:00+11:00` read its `+11:00` as a clock time being ADDED to\n * the date, and answered TODAY at 11:00. Not the instant, not an error, and\n * formatted as a date, which is the most convincing way to be wrong. The two\n * spellings now answer identically, which is the only defensible arrangement\n * when one of them was always right.\n */\n\n/**\n * Matches a (reasonably) well-formed ISO8601 date or date-time string:\n * `YYYY-MM-DD` optionally followed by `THH:MM[:SS[.fff]][Z|+HH:MM|-HH:MM]`.\n * Deliberately stricter than the native `Date` constructor's very lenient\n * parsing (which also accepts things like `\"April 1, 2019\"`), only a\n * string actually ISO8601-shaped is accepted here, so `\"not a date\" to\n * date` fails loudly instead of silently parsing as `Invalid Date` (or,\n * worse, something the native parser guesses at).\n */\nconst ISO8601_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Parse an ISO8601-shaped string into epoch milliseconds.\n *\n * Delegates the actual parsing to the native `Date` constructor, which\n * fully implements the ISO8601 extended format (including \"Z\"/\"+HH:MM\"\n * offsets and a fractional-seconds component) per the ECMA-262 Date Time\n * String Format spec, no custom parsing logic needed, just a stricter\n * shape gate in front of it (see {@link ISO8601_PATTERN}'s doc comment).\n *\n * A date-only string (`\"2019-04-01\"`) parses as UTC midnight; a date-time\n * with no offset and no \"Z\" (`\"2019-04-01T15:30:00\"`) parses in the HOST\n * SYSTEM's local timezone, both are the native `Date` constructor's own\n * spec-mandated behavior, not something this function adds.\n *\n * @returns epoch ms, or `null` if `s` isn't ISO8601-shaped or doesn't\n * parse to a valid instant.\n */\nexport function parseIso8601(s: string): number | null {\n // A `ValueType.String` Value's `.value` used to retain its original\n // surrounding double-quotes, because `tokenizeString()` set the token's\n // value to the raw source slice and `OpCode.PUSH_STRING` pushed that\n // verbatim. It no longer does: the token's `value` is the payload and its\n // `text` is the quoted slice. The strip below stays because this function\n // is also reachable with text that came from somewhere other than a\n // literal, and stripping a pair that is not there is a no-op.\n let trimmed = s.trim();\n if (trimmed.length >= 2 && trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n trimmed = trimmed.slice(1, -1);\n }\n if (!ISO8601_PATTERN.test(trimmed)) return null;\n const ms = new Date(trimmed).getTime();\n return Number.isNaN(ms) ? null : ms;\n}\n\n/**\n * Format epoch milliseconds as an ISO8601 string with an explicit\n * `+HH:MM`/`-HH:MM` offset, e.g. `\"2019-04-01T15:30:00+11:00\"`.\n *\n * DESIGN NOTE: uses the HOST SYSTEM's local timezone offset for the\n * offset component. This engine's `Datetime` representation is a bare\n * epoch-ms number with no zone tag (see `packages/time/TimePackage.ts`'s\n * doc comment for the same limitation affecting timezone conversion), so\n * there is no per-expression timezone context to draw on otherwise, the\n * process's own local offset (`Date.getTimezoneOffset()`) is the only\n * notion of \"local\" available. No milliseconds component is emitted,\n * matching the precision of the task's own worked example.\n */\nexport function formatIso8601Local(epochMs: number): string {\n const d = new Date(epochMs);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n\n const year = d.getFullYear();\n const month = pad(d.getMonth() + 1);\n const day = pad(d.getDate());\n const hours = pad(d.getHours());\n const minutes = pad(d.getMinutes());\n const seconds = pad(d.getSeconds());\n\n // getTimezoneOffset() is (UTC - local) in minutes, i.e. the SIGN is\n // inverted relative to a \"+HH:MM ahead of UTC\" display offset.\n const offsetMinutesTotal = -d.getTimezoneOffset();\n const sign = offsetMinutesTotal >= 0 ? \"+\" : \"-\";\n const absOffset = Math.abs(offsetMinutesTotal);\n const offsetHours = pad(Math.floor(absOffset / 60));\n const offsetMinutes = pad(absOffset % 60);\n\n return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${sign}${offsetHours}:${offsetMinutes}`;\n}\n\n/**\n * Magnitude threshold distinguishing a millisecond Unix timestamp from a\n * second Unix timestamp: values at or above this are treated as\n * milliseconds, below it as seconds.\n *\n * Chosen so that \"now\" in EITHER unit sits comfortably on its own side:\n * seconds-since-epoch for the foreseeable future stays in the ~1.7-2.5\n * billion range (1e9-1e10-ish), nowhere near 1e12, while the SAME\n * instant in milliseconds is ~1000x larger, comfortably past 1e12\n * (e.g. \"2024-12-10\" is ~1.73e9 seconds or ~1.73e12 ms). 1e12 sits well\n * clear of both real-world ranges for at least the next few centuries of\n * second-timestamps, so this is a safe, simple magnitude gate rather than\n * a fragile exact boundary.\n */\nconst MS_TIMESTAMP_THRESHOLD = 1e12;\n\n/**\n * Interpret a bare numeric Unix timestamp as epoch milliseconds, applying\n * the magnitude-based seconds-vs-milliseconds disambiguation described by\n * {@link MS_TIMESTAMP_THRESHOLD}.\n */\nexport function unixTimestampToEpochMs(n: number): number {\n return Math.abs(n) >= MS_TIMESTAMP_THRESHOLD ? n : n * 1000;\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\nimport { parseIso8601 } from \"@solve-js/packages/datetime/Iso8601\";\nimport type { DateInputOrder } from \"@solve-js/constants/Configuration\";\n\n/**\n * Token type a fused date literal is rewritten to.\n *\n * One type covers every supported ordering, so the parselet handles the shape\n * rather than the locale.\n */\nexport const DATETIME_LITERAL_TYPE = \"DATETIME_LITERAL\";\nconst DATETIME_LITERAL_TYPE_ID = tokenTypeId(DATETIME_LITERAL_TYPE);\n\n/** A pure digit string, guards against fusing hex/scientific/bigint-suffixed NUMBER tokens. */\nconst PLAIN_INTEGER = /^\\d+$/;\n\n/** First NUMBER token of a dot-separated literal: the lexer's decimal scanner\n * merges \"DD.MM\" into one float-shaped token (see module doc below). */\nconst DOT_DAY_MONTH = /^\\d{1,2}\\.\\d{1,2}$/;\n\n/** Second NUMBER token of a dot-separated literal: the lexer re-enters\n * tokenizeNumber() AT the second dot, so the year keeps its leading dot. */\nconst DOT_LEADING_YEAR = /^\\.(\\d{2}|\\d{4})$/;\n\n/**\n * Day and month groups of a separator-separated literal, in any of the three\n * orderings below: one or two digits, padded or not.\n *\n * Deliberately NOT two digits exactly. Zero-padding is what ISO 8601 requires\n * of a serialized date, but it is not what people type: \"2024-5-3\" is an\n * ordinary way to write a date and has to keep working. The digit count is\n * still bounded because a group of three or more digits is not a date group at\n * all, and the calendar check in {@link buildDateToken} would not catch it on\n * its own (\"030\" reads back as day 30).\n *\n * What actually separates a date from the arithmetic it is spelled like is\n * adjacency, not padding. See {@link writtenAsOneRun}.\n */\nconst DAY_OR_MONTH = /^\\d{1,2}$/;\n\n/**\n * Whether every token in a run touches the next one in the source text, with\n * no whitespace anywhere between the first character and the last.\n *\n * This is the whole basis for telling a date literal apart from the\n * arithmetic it is spelled identically to. A date is written as one\n * uninterrupted run (\"2024-5-3\"); a subtraction chain is written with spaces\n * around its operators (\"2024 - 5 - 3\"). The lexer records that difference in\n * the token offsets and nowhere else, since the tokens themselves are the same\n * five either way:\n *\n * 2024-5-3 NUMBER@0 MINUS@4 NUMBER@5 MINUS@6 NUMBER@7\n * 2024 - 5 - 3 NUMBER@0 MINUS@5 NUMBER@7 MINUS@9 NUMBER@11\n *\n * The same technique, for the same reason, is what tells \"5k\" from \"5 k\" in\n * `arithmetic/normalizer/LargeNumberSuffixNormalizerRule.ts`.\n *\n * ## Why this replaced a zero-padding requirement on the ISO branch\n * The ISO branch briefly required its month and day groups to be padded to two\n * digits, which did stop \"2024 - 5 - 3\" being answered as \"Friday, May 3,\n * 2024\" but also stopped \"2024-5-3\" being a date at all. Padding was never the\n * real distinction, and the rule's own US branch is the proof: it has always\n * accepted unpadded groups, so \"1-1-2020\" and \"12-25-2023\" are both dates\n * today. Requiring padding on one branch of the two was therefore an\n * inconsistency between two spellings of one rule rather than a policy.\n *\n * The US branch's own guard is a 2-or-4-digit trailing year plus the calendar\n * check, and it is NOT safe against spaced arithmetic on its own: before this\n * check existed, \"12 - 25 - 2023\" answered Christmas 2023 instead of -2036,\n * and \"1 - 1 - 2020\" answered New Year's Day instead of -2020. Applying\n * adjacency to the whole run rather than to one branch fixes that at the same\n * time and leaves both branches resting on the same reason.\n *\n * ## Padded but spaced\n * \"2024 - 05 - 03\" is subtraction under this check, and that is the intended\n * reading. Nobody types the spaces when they mean the date, so the spacing is\n * the clearest signal available about which was meant, and the padding is not:\n * a person subtracting may well write \"05\" for the same reason they write\n * \"05\" anywhere else. Choosing the date there would mean no spelling of that\n * subtraction existed.\n *\n * `sourceEnd` is preferred over `text.length` where it is set, because a token\n * an earlier rule fused carries replacement text rather than source text and\n * only `sourceEnd` still describes the span it covers (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`).\n */\nfunction writtenAsOneRun(tokens: Token[]): boolean {\n for (let i = 0; i < tokens.length - 1; i++) {\n const token = tokens[i];\n const end = token.sourceEnd ?? token.offset + token.text.length;\n if (end !== tokens[i + 1].offset) return false;\n }\n return true;\n}\n\n/**\n * Resolves a year token's raw digit text to a 4-digit year.\n *\n * Accepts exactly 2 or 4 digits (matching the wiki's documented formats).\n * A 2-digit year is windowed using the common glibc `strptime(\"%y\")`\n * convention: 00-68 -> 2000-2068, 69-99 -> 1969-1999. Any other digit\n * count (1 or 3 digits) is not a valid year shape and returns null so the\n * caller can decline the match and fall back to ordinary arithmetic.\n */\nfunction resolveYear(digits: string): number | null {\n if (digits.length === 4) return Number(digits);\n if (digits.length === 2) {\n const yy = Number(digits);\n return yy <= 68 ? 2000 + yy : 1900 + yy;\n }\n return null;\n}\n\n/**\n * Converts a validated day/month/year triple into a fused DATETIME_LITERAL\n * token, or null if the triple isn't a real calendar date (e.g. \"30\" for\n * February), letting the caller fall back to treating the source tokens\n * as ordinary arithmetic instead of a date.\n */\nexport function buildDateToken(\n day: number,\n month: number,\n year: number,\n sourceTokens: Token[],\n ruleName: string,\n): NormalizerMatch | null {\n if (month < 1 || month > 12 || day < 1 || day > 31) return null;\n\n // Local midnight, consistent with formatDatetime()'s toLocaleString()\n // display and DATE_NOW's Date.now() epoch, both of which are local-time.\n const date = new Date(year, month - 1, day);\n // Reject calendar rollover (e.g. day=30 in February) rather than silently\n // normalizing to March 2, a rollover almost always means the tokens were\n // never a date to begin with (e.g. \"2-30-5\" as chained subtraction).\n if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {\n return null;\n }\n\n const first = sourceTokens[0];\n const text = sourceTokens.map((t) => t.value).join(\"\");\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(date.getTime()),\n text,\n first.offset,\n 0,\n first.line,\n first.col,\n );\n\n return { consumed: sourceTokens.length, replacement: [fusedToken], ruleName };\n}\n\n/**\n * A full ISO 8601 timestamp: an ISO date with a time of day, optionally\n * carrying a UTC offset or the `Z` that means one of zero.\n *\n * Anchored at the start and deliberately greedy about the offset, so\n * `...T15:30:00+11:00` matches through the offset rather than stopping at the\n * seconds and leaving `+11:00` behind as an addition. That is what the bare\n * form used to do: `2019-04-01T15:30:00+11:00` read the offset as a clock time\n * being ADDED to the date on its left, and answered today at 11:00. Both\n * halves of that were wrong and neither was visible, which is worse than the\n * bare form simply not being supported.\n *\n * The time of day is required. Without it this would match what the date-only\n * branches below already handle, and they carry the ambiguity rules\n * (adjacency, group shapes) that keep a subtraction chain a subtraction.\n *\n * Matched against reconstructed source text rather than token by token. The\n * lexer has no idea this is one literal, so it emits nine to fourteen tokens\n * for it with the shape depending on the spelling (`T15` arrives as an\n * identifier, `Z` as another, an offset as a PLUS or MINUS with two more\n * numbers), and enumerating those permutations in token patterns is how a\n * spelling gets missed.\n *\n * `T` and `Z` are uppercase only, matching `Iso8601.ts`'s own pattern, which is\n * what actually parses the match. Accepting a spelling here that the parser\n * then refuses would mean the bare form supported more shapes than the quoted\n * one, for no reason a reader could infer.\n */\nconst ISO_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?/;\n\n/**\n * Token types a run of ISO 8601 timestamp text can lex into. Anything else\n * ends the run, so the reconstruction below can never reach across an operator\n * or a word that is not part of the literal.\n */\nconst ISO_TOKEN_TYPES = new Set([\"NUMBER\", \"MINUS\", \"PLUS\", \"COLON\", \"IDENT\"]);\n\n/**\n * How many tokens the longest supported spelling occupies. `2019-04-01T15:30:00.123+11:00`\n * is fourteen; the cap only bounds the walk, since the match itself decides\n * where the literal ends.\n */\nconst ISO_MAX_TOKENS = 16;\n\n/**\n * Fuses a bare (unquoted) ISO 8601 timestamp into one DATETIME_LITERAL.\n *\n * `Iso8601.ts` could always parse this shape, and still does the parsing here;\n * what it said could not be done without \"a much larger, dedicated lexer\n * change\" was recognising the bare form, on the grounds that it is ambiguous\n * with arithmetic. The date half of that ambiguity was settled by the rule this\n * helper sits inside (a date is written as one uninterrupted run, so\n * `2024 - 5 - 3` stays arithmetic), and the time half is not ambiguous at all:\n * no chain of subtractions contains a `T15:30`.\n *\n * Contiguity in the SOURCE is what makes that true, the same test\n * {@link writtenAsOneRun} applies to the date-only orderings. Every token has\n * to begin exactly where the previous one ended, so `2019-04-01 T15:30` with a\n * space in it, or `2019-04-01 + 11:00` with the offset written as an addition,\n * are left alone: the user who typed a space typed two things.\n *\n * A token an earlier normalizer rule already fused ends the run rather than\n * joining it. Its `text` is replacement text rather than source text (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`), so concatenating it\n * would reconstruct something the user never typed, and nothing that has\n * already been fused into a phrase is part of a timestamp anyway.\n *\n * @returns The fused match, or null when the tokens at `pos` are not a\n * timestamp, when the match would end mid-token, or when the shape is\n * ISO-like but names no real instant (`2019-04-01T25:00:00`).\n */\nfunction fuseIsoTimestamp(tokens: Token[], pos: number, ruleName: string): NormalizerMatch | null {\n const first = tokens[pos];\n if (first.sourceEnd !== undefined) return null;\n let text = first.text;\n let runEnd = first.offset + first.text.length;\n const window: Token[] = [first];\n for (let i = pos + 1; i < tokens.length && window.length < ISO_MAX_TOKENS; i++) {\n const next = tokens[i];\n if (next.sourceEnd !== undefined) break;\n if (next.offset !== runEnd || !ISO_TOKEN_TYPES.has(next.type)) break;\n text += next.text;\n runEnd = next.offset + next.text.length;\n window.push(next);\n }\n\n const matched = ISO_TIMESTAMP.exec(text);\n if (matched === null) return null;\n\n // The literal has to end where a token ends. A match that stopped halfway\n // through one would leave the parser holding a token whose text has already\n // been consumed, so decline and let the ordinary rules have it.\n let consumed = 0;\n let covered = 0;\n for (const token of window) {\n covered += token.text.length;\n consumed++;\n if (covered >= matched[0].length) break;\n }\n if (covered !== matched[0].length) return null;\n\n // The instant comes from the same parser the quoted form uses, so the two\n // spellings cannot drift apart: an offset means what it means there, and a\n // timestamp with no offset is local time, exactly as a bare date literal is\n // local midnight.\n const epochMs = parseIso8601(matched[0]);\n if (epochMs === null) return null;\n\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(epochMs),\n matched[0],\n first.offset,\n 0,\n first.line,\n first.col,\n first.offset + matched[0].length,\n );\n return { consumed, replacement: [fusedToken], ruleName };\n}\n\n/**\n * Maps the three numeric groups of a slash- or hyphen-separated literal to a\n * (day, month, year) triple under an explicit {@link DateInputOrder}, or null\n * when a group is the wrong shape for its role (a non-4-digit year in `YMD`, a\n * year group that is neither two nor four digits in `DMY`/`MDY`).\n *\n * Only reached when the host has fixed an order; `'auto'` keeps the historic\n * per-separator reading in the rule below and never calls this.\n */\nfunction resolveOrderedGroups(\n g0: string, g1: string, g2: string, order: Exclude<DateInputOrder, \"auto\">,\n): { day: number; month: number; year: number } | null {\n if (order === \"YMD\") {\n if (g0.length !== 4) return null;\n if (!DAY_OR_MONTH.test(g1) || !DAY_OR_MONTH.test(g2)) return null;\n return { year: Number(g0), month: Number(g1), day: Number(g2) };\n }\n // DMY and MDY: two 1-2 digit groups and a trailing 2- or 4-digit year.\n if (!DAY_OR_MONTH.test(g0) || !DAY_OR_MONTH.test(g1)) return null;\n const year = resolveYear(g2);\n if (year === null) return null;\n return order === \"DMY\"\n ? { day: Number(g0), month: Number(g1), year }\n : { day: Number(g1), month: Number(g0), year };\n}\n\n/**\n * NormalizerRule that fuses numeric date literals into a single\n * DATETIME_LITERAL token, per the documented \"Datetime Formats\":\n * - European: DD/MM/YYYY (5 tokens: NUMBER SLASH NUMBER SLASH NUMBER)\n * - US: MM-DD-YYYY (5 tokens: NUMBER MINUS NUMBER MINUS NUMBER)\n * - ISO 8601: YYYY-MM-DD (same 5-token shape as US, disambiguated by the\n * first group being exactly 4 digits)\n * - Dot: DD.MM.YYYY (2 tokens. See below)\n *\n * ## Why the dot format is a 2-token window, not 5\n * ExpressionLexer's tokenizeNumber() treats \".\" adjacent to digits on both\n * sides as a decimal point, not a separator. For \"25.12.2023\" the lexer\n * itself emits only two NUMBER tokens: \"25.12\" (day+month merged into one\n * float-shaped literal) and \".2023\" (the lexer re-enters number scanning\n * AT the second dot, so the year keeps a leading dot). There is no 5-token\n * NUMBER-DOT-NUMBER-DOT-NUMBER shape to match against, the fusion has to\n * happen post-hoc from that 2-token shape instead. This only works for the\n * literal typed with no internal whitespace (e.g. \"25.12.2023\"); a spaced\n * variant (\"25 .12 .2023\") produces three separate leading-dot tokens and\n * is intentionally not supported, out of scope for the documented format.\n *\n * ## Ambiguity with existing arithmetic\n * A date-shaped SLASH or MINUS chain (e.g. \"25/12/2023\" or \"12-25-2023\")\n * previously parsed as chained division/subtraction. This rule\n * deliberately reinterprets any such chain that resolves to a real\n * calendar date as a date literal instead, matching the documented\n * behavior. Chains that aren't valid dates (out-of-range day/month, a\n * February 30, a non-2/4-digit year) fall through unchanged.\n *\n * That reinterpretation only ever claims a chain written as one\n * uninterrupted run of characters. \"25/12/2023\" and \"12-25-2023\" are dates;\n * \"25 / 12 / 2023\" and \"12 - 25 - 2023\", written with the spaces an operator\n * normally gets, stay division and subtraction. {@link writtenAsOneRun}\n * carries the full reasoning, including why this is checked instead of\n * requiring an ISO date's zero-padding.\n *\n * ## Relationship to Iso8601.ts / DatePhrase.ts\n * This is the general-purpose \"bare numeric date literal\" implementation\n * those two files' doc comments referenced as landing on a sibling branch\n * (`feat/safety-limits-datetime-literals`), now ported here. It's\n * intentionally independent of both: `Iso8601.ts` only parses QUOTED\n * STRING literals (`\"2019-04-01...\" to date`), and the Stocks package's\n * `DatePhrase.ts` is a narrower, deliberately-diverging grammar (US-style\n * bare SLASH dates, 4-digit-year-only) scoped to stock-history queries\n * neither of those needed to change for this to land.\n */\nexport function dateLiteralNormalizerRule(\n getInputOrder: () => DateInputOrder = () => \"auto\",\n): NormalizerRule {\n return {\n name: \"datetime:date-literal\",\n priority: 70,\n startTokenTypes: [\"NUMBER\"],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n const t0 = tokens[pos];\n if (t0.type !== \"NUMBER\") return null;\n\n // ── Dot format: 2-token window (see module doc) ──────────────────\n if (DOT_DAY_MONTH.test(t0.value)) {\n const t1 = tokens[pos + 1];\n if (t1 && t1.type === \"NUMBER\" && DOT_LEADING_YEAR.test(t1.value)) {\n const [dayText, monthText] = t0.value.split(\".\");\n const year = resolveYear(t1.value.slice(1));\n if (year !== null) {\n const match = buildDateToken(\n Number(dayText), Number(monthText), year,\n [t0, t1], \"datetime:date-literal:dot\",\n );\n if (match) return match;\n }\n }\n return null;\n }\n\n // ── ISO 8601 timestamp: as many tokens as the spelling takes ─────\n // Tried before the date-only windows below, which would otherwise fuse\n // the date half of a timestamp and leave the time half to be read as\n // arithmetic. See fuseIsoTimestamp().\n if (t0.value.length === 4 && PLAIN_INTEGER.test(t0.value)) {\n const timestamp = fuseIsoTimestamp(tokens, pos, \"datetime:date-literal:iso-timestamp\");\n if (timestamp) return timestamp;\n }\n\n // ── Slash / minus format: 5-token window ─────────────────────────\n if (!PLAIN_INTEGER.test(t0.value)) return null;\n const sep1 = tokens[pos + 1];\n if (!sep1 || (sep1.type !== \"SLASH\" && sep1.type !== \"MINUS\")) return null;\n const t1 = tokens[pos + 2];\n const sep2 = tokens[pos + 3];\n const t2 = tokens[pos + 4];\n if (!t1 || t1.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t1.value)) return null;\n if (!sep2 || sep2.type !== sep1.type) return null;\n if (!t2 || t2.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t2.value)) return null;\n\n const sourceTokens = [t0, sep1, t1, sep2, t2];\n // The one check that separates every ordering below from the arithmetic\n // it is spelled identically to, and the only one that applies to all\n // three equally. See writtenAsOneRun.\n if (!writtenAsOneRun(sourceTokens)) return null;\n\n // A host-fixed order (DMY/MDY/YMD) reads slash and hyphen dates the same\n // way, so a US reader's `12/25/2023` and an ISO `2023/12/25` both parse.\n // `'auto'` falls through to the historic per-separator reading below.\n const order = getInputOrder();\n if (order !== \"auto\") {\n const resolved = resolveOrderedGroups(t0.value, t1.value, t2.value, order);\n if (resolved === null) return null;\n return buildDateToken(\n resolved.day, resolved.month, resolved.year, sourceTokens,\n `datetime:date-literal:${order.toLowerCase()}`,\n );\n }\n\n if (sep1.type === \"SLASH\") {\n // European: DD/MM/YYYY (always, no ISO-slash variant is documented)\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n return buildDateToken(Number(t0.value), Number(t1.value), year, sourceTokens, \"datetime:date-literal:european\");\n }\n\n // MINUS: ISO (YYYY-MM-DD) if the first group is exactly 4 digits, else US (MM-DD-YYYY)\n if (t0.value.length === 4) {\n if (!DAY_OR_MONTH.test(t1.value) || !DAY_OR_MONTH.test(t2.value)) return null;\n // year=t0, month=t1, day=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t2.value), Number(t1.value), Number(t0.value), sourceTokens, \"datetime:date-literal:iso\");\n }\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n // month=t0, day=t1, year=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t1.value), Number(t0.value), year, sourceTokens, \"datetime:date-literal:us\");\n },\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkFAGFPVYK_cjs=require('./chunk-FAGFPVYK.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var I={maxPasses:100,maxTokens:1e4,onFusion:()=>{}};function N(u,e,t){let n=t[0],s=t[t.length-1],r=new chunkFAGFPVYK_cjs.a(u,chunk5IJD5L3O_cjs.c(u),e,e,n.offset,n.lineBreaks??0,n.line,n.col);return r.sourceEnd=s.sourceEnd??s.offset+s.text.length,r}function A(u,e){let t=e[e.length-1];t&&(u.sourceEnd=t.sourceEnd??t.offset+t.text.length);}var v=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],k=(()=>{let u=v.map(n=>chunk5IJD5L3O_cjs.c(n)),e=Math.max(...u)+1,t=new Uint8Array(e);for(let n of u)t[n]=1;return t})(),C=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.phraseTrie=new T;this.options={...I,...e};}register(e){this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear();}unregister(e){this.rules=this.rules.filter(t=>t.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear();}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.phraseTrie=new T;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,t)=>t.priority-e.priority)),this.sortedRulesCache}rulesForTokenType(e){let t=this.rulesByTokenType.get(e);return t===void 0&&(t=this.getSortedRules().filter(n=>n.startTokenTypes===void 0||n.startTokenTypes.includes(e)),this.rulesByTokenType.set(e,t)),t}get ruleCount(){return this.rules.length}addPhrase(e,t){this.phraseTrie.addPhrase(e,t);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,t){if(e.length===0)return e;let n=t??this.options.onFusion,s=this.options.maxPasses,r=this.options.maxTokens,o=e,i=true,p=0;for(;i&&p<s;){i=false,p++;let m=[],l=0;for(;l<o.length;){let f=false,y=o[l].typeId;if(y>=k.length||k[y]===0){let c=this.phraseTrie.matchAt(o,l);if(c){let a=o.slice(l,l+c.consumed);for(let h of c.replacement)m.push(h);c.consumed>1&&c.replacement.length===1&&(A(c.replacement[0],a),n({rule:c.ruleName??"phrase-trie",sourceTokens:a,fusedToken:c.replacement[0]})),l+=c.consumed,i=true;continue}}for(let c of this.rulesForTokenType(o[l].type)){let a=c.match(o,l);if(a){let h=o.slice(l,l+a.consumed);for(let g of a.replacement)m.push(g);if(a.consumed>1&&a.replacement.length===1)A(a.replacement[0],h),n({rule:c.name,sourceTokens:h,fusedToken:a.replacement[0]});else if(a.consumed>1&&a.replacement.length<a.consumed)for(let g of a.replacement)n({rule:c.name,sourceTokens:h,fusedToken:g});l+=a.consumed,i=true,f=true;break}}f||(m.push(o[l]),l++);}if(m.length>r)throw chunkNAZ6PGLS_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${m.length}) exceeds safety limit (${r})`,{tokenCount:m.length,maxTokens:r});o=m;}return o}};var T=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,t){let n=e.toLowerCase().trim().split(/\s+/);if(n.length===0||n[0]==="")return;this.startWords.add(n[0]);let s=n[0],r;if(this.root.has(s)?r=this.root.get(s):(r={children:new Map,terminal:null},this.root.set(s,r)),n.length===1){r.terminal={tokenType:t,phrase:e,consumed:1};return}for(let o=1;o<n.length;o++){let i=n[o];r.children.has(i)||r.children.set(i,{children:new Map,terminal:null}),r=r.children.get(i);}r.terminal={tokenType:t,phrase:e,consumed:n.length};}matchAt(e,t){if(t>=e.length)return null;let n=e[t].type;if(n==="TAG"||n.startsWith("TAG_"))return null;let s=e[t].value.toLowerCase();if(!this.startWords.has(s))return null;let r=this.root.get(s);if(!r)return null;let o=null,i=1;if(r.terminal){let p=e.slice(t,t+1);o={consumed:1,replacement:[N(r.terminal.tokenType,r.terminal.phrase,p)],ruleName:r.terminal.phrase};}for(let p=t+1;p<e.length&&r?.children;p++){let m=e[p].type;if(m==="TAG"||m.startsWith("TAG_"))break;let l=e[p].value.toLowerCase();if(r=r.children.get(l),!r)break;if(i++,r.terminal){let f=e.slice(t,t+i);o={consumed:i,replacement:[N(r.terminal.tokenType,r.terminal.phrase,f)],ruleName:r.terminal.phrase};}}return o}get size(){return this.root.size}getAllPhrases(){let e={},t=(n,s)=>{n.terminal&&(e[s.join(" ")]=n.terminal.tokenType);for(let[r,o]of n.children)t(o,[...s,r]);};for(let[n,s]of this.root)t(s,[n]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var w=new Set(["per","a","an","each","every"]),L=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function S(u=50,e){let t=e??(n=>L.has(n.toLowerCase()));return {name:"implicit:multiply",priority:u,match(n,s){if(s+1>=n.length)return null;let r=n[s],o=n[s+1],i=o.value.toLowerCase();if(t(i)||w.has(i)&&n[s+2]?.type==="UNIT"||!((r.type==="NUMBER"||r.type==="RPAREN")&&(o.type==="IDENT"||o.type==="LPAREN"||o.type==="PI"||o.type==="E")))return null;let m=new chunkFAGFPVYK_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",o.offset,0,o.line,o.col);return {consumed:1,replacement:[r,m]}}}}function F(u,e){let t=[];for(let n=0;n<e;n++){let s=u[n];if(s.type==="LBRACKET")t.push(true);else if(s.type==="LPAREN"){let r=u[n-1],o=!!r&&(r.type==="MAP"||r.type==="REDUCE"||r.type==="SUM_FN"||r.type==="PROD_FN"||r.type==="IDENT"&&(r.value.toLowerCase()==="map"||r.value.toLowerCase()==="reduce"||r.value.toLowerCase()==="sum"||r.value.toLowerCase()==="prod"));t.push(o);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&t.pop();}return t.length>0&&t[t.length-1]}function W(){return [S()]}var U={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};exports.a=T;exports.b=N;exports.c=C;exports.d=S;exports.e=F;exports.f=W;exports.g=U;//# sourceMappingURL=chunk-RC4M6HBX.cjs.map
2
- //# sourceMappingURL=chunk-RC4M6HBX.cjs.map
1
+ 'use strict';var chunkFAGFPVYK_cjs=require('./chunk-FAGFPVYK.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var I={maxPasses:100,maxTokens:1e4,onFusion:()=>{}};function N(u,e,t){let n=t[0],s=t[t.length-1],r=new chunkFAGFPVYK_cjs.a(u,chunk5IJD5L3O_cjs.c(u),e,e,n.offset,n.lineBreaks??0,n.line,n.col);return r.sourceEnd=s.sourceEnd??s.offset+s.text.length,r}function A(u,e){let t=e[e.length-1];t&&(u.sourceEnd=t.sourceEnd??t.offset+t.text.length);}var v=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],k=(()=>{let u=v.map(n=>chunk5IJD5L3O_cjs.c(n)),e=Math.max(...u)+1,t=new Uint8Array(e);for(let n of u)t[n]=1;return t})(),C=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.phraseTrie=new T;this.options={...I,...e};}register(e){this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear();}unregister(e){this.rules=this.rules.filter(t=>t.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear();}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.phraseTrie=new T;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,t)=>t.priority-e.priority)),this.sortedRulesCache}rulesForTokenType(e){let t=this.rulesByTokenType.get(e);return t===void 0&&(t=this.getSortedRules().filter(n=>n.startTokenTypes===void 0||n.startTokenTypes.includes(e)),this.rulesByTokenType.set(e,t)),t}get ruleCount(){return this.rules.length}addPhrase(e,t){this.phraseTrie.addPhrase(e,t);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,t){if(e.length===0)return e;let n=t??this.options.onFusion,s=this.options.maxPasses,r=this.options.maxTokens,o=e,i=true,p=0;for(;i&&p<s;){i=false,p++;let m=[],l=0;for(;l<o.length;){let f=false,y=o[l].typeId;if(y>=k.length||k[y]===0){let c=this.phraseTrie.matchAt(o,l);if(c){let a=o.slice(l,l+c.consumed);for(let h of c.replacement)m.push(h);c.consumed>1&&c.replacement.length===1&&(A(c.replacement[0],a),n({rule:c.ruleName??"phrase-trie",sourceTokens:a,fusedToken:c.replacement[0]})),l+=c.consumed,i=true;continue}}for(let c of this.rulesForTokenType(o[l].type)){let a=c.match(o,l);if(a){let h=o.slice(l,l+a.consumed);for(let g of a.replacement)m.push(g);if(a.consumed>1&&a.replacement.length===1)A(a.replacement[0],h),n({rule:c.name,sourceTokens:h,fusedToken:a.replacement[0]});else if(a.consumed>1&&a.replacement.length<a.consumed)for(let g of a.replacement)n({rule:c.name,sourceTokens:h,fusedToken:g});l+=a.consumed,i=true,f=true;break}}f||(m.push(o[l]),l++);}if(m.length>r)throw chunkNAZ6PGLS_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${m.length}) exceeds safety limit (${r})`,{tokenCount:m.length,maxTokens:r});o=m;}return o}};var T=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,t){let n=e.toLowerCase().trim().split(/\s+/);if(n.length===0||n[0]==="")return;this.startWords.add(n[0]);let s=n[0],r;if(this.root.has(s)?r=this.root.get(s):(r={children:new Map,terminal:null},this.root.set(s,r)),n.length===1){r.terminal={tokenType:t,phrase:e,consumed:1};return}for(let o=1;o<n.length;o++){let i=n[o];r.children.has(i)||r.children.set(i,{children:new Map,terminal:null}),r=r.children.get(i);}r.terminal={tokenType:t,phrase:e,consumed:n.length};}matchAt(e,t){if(t>=e.length)return null;let n=e[t].type;if(n==="TAG"||n.startsWith("TAG_"))return null;let s=e[t].value.toLowerCase();if(!this.startWords.has(s))return null;let r=this.root.get(s);if(!r)return null;let o=null,i=1;if(r.terminal){let p=e.slice(t,t+1);o={consumed:1,replacement:[N(r.terminal.tokenType,r.terminal.phrase,p)],ruleName:r.terminal.phrase};}for(let p=t+1;p<e.length&&r?.children;p++){let m=e[p].type;if(m==="TAG"||m.startsWith("TAG_"))break;let l=e[p].value.toLowerCase();if(r=r.children.get(l),!r)break;if(i++,r.terminal){let f=e.slice(t,t+i);o={consumed:i,replacement:[N(r.terminal.tokenType,r.terminal.phrase,f)],ruleName:r.terminal.phrase};}}return o}get size(){return this.root.size}getAllPhrases(){let e={},t=(n,s)=>{n.terminal&&(e[s.join(" ")]=n.terminal.tokenType);for(let[r,o]of n.children)t(o,[...s,r]);};for(let[n,s]of this.root)t(s,[n]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var w=new Set(["per","a","an","each","every"]),L=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function S(u=50,e){let t=e??(n=>L.has(n.toLowerCase()));return {name:"implicit:multiply",priority:u,startTokenTypes:["NUMBER","RPAREN"],match(n,s){if(s+1>=n.length)return null;let r=n[s],o=n[s+1],i=o.value.toLowerCase();if(t(i)||w.has(i)&&n[s+2]?.type==="UNIT"||!((r.type==="NUMBER"||r.type==="RPAREN")&&(o.type==="IDENT"||o.type==="LPAREN"||o.type==="PI"||o.type==="E")))return null;let m=new chunkFAGFPVYK_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",o.offset,0,o.line,o.col);return {consumed:1,replacement:[r,m]}}}}function F(u,e){let t=[];for(let n=0;n<e;n++){let s=u[n];if(s.type==="LBRACKET")t.push(true);else if(s.type==="LPAREN"){let r=u[n-1],o=!!r&&(r.type==="MAP"||r.type==="REDUCE"||r.type==="SUM_FN"||r.type==="PROD_FN"||r.type==="IDENT"&&(r.value.toLowerCase()==="map"||r.value.toLowerCase()==="reduce"||r.value.toLowerCase()==="sum"||r.value.toLowerCase()==="prod"));t.push(o);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&t.pop();}return t.length>0&&t[t.length-1]}function W(){return [S()]}var U={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};exports.a=T;exports.b=N;exports.c=C;exports.d=S;exports.e=F;exports.f=W;exports.g=U;//# sourceMappingURL=chunk-LZSSAH5D.cjs.map
2
+ //# sourceMappingURL=chunk-LZSSAH5D.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","token","LexerToken","tokenTypeId","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","len","table","id","TokenNormalizer","options","PhraseTrie","rule","ruleName","r","a","b","list","phrase","tokenType","word","tokens","onFusion","fusionHandler","maxPasses","maxTokens","current","changed","passCount","result","pos","matched","tid","trieMatch","rt","match","ErrorFactory","words","firstWord","node","i","startType","best","depth","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","t","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules","BUILTIN_PHRASES"],"mappings":"uKA2EA,IAAMA,CAAAA,CAA+C,CACnD,SAAA,CAAW,GAAA,CACX,UAAW,GAAA,CACX,QAAA,CAAU,IAAM,CAAC,CACnB,CAAA,CAwBO,SAASC,CAAAA,CACdC,CAAAA,CACAC,EACAC,CAAAA,CACO,CACP,IAAMC,CAAAA,CAAQD,EAAa,CAAC,CAAA,CACtBE,CAAAA,CAAOF,CAAAA,CAAaA,EAAa,MAAA,CAAS,CAAC,CAAA,CAC3CG,CAAAA,CAAQ,IAAIC,mBAAAA,CAChBN,CAAAA,CACAO,mBAAAA,CAAYP,CAAI,EAChBC,CAAAA,CACAA,CAAAA,CACAE,CAAAA,CAAM,MAAA,CACNA,EAAM,UAAA,EAAc,CAAA,CACpBA,CAAAA,CAAM,IAAA,CACNA,EAAM,GACR,CAAA,CAGA,OAAAE,CAAAA,CAAM,UAAYD,CAAAA,CAAK,SAAA,EAAaA,CAAAA,CAAK,MAAA,CAASA,EAAK,IAAA,CAAK,MAAA,CACrDC,CACT,CAkBA,SAASG,CAAAA,CAAiBC,CAAAA,CAAcP,CAAAA,CAA6B,CACnE,IAAME,CAAAA,CAAOF,CAAAA,CAAaA,CAAAA,CAAa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,aAAA,CACf,UAAA,CAAY,UAAA,CACZ,aAAA,CAAe,cACf,WAAA,CAAa,WAAA,CAKb,eAAA,CAAiB,aAAA,CACjB,aAAc,WACf","file":"chunk-LZSSAH5D.cjs","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Per-token-type view of the priority-sorted rules: for a token type, the\n * rules that could match a token of that type (those with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list the type),\n * in the same priority order {@link getSortedRules} produces. Built lazily on\n * the first token of each type and cached, so a document of many number and\n * operator tokens never re-tries the many rules that only fire on an\n * identifier. Invalidated alongside {@link sortedRulesCache}.\n */\n private rulesByTokenType = new Map<string, NormalizerRule[]>();\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n this.rules.push(rule);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * The priority-sorted rules to try at a token of `type`: every rule with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list this type.\n * A rule that declares a different trigger would have returned null here\n * anyway, so omitting it is behaviour-preserving. Built once per distinct type\n * and cached, which is what turns the per-position rule scan from \"try all R\n * rules\" into \"try only the ones that could fire on this token\".\n */\n private rulesForTokenType(type: string): NormalizerRule[] {\n let list = this.rulesByTokenType.get(type);\n if (list === undefined) {\n list = this.getSortedRules().filter(\n (rule) => rule.startTokenTypes === undefined || rule.startTokenTypes.includes(type),\n );\n this.rulesByTokenType.set(type, list);\n }\n return list;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // Rules are consulted per token type via rulesForTokenType(), which builds\n // on the priority-sorted cache in getSortedRules().\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n const result: Token[] = [];\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try, in priority order, only the rules that can fire on this token's\n // type (see rulesForTokenType); a rule declaring a different trigger\n // would have returned null here anyway.\n for (const rule of this.rulesForTokenType(current[pos].type)) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged\n result.push(current[pos]);\n pos++;\n }\n }\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (result.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${result.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: result.length, maxTokens }\n );\n }\n\n current = result;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n startTokenTypes: [\"NUMBER\", \"RPAREN\"],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Check trigger conditions ──\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}