solve-engine 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PackageCompatibility-CCdud__Q.d.cts → PackageCompatibility-BG0iur4I.d.cts} +1 -1
- package/dist/{PackageCompatibility-4QtIErfx.d.ts → PackageCompatibility-BlIcQg5v.d.ts} +1 -1
- package/dist/{PackageRegistry-B7wkfSrY.d.ts → PackageRegistry-BJ0QQd3k.d.ts} +4 -4
- package/dist/{PackageRegistry-Hx85XD01.d.cts → PackageRegistry-DeGDZkNt.d.cts} +4 -4
- package/dist/{Parselet-CTNpfuEB.d.cts → Parselet-BSndkWEY.d.cts} +1 -1
- package/dist/{Parselet-DONNUpur.d.ts → Parselet-Blq8B0Gj.d.ts} +1 -1
- package/dist/{ScopeManager-BkbDXK_R.d.ts → ScopeManager-CF3cZUqW.d.ts} +2 -2
- package/dist/{ScopeManager-Cvgypcu4.d.cts → ScopeManager-D8nLv--u.d.cts} +2 -2
- package/dist/{VMCheckpoints-9zBQnTsN.d.ts → VMCheckpoints-BsR5_auF.d.ts} +2 -2
- package/dist/{VMCheckpoints-CBMGiSqw.d.cts → VMCheckpoints-Dy39SVHa.d.cts} +2 -2
- package/dist/{Value-D1XlMwe2.d.cts → Value-DCTqTSeP.d.cts} +22 -5
- package/dist/{Value-D1XlMwe2.d.ts → Value-DCTqTSeP.d.ts} +22 -5
- package/dist/chunk-5AMJNF7J.js +3 -0
- package/dist/chunk-5AMJNF7J.js.map +1 -0
- package/dist/chunk-5TCSFTZD.js +2 -0
- package/dist/chunk-5TCSFTZD.js.map +1 -0
- package/dist/chunk-5TVI2UPZ.cjs +2 -0
- package/dist/chunk-5TVI2UPZ.cjs.map +1 -0
- package/dist/{chunk-ZOOVGXMK.cjs → chunk-75XDS65A.cjs} +2 -2
- package/dist/{chunk-ZOOVGXMK.cjs.map → chunk-75XDS65A.cjs.map} +1 -1
- package/dist/chunk-A33K7NY4.js +2 -0
- package/dist/chunk-A33K7NY4.js.map +1 -0
- package/dist/chunk-AQWNEO7M.cjs +2 -0
- package/dist/{chunk-Z5KBBQOJ.cjs.map → chunk-AQWNEO7M.cjs.map} +1 -1
- package/dist/{chunk-OVQ3V4CG.cjs → chunk-B7J24Q5T.cjs} +2 -2
- package/dist/{chunk-OVQ3V4CG.cjs.map → chunk-B7J24Q5T.cjs.map} +1 -1
- package/dist/{chunk-HMEZJXLX.js → chunk-CVY2A3TP.js} +2 -2
- package/dist/{chunk-HMEZJXLX.js.map → chunk-CVY2A3TP.js.map} +1 -1
- package/dist/{chunk-HOQU47MF.cjs → chunk-FNNIAJNY.cjs} +2 -2
- package/dist/{chunk-HOQU47MF.cjs.map → chunk-FNNIAJNY.cjs.map} +1 -1
- package/dist/{chunk-3AVWA5IZ.cjs → chunk-FUDVKPB7.cjs} +2 -2
- package/dist/{chunk-3AVWA5IZ.cjs.map → chunk-FUDVKPB7.cjs.map} +1 -1
- package/dist/chunk-GYX6S6OS.cjs +3 -0
- package/dist/chunk-GYX6S6OS.cjs.map +1 -0
- package/dist/{chunk-GKDZ7TSX.cjs → chunk-HAEOMJE3.cjs} +2 -2
- package/dist/{chunk-GKDZ7TSX.cjs.map → chunk-HAEOMJE3.cjs.map} +1 -1
- package/dist/{chunk-T52Y5G24.js → chunk-HF4H7LYA.js} +4 -4
- package/dist/{chunk-T52Y5G24.js.map → chunk-HF4H7LYA.js.map} +1 -1
- package/dist/chunk-HTJPV42D.js +2 -0
- package/dist/{chunk-XTM4HTRB.js.map → chunk-HTJPV42D.js.map} +1 -1
- package/dist/chunk-IHZBKT7L.cjs +3 -0
- package/dist/chunk-IHZBKT7L.cjs.map +1 -0
- package/dist/{chunk-SWKYVSMP.js → chunk-JEFMG6CV.js} +2 -2
- package/dist/{chunk-SWKYVSMP.js.map → chunk-JEFMG6CV.js.map} +1 -1
- package/dist/{chunk-P6BLASAA.js → chunk-JQBG3LX4.js} +2 -2
- package/dist/{chunk-P6BLASAA.js.map → chunk-JQBG3LX4.js.map} +1 -1
- package/dist/{chunk-GHW2X7PS.js → chunk-KHCNMNZZ.js} +2 -2
- package/dist/{chunk-GHW2X7PS.js.map → chunk-KHCNMNZZ.js.map} +1 -1
- package/dist/{chunk-4XTD4B77.js → chunk-KXM7EY27.js} +3 -3
- package/dist/{chunk-4XTD4B77.js.map → chunk-KXM7EY27.js.map} +1 -1
- package/dist/{chunk-R7T3NGUE.cjs → chunk-MVP2YD4X.cjs} +2 -2
- package/dist/{chunk-R7T3NGUE.cjs.map → chunk-MVP2YD4X.cjs.map} +1 -1
- package/dist/chunk-N4HJTHZR.js +2 -0
- package/dist/{chunk-ZJPAPBP3.js.map → chunk-N4HJTHZR.js.map} +1 -1
- package/dist/chunk-P5EMTVMJ.js +3 -0
- package/dist/chunk-P5EMTVMJ.js.map +1 -0
- package/dist/chunk-PNDQRCRQ.cjs +2 -0
- package/dist/chunk-PNDQRCRQ.cjs.map +1 -0
- package/dist/{chunk-B4P4M4ZW.cjs → chunk-W7VOTR2J.cjs} +3 -3
- package/dist/{chunk-B4P4M4ZW.cjs.map → chunk-W7VOTR2J.cjs.map} +1 -1
- package/dist/{chunk-VYWGUMFW.js → chunk-WTEXBPBR.js} +2 -2
- package/dist/{chunk-VYWGUMFW.js.map → chunk-WTEXBPBR.js.map} +1 -1
- package/dist/{chunk-KSDTVFXA.cjs → chunk-ZRFUD2LX.cjs} +4 -4
- package/dist/{chunk-KSDTVFXA.cjs.map → chunk-ZRFUD2LX.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +7 -7
- package/dist/engine.d.ts +7 -7
- package/dist/engine.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/language.d.cts +6 -6
- package/dist/language.d.ts +6 -6
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +6 -6
- package/dist/packages.d.ts +6 -6
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-DY0rhgQG.d.cts → pipeline-BM8xc0CZ.d.cts} +3 -3
- package/dist/{pipeline-BH7BFOTJ.d.ts → pipeline-J2ehIm7t.d.ts} +3 -3
- package/dist/resolvers.d.cts +1 -1
- package/dist/resolvers.d.ts +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +6 -6
- package/dist/testing.d.ts +6 -6
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +1 -1
- package/dist/uom.d.ts +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +6 -6
- package/dist/vm.d.ts +6 -6
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +15 -5
- package/dist/worker.d.ts +15 -5
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-3DD2RVBI.cjs +0 -3
- package/dist/chunk-3DD2RVBI.cjs.map +0 -1
- package/dist/chunk-5FGOIDLS.cjs +0 -2
- package/dist/chunk-5FGOIDLS.cjs.map +0 -1
- package/dist/chunk-5OIXCVB2.js +0 -3
- package/dist/chunk-5OIXCVB2.js.map +0 -1
- package/dist/chunk-ESUN2THE.cjs +0 -2
- package/dist/chunk-ESUN2THE.cjs.map +0 -1
- package/dist/chunk-IO374J6Z.js +0 -2
- package/dist/chunk-IO374J6Z.js.map +0 -1
- package/dist/chunk-R2ENWQ76.js +0 -2
- package/dist/chunk-R2ENWQ76.js.map +0 -1
- package/dist/chunk-SOSUS2SK.cjs +0 -3
- package/dist/chunk-SOSUS2SK.cjs.map +0 -1
- package/dist/chunk-T4Y5XOT2.js +0 -3
- package/dist/chunk-T4Y5XOT2.js.map +0 -1
- package/dist/chunk-XTM4HTRB.js +0 -2
- package/dist/chunk-Z5KBBQOJ.cjs +0 -2
- package/dist/chunk-ZJPAPBP3.js +0 -2
package/dist/testing.d.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import { I as IEnginePackage, E as ExpressionEngine } from './PackageRegistry-
|
|
2
|
-
import { V as Value } from './Value-
|
|
1
|
+
import { I as IEnginePackage, E as ExpressionEngine } from './PackageRegistry-BJ0QQd3k.js';
|
|
2
|
+
import { V as Value } from './Value-DCTqTSeP.js';
|
|
3
3
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.js';
|
|
4
|
-
import { C as CompatibilityReport } from './PackageCompatibility-
|
|
5
|
-
import './Parselet-
|
|
4
|
+
import { C as CompatibilityReport } from './PackageCompatibility-BlIcQg5v.js';
|
|
5
|
+
import './Parselet-Blq8B0Gj.js';
|
|
6
6
|
import './BytecodeBuilder-BGq9ZiO3.js';
|
|
7
7
|
import './Token-CbP_OutD.js';
|
|
8
|
-
import './pipeline-
|
|
8
|
+
import './pipeline-J2ehIm7t.js';
|
|
9
9
|
import './Lexer-DKMlj7Sy.js';
|
|
10
10
|
import './resolvers.js';
|
|
11
11
|
import '@tanstack/query-core';
|
|
12
12
|
import './TokenNormalizer-DCWdZjGz.js';
|
|
13
|
-
import './ScopeManager-
|
|
13
|
+
import './ScopeManager-CF3cZUqW.js';
|
|
14
14
|
import './Configuration-BGQn-cJ8.js';
|
|
15
15
|
|
|
16
16
|
/**
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {n as n$1,a,b}from'./chunk-
|
|
1
|
+
import {n as n$1,a,b}from'./chunk-HF4H7LYA.js';import'./chunk-JQBG3LX4.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-N4HJTHZR.js';import'./chunk-KHCNMNZZ.js';import'./chunk-5AMJNF7J.js';import'./chunk-XEIDV5JP.js';import {y}from'./chunk-P5EMTVMJ.js';import'./chunk-JEFMG6CV.js';import'./chunk-AR7L5OJ2.js';import'./chunk-YVKHEAFT.js';import'./chunk-5FO4PDIG.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-HTJPV42D.js';import'./chunk-YAYBVVG2.js';import'./chunk-YNMMRH44.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-WTEXBPBR.js';import {m}from'./chunk-A33K7NY4.js';import'./chunk-WGZ3FNHI.js';import {a as a$1}from'./chunk-CVY2A3TP.js';import'./chunk-YAHGSBMC.js';import'./chunk-JPFCXLJV.js';import'./chunk-G7TBEQRQ.js';import'./chunk-IJMNVBIS.js';import'./chunk-62LMTO4F.js';import'./chunk-TRBXW6HW.js';import'./chunk-2JMFUQZH.js';import {b as b$1}from'./chunk-MPB7KUN5.js';var i=class o extends Error{constructor(t){super(t.message),this.name="ExpectationError",this.code=t.code,this.expected=t.expected,this.actual=t.actual,Object.setPrototypeOf(this,o.prototype);}};function V(o=[],t={}){let{locale:e="en",includeBuiltins:r=true}=t,s=new n$1({locale:e,packages:r?y:[]});for(let a of o)s.registerPackage(a);return s}function v(o,t){try{let e=o.evaluateExpression(t);return e.isError()?{status:"error",code:e.errorCode??"",message:e.errorMessage??"",source:e}:e.isPending()?{status:"pending",value:e}:{status:"value",value:e}}catch(e){if(e instanceof b$1)return {status:"error",code:e.code,message:e.message,source:e};let r=e instanceof Error?e.message:String(e);return {status:"error",code:"UNKNOWN_ERROR",message:r,source:new m(13,"UNKNOWN_ERROR",r)}}}function x(o,t){if(Object.is(o,t))return true;if(!Number.isFinite(o)||!Number.isFinite(t))return false;let e=1e-9*Math.max(1,Math.abs(o),Math.abs(t));return Math.abs(o-t)<=e}function l(o){return o.type===3?JSON.stringify(o.value):o.type===6&&typeof o.unit=="string"?`${String(o.value)} ${o.unit}`:String(o.value)}function n(o){switch(o.status){case "value":return l(o.value);case "pending":return "a pending async value";case "error":return `an error (${o.code}: ${o.message})`}}var d=class{constructor(t,e){this.expression=t;this.outcome=e;}get value(){if(this.outcome.status==="error")throw new i({code:"EXPECTED_VALUE",message:`Expected "${this.expression}" to evaluate, but it failed with ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this.outcome.value}toEvaluate(){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EVALUATE",message:`Expected "${this.expression}" to evaluate to a value, but got ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this}toEqual(t,e){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but got ${n(this.outcome)}.`,expected:c(t,e),actual:n(this.outcome)});let r=this.outcome.value,s;if(typeof t=="number"?s=x(r.toNumber(),t):typeof t=="boolean"?s=r.type===10&&r.value===t:s=C(r)===t,!s)throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but it was ${l(r)}.`,expected:c(t,e),actual:l(r)});if(e!==void 0&&r.unit!==e)throw new i({code:"EXPECTED_UNIT",message:`Expected "${this.expression}" to carry the unit "${e}", but it was ${r.unit===void 0?"unitless":`"${r.unit}"`}.`,expected:`unit "${e}"`,actual:r.unit===void 0?"no unit":`unit "${r.unit}"`});return this}toBeError(){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_ERROR",message:`Expected "${this.expression}" to fail, but it produced ${n(this.outcome)}.`,expected:"an error",actual:n(this.outcome)});return this}toFailWith(t){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it produced ${n(this.outcome)}.`,expected:`error code "${t}"`,actual:n(this.outcome)});if(this.outcome.code!==t)throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it failed with "${this.outcome.code}" (${this.outcome.message}).`,expected:`error code "${t}"`,actual:`error code "${this.outcome.code}"`});return this}toBePending(){if(this.outcome.status!=="pending")throw new i({code:"EXPECTED_PENDING",message:`Expected "${this.expression}" to be pending, but got ${n(this.outcome)}.`,expected:"a pending async value",actual:n(this.outcome)});return this}};function c(o,t){let e=typeof o=="string"?JSON.stringify(o):String(o);return t===void 0?e:`${e} ${t}`}function C(o){return String(o.value)}function D(o,t){return new d(t,v(o,t))}var O=["a","an","and","or","but","if","then","the","this","that","these","those","in","on","at","to","of","for","from","with","by","as","per","into","over","is","are","was","were","be","been","being","do","does","did","have","has","had","will","would","can","could","should","may","might","must","price","cost","value","total","sum","count","rate","amount","number","time","date","day","week","month","year","hour","minute","second","add","buy","sell","hold","make","take","give","get","set","run","up","down","out","off","all","some","any","no","not","more","less","one","two","three","first","last","next","each","every","here","there"],$=["error","warning","info"];function k(o){let t=[],e=o.lexerVocabulary;if(e?.keywords)for(let[r,s]of Object.entries(e.keywords))t.push({word:r,via:"keyword",tokenType:s});if(e?.units)for(let r of e.units)t.push({word:r,via:"unit"});if(e?.operators)for(let[r,s]of Object.entries(e.operators))t.push({word:r,via:"operator",tokenType:s});if(o.phrases)for(let[r,s]of Object.entries(o.phrases))r.includes(" ")||t.push({word:r,via:"phrase",tokenType:s});return t}var p=class{constructor(t){this.pkg=t;}notToShadow(t=O){let e=new Set(t.map(s=>s.toLowerCase())),r=k(this.pkg).filter(s=>e.has(s.word.toLowerCase()));if(r.length>0){let s=r.map(a=>`"${a.word}" (${a.via})`).join(", ");throw new i({code:"PACKAGE_SHADOWS_PROSE",message:`Package "${this.pkg.name}" claims prose word(s) as syntax: ${s}. A word that is also ordinary English turns prose into arithmetic; prefer a multi-word phrase or a form that requires a parenthesis.`,expected:"no prose words claimed as syntax",actual:s})}return r}notToCollideWith(t,e="error"){let r=a(this.pkg,t),s=$.indexOf(e),a$1=r.conflicts.filter(u=>$.indexOf(u.severity)<=s);if(a$1.length>0){let u=a$1.map(g=>`[${g.severity}] ${g.detail}`).join(`
|
|
2
2
|
`);throw new i({code:"PACKAGE_VOCABULARY_COLLISION",message:`Package "${this.pkg.name}" collides with another package:
|
|
3
3
|
${u}`,expected:`no conflicts at or above "${e}" severity`,actual:`${a$1.length} conflict(s)`})}return r}toDeclareCompatibleEngineVersion(t=a$1){let e=b(this.pkg,t);if(!e.compatible){let r=e.reason==="invalid-range"?`its range "${e.declaredRange}" is not valid semver`:`its range "${e.declaredRange}" is not satisfied by engine version "${e.engineVersion}"`;throw new i({code:"PACKAGE_ENGINE_VERSION_INCOMPATIBLE",message:`Package "${this.pkg.name}" declares an engineVersion that will be rejected at registration: ${r}.`,expected:`an engineVersion satisfied by "${t}"`,actual:`"${e.declaredRange}"`})}return this}};function L(o){return new p(o)}export{O as COMMON_PROSE_WORDS,i as ExpectationError,d as ExpressionAssertion,p as PackageAssertion,V as createTestEngine,D as expectExpression,L as expectPackage};//# sourceMappingURL=testing.js.map
|
|
4
4
|
//# sourceMappingURL=testing.js.map
|
package/dist/uom.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkFUDVKPB7_cjs=require('./chunk-FUDVKPB7.cjs'),chunk4BZIYU7S_cjs=require('./chunk-4BZIYU7S.cjs');require('./chunk-VBSMA7WJ.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-PNDQRCRQ.cjs');var chunkIANAMBJQ_cjs=require('./chunk-IANAMBJQ.cjs');require('./chunk-CIQOK7Q4.cjs'),require('./chunk-SOMGSIO4.cjs');Object.defineProperty(exports,"CurrencyAsyncResolver",{enumerable:true,get:function(){return chunkFUDVKPB7_cjs.b}});Object.defineProperty(exports,"CurrencyExchangeService",{enumerable:true,get:function(){return chunk4BZIYU7S_cjs.a}});Object.defineProperty(exports,"currencyExchangeService",{enumerable:true,get:function(){return chunk4BZIYU7S_cjs.b}});Object.defineProperty(exports,"sharedCurrencyExchange",{enumerable:true,get:function(){return chunk4BZIYU7S_cjs.c}});Object.defineProperty(exports,"canConvert",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.d}});Object.defineProperty(exports,"convertUnit",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.e}});Object.defineProperty(exports,"getBestUnit",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.h}});Object.defineProperty(exports,"getMeasure",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.c}});Object.defineProperty(exports,"isConvertibleUnit",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.g}});Object.defineProperty(exports,"resolveUnit",{enumerable:true,get:function(){return chunkIANAMBJQ_cjs.b}});//# sourceMappingURL=uom.cjs.map
|
|
2
2
|
//# sourceMappingURL=uom.cjs.map
|
package/dist/uom.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import { QueryClient } from '@tanstack/query-core';
|
|
|
2
2
|
import { T as Token } from './Token-CbP_OutD.cjs';
|
|
3
3
|
import { a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
4
4
|
import { IAsyncResolver, AsyncCheckResult } from './resolvers.cjs';
|
|
5
|
-
import './Value-
|
|
5
|
+
import './Value-DCTqTSeP.cjs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Caches exchange rates fetched from an external source.
|
package/dist/uom.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { QueryClient } from '@tanstack/query-core';
|
|
|
2
2
|
import { T as Token } from './Token-CbP_OutD.js';
|
|
3
3
|
import { a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.js';
|
|
4
4
|
import { IAsyncResolver, AsyncCheckResult } from './resolvers.js';
|
|
5
|
-
import './Value-
|
|
5
|
+
import './Value-DCTqTSeP.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Caches exchange rates fetched from an external source.
|
package/dist/uom.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as CurrencyAsyncResolver}from'./chunk-
|
|
1
|
+
export{b as CurrencyAsyncResolver}from'./chunk-JEFMG6CV.js';export{a as CurrencyExchangeService,b as currencyExchangeService,c as sharedCurrencyExchange}from'./chunk-YAYBVVG2.js';import'./chunk-YNMMRH44.js';import'./chunk-HFKDWQUL.js';import'./chunk-A33K7NY4.js';export{d as canConvert,e as convertUnit,h as getBestUnit,c as getMeasure,g as isConvertibleUnit,b as resolveUnit}from'./chunk-WGZ3FNHI.js';import'./chunk-2JMFUQZH.js';import'./chunk-MPB7KUN5.js';//# sourceMappingURL=uom.js.map
|
|
2
2
|
//# sourceMappingURL=uom.js.map
|
package/dist/vm.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkHAEOMJE3_cjs=require('./chunk-HAEOMJE3.cjs');require('./chunk-MVP2YD4X.cjs');var chunkAQWNEO7M_cjs=require('./chunk-AQWNEO7M.cjs');require('./chunk-4BZIYU7S.cjs'),require('./chunk-VBSMA7WJ.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-75XDS65A.cjs');var chunkPNDQRCRQ_cjs=require('./chunk-PNDQRCRQ.cjs');require('./chunk-IANAMBJQ.cjs'),require('./chunk-CIQOK7Q4.cjs'),require('./chunk-SOMGSIO4.cjs');var l=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,n,e){if(e.length===0)return null;let r=this.checkpoints.length>0?this.checkpoints[this.checkpoints.length-1]:null,o=Object.create(r?.variables??null),i=Object.create(r?.functions??null);for(let s of e){if(this.vm.hasUserFunction(s)){let p=this.vm.getUserFunction(s);p&&(i[s]=p);continue}let u=this.vm.getVar(s);u!==void 0&&(o[s]=u);}let c={lineNumber:t,lineId:n,variables:o,functions:i,parent:r};return this.checkpoints.push(c),c}restoreTo(t){let n=this.getNearestCheckpoint(t);if(!n){this.vm.reset();return}let e=[],r=n;for(;r;)e.unshift(r),r=r.parent;this.vm.reset();for(let o of e){for(let i of Object.keys(o.variables))this.vm.setVar(i,o.variables[i]);for(let i of Object.keys(o.functions)){let c=o.functions[i];this.vm.defineUserFunction(c.name,c.params,c.program);}}}getNearestCheckpoint(t){let n=null;for(let e of this.checkpoints)if(e.lineNumber<=t)n=e;else break;return n}getCheckpointAt(t){return this.checkpoints.find(n=>n.lineNumber===t)}getAllCheckpoints(){return this.checkpoints}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1].variables;for(;e;){if(Object.prototype.hasOwnProperty.call(e,t))return e[t];e=Object.getPrototypeOf(e);}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};Object.defineProperty(exports,"DependencyGraph",{enumerable:true,get:function(){return chunkHAEOMJE3_cjs.a}});Object.defineProperty(exports,"ScopeManager",{enumerable:true,get:function(){return chunkHAEOMJE3_cjs.b}});Object.defineProperty(exports,"createVM",{enumerable:true,get:function(){return chunkHAEOMJE3_cjs.c}});Object.defineProperty(exports,"executeBytecode",{enumerable:true,get:function(){return chunkHAEOMJE3_cjs.d}});Object.defineProperty(exports,"OpRegistry",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.v}});Object.defineProperty(exports,"allocatePluginFunctionIndex",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.E}});Object.defineProperty(exports,"binaryOp",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.u}});Object.defineProperty(exports,"builtinFunctions",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.C}});Object.defineProperty(exports,"pluginFunctionIndexFor",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.F}});Object.defineProperty(exports,"pluginFunctionRegistry",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.D}});Object.defineProperty(exports,"sharedOpRegistry",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.w}});Object.defineProperty(exports,"unifyUom",{enumerable:true,get:function(){return chunkAQWNEO7M_cjs.j}});Object.defineProperty(exports,"Value",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.m}});Object.defineProperty(exports,"ValueType",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.g}});Object.defineProperty(exports,"bigIntValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.s}});Object.defineProperty(exports,"chargeAllocation",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.c}});Object.defineProperty(exports,"checkAllocation",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.d}});Object.defineProperty(exports,"checkedArray",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.e}});Object.defineProperty(exports,"colVectorValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.E}});Object.defineProperty(exports,"hexValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.r}});Object.defineProperty(exports,"matrixValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.C}});Object.defineProperty(exports,"numberValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.n}});Object.defineProperty(exports,"rangeValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.F}});Object.defineProperty(exports,"rowVectorValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.D}});Object.defineProperty(exports,"stringValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.t}});Object.defineProperty(exports,"uomValue",{enumerable:true,get:function(){return chunkPNDQRCRQ_cjs.u}});exports.VMCheckpointer=l;//# sourceMappingURL=vm.cjs.map
|
|
2
2
|
//# sourceMappingURL=vm.cjs.map
|
package/dist/vm.d.cts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { P as PluginFunctionHandler } from './ScopeManager-
|
|
2
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, O as OpRegistry, S as ScopeManager, V as VM, c as createVM, e as executeBytecode, s as sharedOpRegistry } from './ScopeManager-
|
|
3
|
-
import { V as Value } from './Value-
|
|
4
|
-
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-
|
|
5
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-
|
|
1
|
+
import { P as PluginFunctionHandler } from './ScopeManager-D8nLv--u.cjs';
|
|
2
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, O as OpRegistry, S as ScopeManager, V as VM, c as createVM, e as executeBytecode, s as sharedOpRegistry } from './ScopeManager-D8nLv--u.cjs';
|
|
3
|
+
import { V as Value } from './Value-DCTqTSeP.cjs';
|
|
4
|
+
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-DCTqTSeP.cjs';
|
|
5
|
+
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-Dy39SVHa.cjs';
|
|
6
6
|
import './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
7
7
|
import './EngineError-Ce1lPkjZ.cjs';
|
|
8
|
-
import './pipeline-
|
|
8
|
+
import './pipeline-BM8xc0CZ.cjs';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* The ceiling on how much memory one evaluation is allowed to ask for.
|
package/dist/vm.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { P as PluginFunctionHandler } from './ScopeManager-
|
|
2
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, O as OpRegistry, S as ScopeManager, V as VM, c as createVM, e as executeBytecode, s as sharedOpRegistry } from './ScopeManager-
|
|
3
|
-
import { V as Value } from './Value-
|
|
4
|
-
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-
|
|
5
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-
|
|
1
|
+
import { P as PluginFunctionHandler } from './ScopeManager-CF3cZUqW.js';
|
|
2
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, O as OpRegistry, S as ScopeManager, V as VM, c as createVM, e as executeBytecode, s as sharedOpRegistry } from './ScopeManager-CF3cZUqW.js';
|
|
3
|
+
import { V as Value } from './Value-DCTqTSeP.js';
|
|
4
|
+
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-DCTqTSeP.js';
|
|
5
|
+
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-BsR5_auF.js';
|
|
6
6
|
import './BytecodeBuilder-BGq9ZiO3.js';
|
|
7
7
|
import './EngineError-Ce1lPkjZ.js';
|
|
8
|
-
import './pipeline-
|
|
8
|
+
import './pipeline-J2ehIm7t.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* The ceiling on how much memory one evaluation is allowed to ask for.
|
package/dist/vm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as DependencyGraph,b as ScopeManager,c as createVM,d as executeBytecode}from'./chunk-
|
|
1
|
+
export{a as DependencyGraph,b as ScopeManager,c as createVM,d as executeBytecode}from'./chunk-N4HJTHZR.js';import'./chunk-KHCNMNZZ.js';export{v as OpRegistry,E as allocatePluginFunctionIndex,u as binaryOp,C as builtinFunctions,F as pluginFunctionIndexFor,D as pluginFunctionRegistry,w as sharedOpRegistry,j as unifyUom}from'./chunk-HTJPV42D.js';import'./chunk-YAYBVVG2.js';import'./chunk-YNMMRH44.js';import'./chunk-HFKDWQUL.js';import'./chunk-WTEXBPBR.js';export{m as Value,g as ValueType,s as bigIntValue,c as chargeAllocation,d as checkAllocation,e as checkedArray,E as colVectorValue,r as hexValue,C as matrixValue,n as numberValue,F as rangeValue,D as rowVectorValue,t as stringValue,u as uomValue}from'./chunk-A33K7NY4.js';import'./chunk-WGZ3FNHI.js';import'./chunk-2JMFUQZH.js';import'./chunk-MPB7KUN5.js';var l=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,n,e){if(e.length===0)return null;let r=this.checkpoints.length>0?this.checkpoints[this.checkpoints.length-1]:null,o=Object.create(r?.variables??null),i=Object.create(r?.functions??null);for(let s of e){if(this.vm.hasUserFunction(s)){let p=this.vm.getUserFunction(s);p&&(i[s]=p);continue}let u=this.vm.getVar(s);u!==void 0&&(o[s]=u);}let c={lineNumber:t,lineId:n,variables:o,functions:i,parent:r};return this.checkpoints.push(c),c}restoreTo(t){let n=this.getNearestCheckpoint(t);if(!n){this.vm.reset();return}let e=[],r=n;for(;r;)e.unshift(r),r=r.parent;this.vm.reset();for(let o of e){for(let i of Object.keys(o.variables))this.vm.setVar(i,o.variables[i]);for(let i of Object.keys(o.functions)){let c=o.functions[i];this.vm.defineUserFunction(c.name,c.params,c.program);}}}getNearestCheckpoint(t){let n=null;for(let e of this.checkpoints)if(e.lineNumber<=t)n=e;else break;return n}getCheckpointAt(t){return this.checkpoints.find(n=>n.lineNumber===t)}getAllCheckpoints(){return this.checkpoints}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1].variables;for(;e;){if(Object.prototype.hasOwnProperty.call(e,t))return e[t];e=Object.getPrototypeOf(e);}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};export{l as VMCheckpointer};//# sourceMappingURL=vm.js.map
|
|
2
2
|
//# sourceMappingURL=vm.js.map
|
package/dist/worker.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkP6WPEUAJ_cjs=require('./chunk-P6WPEUAJ.cjs'),
|
|
2
|
-
`).forEach((u,d)=>a.set(d+1,u)):
|
|
1
|
+
'use strict';var chunkP6WPEUAJ_cjs=require('./chunk-P6WPEUAJ.cjs'),chunkZRFUD2LX_cjs=require('./chunk-ZRFUD2LX.cjs');require('./chunk-FNNIAJNY.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-LNZNJSRW.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-HAEOMJE3.cjs'),require('./chunk-MVP2YD4X.cjs');var chunkIHZBKT7L_cjs=require('./chunk-IHZBKT7L.cjs');require('./chunk-R2SZFJTT.cjs');var chunkGYX6S6OS_cjs=require('./chunk-GYX6S6OS.cjs');require('./chunk-FUDVKPB7.cjs'),require('./chunk-NXIMGB4S.cjs'),require('./chunk-4QVBSG6B.cjs'),require('./chunk-VAGS5JS7.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-AQWNEO7M.cjs'),require('./chunk-4BZIYU7S.cjs'),require('./chunk-VBSMA7WJ.cjs'),require('./chunk-TLG7VZRX.cjs');var chunk5TVI2UPZ_cjs=require('./chunk-5TVI2UPZ.cjs'),chunk75XDS65A_cjs=require('./chunk-75XDS65A.cjs');require('./chunk-PNDQRCRQ.cjs'),require('./chunk-IANAMBJQ.cjs'),require('./chunk-B7J24Q5T.cjs'),require('./chunk-32GC2FHC.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-2LFLR3VZ.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-MSYX32PF.cjs'),require('./chunk-FWW3M36J.cjs'),require('./chunk-CIQOK7Q4.cjs');var chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');var W=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:r.config,packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=chunkP6WPEUAJ_cjs.e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(chunkP6WPEUAJ_cjs.e());if(t?.aborted)return Promise.reject(chunkP6WPEUAJ_cjs.d(r));let s=this.nextId++;return new Promise((i,l)=>{let p={resolve:i,reject:l};if(t){let c=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(chunkP6WPEUAJ_cjs.d(r)));};p.signal=t,p.onAbort=c,t.addEventListener("abort",c,{once:true});}this.pending.set(s,p),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(chunkP6WPEUAJ_cjs.c(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:chunkP6WPEUAJ_cjs.c(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function K(e){let r=new W(e.transport);return await r.init(e),r}function C(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function U(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?chunk75XDS65A_cjs.R(n):typeof n=="number"&&!Number.isFinite(n)?C(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:chunkIHZBKT7L_cjs.c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=C(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=U(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:chunk5TVI2UPZ_cjs.f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:chunk5TVI2UPZ_cjs.g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:chunkIHZBKT7L_cjs.c(e).replace(/^=\s*/,"")};}return t}function O(e,r){return e?m(e,r):null}function _(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:O(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>_(n,r)),expression:e.expression,result:O(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function H(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw chunkSOMGSIO4_cjs.c.config(chunkP6WPEUAJ_cjs.a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function B(e,r={}){let n=r.packages??chunkGYX6S6OS_cjs.y,t=null,s,i=new Map,l=new Map,p=null,c=null,g=o=>e.postMessage(o),h=(o,a)=>{g({kind:"error",id:o,error:chunkP6WPEUAJ_cjs.b(chunkSOMGSIO4_cjs.d(a))});},N=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
|
|
2
|
+
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},q=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:chunkP6WPEUAJ_cjs.b(chunkSOMGSIO4_cjs.d(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let L=o.evaluateLine(d,f);L&&u.push({lineNumber:d,value:m(L,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},F=o=>{c?.();let a=o.getEventStream().getReader();c=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;q(o,d);}}catch{}})();},D=o=>{try{let a=H(n,o.packages);t=new chunkZRFUD2LX_cjs.n({locale:o.localeCode??"en",diagnostics:o.diagnostics??!1,config:o.config,packages:a}),s=o.formatting,F(t),g({kind:"ready",id:o.id});}catch(a){h(o.id,a);}},V=(o,a)=>{let{method:u,args:d}=a;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw chunkSOMGSIO4_cjs.c.execution(chunkP6WPEUAJ_cjs.a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},j=o=>{let a=t;if(!a){h(o.id,chunkSOMGSIO4_cjs.c.execution(chunkP6WPEUAJ_cjs.a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}p?.abort();let u=new AbortController;p=u,l=N(o),i.set(o.id,u),a.setKeystrokeSignal(u.signal);try{let d=V(a,o);g({kind:"result",id:o.id,value:d});}catch(d){h(o.id,d);}finally{i.delete(o.id),a.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":D(a);break;case "request":j(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{c?.(),c=null,p?.abort(),p=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function G(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function J(){let e=null,r=null,n=true,t=(l,p)=>{let c=G(p);queueMicrotask(()=>{n&&l()?.(c);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function $(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function Q(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}exports.createLinkedTransports=J;exports.createWorkerEngine=K;exports.eventTargetTransport=$;exports.messagePortTransport=Q;exports.serializeParsedLine=y;exports.serializeParsingResult=R;exports.serializeValue=m;exports.startWorkerRuntime=B;//# sourceMappingURL=worker.cjs.map
|
|
3
3
|
//# sourceMappingURL=worker.cjs.map
|
package/dist/worker.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"+tCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,SAAA,CAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAAUA,CAAG,CAAC,EACtD,CAGA,IAAA,CAAKC,CAAAA,CAA6C,CACjD,IAAMC,CAAAA,CAAK,IAAA,CAAK,MAAA,EAAA,CAChB,OAAO,IAAI,OAAA,CAAc,CAACC,CAAAA,CAASC,CAAAA,GAAW,CAC7C,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAIF,CAAAA,CAA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AA,CAAQ,MACT,CACD,EAYiB,IAAA,CAVa,CAC7B,WAAA,CAAcxE,CAAAA,EAAYyE,EAAQ,IAAMH,CAAAA,CAAetE,CAAO,CAAA,CAC9D,UAAY4E,CAAAA,EAAY,CACvBL,CAAAA,CAAcK,EACf,EACA,SAAA,CAAW,IAAM,CAChBJ,CAAAA,CAAQ,MACT,CACD,CAEsB,CACvB,CAqBO,SAASK,EAAqBH,CAAAA,CAA0C,CAC9E,OAAO,CACN,YAAc1E,CAAAA,EAAY0E,CAAAA,CAAO,WAAA,CAAY1E,CAAO,EACpD,SAAA,CAAY4E,CAAAA,EAAY,CACvB,IAAMpF,EAAYiE,CAAAA,EAAmCmB,CAAAA,CAAQnB,CAAAA,CAAM,IAAI,EACnE,OAAOiB,CAAAA,CAAO,gBAAA,EAAqB,UAAA,CACtCA,EAAO,gBAAA,CAAiB,SAAA,CAAWlF,CAAQ,CAAA,CAE3CkF,EAAO,SAAA,CAAYlF,CAAAA,CAEpBkF,CAAAA,CAAO,KAAA,KACR,CAAA,CAGA,SAAA,CAAW,IAAM,CAChBA,CAAAA,CAAO,aAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,CAAAA,CAAqBC,EAAwC,CAC5E,OAAO,CACN,WAAA,CAAc/E,GAAY+E,CAAAA,CAAK,WAAA,CAAY/E,CAAO,CAAA,CAClD,UAAY4E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAY/E,CAAAA,EAAY4E,CAAAA,CAAQ5E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChB+E,EAAK,SAAA,IAAY,CACjBA,EAAK,KAAA,KACN,CACD,CACD","file":"worker.cjs","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: options.config,\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue> {\n\t\treturn this.call<SerializedValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry, chiefly its custom packages. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t});\n\t\t\tformatting = message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","ip","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"+tCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,UAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAAUA,CAAG,CAAC,EACtD,CAGA,IAAA,CAAKC,CAAAA,CAA6C,CACjD,IAAMC,CAAAA,CAAK,IAAA,CAAK,MAAA,EAAA,CAChB,OAAO,IAAI,OAAA,CAAc,CAACC,CAAAA,CAASC,CAAAA,GAAW,CAC7C,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAIF,CAAAA,CAAI,CAAE,OAAA,CAAS,IAAMC,CAAAA,EAAQ,CAAG,MAAA,CAAAC,CAAO,CAAC,CAAA,CACzD,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,CAC1B,IAAA,CAAM,MAAA,CACN,EAAA,CAAAF,CAAAA,CACA,UAAA,CAAYD,CAAAA,CAAQ,UAAA,CACpB,WAAA,CAAaA,CAAAA,CAAQ,WAAA,CACrB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAChB,QAAA,CAAUA,CAAAA,CAAQ,QAAA,CAClB,UAAA,CAAYA,CAAAA,CAAQ,UACrB,CAAC,EACF,CAAC,CACF,CAEA,aAAA,CACCI,CAAAA,CACAJ,EACmC,CAGnC,GAAM,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AC9D,UAAY6E,CAAAA,EAAY,CACvBL,CAAAA,CAAcK,EACf,EACA,SAAA,CAAW,IAAM,CAChBJ,CAAAA,CAAQ,MACT,CACD,CAEsB,CACvB,CAqBO,SAASK,EAAqBH,CAAAA,CAA0C,CAC9E,OAAO,CACN,YAAc3E,CAAAA,EAAY2E,CAAAA,CAAO,WAAA,CAAY3E,CAAO,EACpD,SAAA,CAAY6E,CAAAA,EAAY,CACvB,IAAMrF,EAAYkE,CAAAA,EAAmCmB,CAAAA,CAAQnB,CAAAA,CAAM,IAAI,EACnE,OAAOiB,CAAAA,CAAO,gBAAA,EAAqB,UAAA,CACtCA,EAAO,gBAAA,CAAiB,SAAA,CAAWnF,CAAQ,CAAA,CAE3CmF,EAAO,SAAA,CAAYnF,CAAAA,CAEpBmF,CAAAA,CAAO,KAAA,KACR,CAAA,CAGA,SAAA,CAAW,IAAM,CAChBA,CAAAA,CAAO,aAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,CAAAA,CAAqBC,EAAwC,CAC5E,OAAO,CACN,WAAA,CAAchF,GAAYgF,CAAAA,CAAK,WAAA,CAAYhF,CAAO,CAAA,CAClD,UAAY6E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAYhF,CAAAA,EAAY6E,CAAAA,CAAQ7E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChBgF,EAAK,SAAA,IAAY,CACjBA,EAAK,KAAA,KACN,CACD,CACD","file":"worker.cjs","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: options.config,\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue> {\n\t\treturn this.call<SerializedValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t} else if (value.type === ValueType.IpCidr) {\n\t\tconst ip = raw as IpCidrData;\n\t\tdto.ipCidr = {\n\t\t\t...(ip.addr !== undefined ? { addr: ip.addr } : {}),\n\t\t\t...(ip.prefix !== undefined ? { prefix: ip.prefix } : {}),\n\t\t\ttext: formatValue(value).replace(/^=\\s*/, \"\"),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry, chiefly its custom packages. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t});\n\t\t\tformatting = message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
|
package/dist/worker.d.cts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { E as EngineConfigOverride } from './Configuration-BGQn-cJ8.cjs';
|
|
2
|
-
import { U as UnifiedParsingOptions, I as IEnginePackage, J as ParsedLine, P as ParsingResult } from './PackageRegistry-
|
|
2
|
+
import { U as UnifiedParsingOptions, I as IEnginePackage, J as ParsedLine, P as ParsingResult } from './PackageRegistry-DeGDZkNt.cjs';
|
|
3
3
|
import { F as FormattingSettings } from './FormattingSettings-bRKjU7wI.cjs';
|
|
4
4
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.cjs';
|
|
5
|
-
import { b as ValueType, i as ColourFormat, V as Value } from './Value-
|
|
6
|
-
import { a as DiagnosticReportJSON } from './pipeline-
|
|
5
|
+
import { b as ValueType, i as ColourFormat, V as Value } from './Value-DCTqTSeP.cjs';
|
|
6
|
+
import { a as DiagnosticReportJSON } from './pipeline-BM8xc0CZ.cjs';
|
|
7
7
|
import { S as SerializedEngineError } from './WorkerError-B4p6PNfx.cjs';
|
|
8
|
-
import './Parselet-
|
|
8
|
+
import './Parselet-BSndkWEY.cjs';
|
|
9
9
|
import './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
10
10
|
import './Token-CbP_OutD.cjs';
|
|
11
11
|
import './Lexer-B4C1qHXu.cjs';
|
|
12
12
|
import './resolvers.cjs';
|
|
13
13
|
import '@tanstack/query-core';
|
|
14
14
|
import './TokenNormalizer-DnlL7_8c.cjs';
|
|
15
|
-
import './ScopeManager-
|
|
15
|
+
import './ScopeManager-D8nLv--u.cjs';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* The seam between the harness and whatever actually carries messages.
|
|
@@ -199,6 +199,16 @@ interface SerializedValue {
|
|
|
199
199
|
range: [number, number];
|
|
200
200
|
expr?: string;
|
|
201
201
|
};
|
|
202
|
+
/**
|
|
203
|
+
* IP/CIDR payload, present only for {@link ValueType.IpCidr}: the 32-bit
|
|
204
|
+
* `addr` and/or CIDR `prefix`, plus `text` (the dotted-quad form the answer
|
|
205
|
+
* shows). See issue #189.
|
|
206
|
+
*/
|
|
207
|
+
ipCidr?: {
|
|
208
|
+
addr?: number;
|
|
209
|
+
prefix?: number;
|
|
210
|
+
text: string;
|
|
211
|
+
};
|
|
202
212
|
/** Whether an async fallback timed out, carried through when the engine set it. */
|
|
203
213
|
timedOut?: boolean;
|
|
204
214
|
}
|