@teachinglab/omd 0.7.35 → 0.7.36

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.
@@ -57,7 +57,7 @@ q: `+this.q.toString():"")+`
57
57
  `),r.seealso&&r.seealso.length&&(i+="See also: "+r.seealso.join(", ")+`
58
58
  `),i},t.prototype.toJSON=function(){var r=$e(this.doc);return r.mathjs="Help",r},t.fromJSON=function(r){var i={};return Object.keys(r).filter(s=>s!=="mathjs").forEach(s=>{i[s]=r[s]}),new t(i)},t.prototype.valueOf=t.prototype.toString,t},{isClass:!0}),nk="Chain",sk=["?on","math","typed"],Vf=R(nk,sk,n=>{var{on:e,math:t,typed:r}=n;function i(u){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");au(u)?this.value=u.value:this.value=u}i.prototype.type="Chain",i.prototype.isChain=!0,i.prototype.done=function(){return this.value},i.prototype.valueOf=function(){return this.value},i.prototype.toString=function(){return at(this.value)},i.prototype.toJSON=function(){return{mathjs:"Chain",value:this.value}},i.fromJSON=function(u){return new i(u.value)};function s(u,c){typeof c=="function"&&(i.prototype[u]=o(c))}function a(u,c){is(i.prototype,u,function(){var f=c();if(typeof f=="function")return o(f)})}function o(u){return function(){if(arguments.length===0)return new i(u(this.value));for(var c=[this.value],h=0;h<arguments.length;h++)c[h+1]=arguments[h];if(r.isTypedFunction(u)){var f=r.resolve(u,c);if(f.params.length===1)throw new Error("chain function "+u.name+" cannot match rest parameter between chain value and additional arguments.");return new i(f.implementation.apply(u,c))}return new i(u.apply(u,c))}}i.createProxy=function(u,c){if(typeof u=="string")s(u,c);else{var h=function(p){Te(u,p)&&l[p]===void 0&&a(p,()=>u[p])};for(var f in u)h(f)}};var l={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return i.createProxy(t),e&&e("import",function(u,c,h){h||a(u,c)}),i},{isClass:!0}),FS={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]},ak={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]},ok={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]},uk={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]},lk={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]},ck={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]},hk={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]},fk={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]},dk={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]},pk={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]},mk={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...",examples:["phi"],seealso:[]},_S={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]},gk={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]},vk={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]},yk={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]},bk={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]},xk={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]},wk={name:"bignumber",category:"Construction",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","bigint","complex","fraction","index","matrix","string","unit"]},Sk={name:"bigint",category:"Construction",syntax:["bigint(x)"],description:"Create a bigint, an integer with an arbitrary number of digits, from a number or string.",examples:["123123123123123123 # a large number will lose digits",'bigint("123123123123123123")','bignumber(["1", "3", "5"])'],seealso:["boolean","bignumber","number","complex","fraction","index","matrix","string","unit"]},Nk={name:"boolean",category:"Construction",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]},Ck={name:"complex",category:"Construction",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]},Dk={name:"createUnit",category:"Construction",syntax:["createUnit(definitions)","createUnit(name, definition)"],description:"Create a user-defined unit and register it with the Unit type.",examples:['createUnit("foo")','createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})','createUnit("mph", "1 mile/hour")'],seealso:["unit","splitUnit"]},Ak={name:"fraction",category:"Construction",syntax:["fraction(num)","fraction(matrix)","fraction(num,den)","fraction({n: num, d: den})"],description:"Create a fraction from a number or from integer numerator and denominator.",examples:["fraction(0.125)","fraction(1, 3) + fraction(2, 5)","fraction({n: 333, d: 53})","fraction([sqrt(9), sqrt(10), sqrt(11)])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]},Ek={name:"index",category:"Construction",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[1:2, 1:2] = 1","B = [1, 2, 3]","B[B>1 and B<3]"],seealso:["bignumber","boolean","complex","matrix","number","range","string","unit"]},Mk={name:"matrix",category:"Construction",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()",'matrix("dense")',"matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])",'matrix([3, 4; 5, 6], "sparse")','matrix([3, 4; 5, 6], "sparse", "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","sparse"]},Tk={name:"number",category:"Construction",syntax:["x","number(x)","number(unit, valuelessUnit)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])",'number(unit("52cm"), "m")'],seealso:["bignumber","bigint","boolean","complex","fraction","index","matrix","string","unit"]},Fk={name:"sparse",category:"Construction",syntax:["sparse()","sparse([a1, b1, ...; a1, b2, ...])",'sparse([a1, b1, ...; a1, b2, ...], "number")'],description:"Create a sparse matrix.",examples:["sparse()","sparse([3, 4; 5, 6])",'sparse([3, 0; 5, 0], "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","matrix"]},_k={name:"splitUnit",category:"Construction",syntax:["splitUnit(unit: Unit, parts: Unit[])"],description:"Split a unit in an array of units whose sum is equal to the original unit.",examples:['splitUnit(1 m, ["feet", "inch"])'],seealso:["unit","createUnit"]},Ok={name:"string",category:"Construction",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]},Bk={name:"unit",category:"Construction",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]},kk={name:"config",category:"Core",syntax:["config()","config(options)"],description:"Get configuration or change configuration.",examples:["config()","1/3 + 1/4",'config({number: "Fraction"})',"1/3 + 1/4"],seealso:[]},Pk={name:"import",category:"Core",syntax:["import(functions)","import(functions, options)"],description:"Import functions or constants from an object.",examples:["import({myFn: f(x)=x^2, myConstant: 32 })","myFn(2)","myConstant"],seealso:[]},zk={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x, "string": f(x)=concat(x,x) })',"double(2)",'double("hello")'],seealso:[]},Rk={name:"derivative",category:"Algebra",syntax:["derivative(expr, variable)","derivative(expr, variable, {simplify: boolean})"],description:"Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.",examples:['derivative("2x^3", "x")','derivative("2x^3", "x", {simplify: false})','derivative("2x^2 + 3x + 4", "x")','derivative("sin(2x)", "x")','f = parse("x^2 + x")','x = parse("x")',"df = derivative(f, x)","df.evaluate({x: 3})"],seealso:["simplify","parse","evaluate"]},Lk={name:"leafCount",category:"Algebra",syntax:["leafCount(expr)"],description:"Computes the number of leaves in the parse tree of the given expression",examples:['leafCount("e^(i*pi)-1")','leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],seealso:["simplify"]},Ik={name:"lsolve",category:"Algebra",syntax:["x=lsolve(L, b)"],description:"Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolveAll","lup","lusolve","usolve","matrix","sparse"]},$k={name:"lsolveAll",category:"Algebra",syntax:["x=lsolveAll(L, b)"],description:"Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolve","lup","lusolve","usolve","matrix","sparse"]},qk={name:"lup",category:"Algebra",syntax:["lup(m)"],description:"Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U",examples:["lup([[2, 1], [1, 4]])","lup(matrix([[2, 1], [1, 4]]))","lup(sparse([[2, 1], [1, 4]]))"],seealso:["lusolve","lsolve","usolve","matrix","sparse","slu","qr"]},Hk={name:"lusolve",category:"Algebra",syntax:["x=lusolve(A, b)","x=lusolve(lu, b)"],description:"Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lusolve(a, b)"],seealso:["lup","slu","lsolve","usolve","matrix","sparse"]},Uk={name:"polynomialRoot",category:"Algebra",syntax:["x=polynomialRoot(-6, 3)","x=polynomialRoot(4, -4, 1)","x=polynomialRoot(-8, 12, -6, 1)"],description:"Finds the roots of a univariate polynomial given by its coefficients starting from constant, linear, and so on, increasing in degree.",examples:["a = polynomialRoot(-6, 11, -6, 1)"],seealso:["cbrt","sqrt"]},Vk={name:"qr",category:"Algebra",syntax:["qr(A)"],description:"Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.",examples:["qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])"],seealso:["lup","slu","matrix"]},Wk={name:"rationalize",category:"Algebra",syntax:["rationalize(expr)","rationalize(expr, scope)","rationalize(expr, scope, detailed)"],description:"Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.",examples:['rationalize("2x/y - y/(x+1)")','rationalize("2x/y - y/(x+1)", true)'],seealso:["simplify"]},jk={name:"resolve",category:"Algebra",syntax:["resolve(node, scope)"],description:"Recursively substitute variables in an expression tree.",examples:['resolve(parse("1 + x"), { x: 7 })','resolve(parse("size(text)"), { text: "Hello World" })','resolve(parse("x + y"), { x: parse("3z") })','resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],seealso:["simplify","evaluate"],mayThrow:["ReferenceError"]},Gk={name:"simplify",category:"Algebra",syntax:["simplify(expr)","simplify(expr, rules)"],description:"Simplify an expression tree.",examples:['simplify("3 + 2 / 4")','simplify("2x + x")','f = parse("x * (x + 2 + x)")',"simplified = simplify(f)","simplified.evaluate({x: 2})"],seealso:["simplifyCore","derivative","evaluate","parse","rationalize","resolve"]},Xk={name:"simplifyConstant",category:"Algebra",syntax:["simplifyConstant(expr)","simplifyConstant(expr, options)"],description:"Replace constant subexpressions of node with their values.",examples:['simplifyConstant("(3-3)*x")','simplifyConstant(parse("z-cos(tau/8)"))'],seealso:["simplify","simplifyCore","evaluate"]},Yk={name:"simplifyCore",category:"Algebra",syntax:["simplifyCore(node)"],description:"Perform simple one-pass simplifications on an expression tree.",examples:['simplifyCore(parse("0*x"))','simplifyCore(parse("(x+0)*2"))'],seealso:["simplify","simplifyConstant","evaluate"]},Jk={name:"slu",category:"Algebra",syntax:["slu(A, order, threshold)"],description:"Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U",examples:["slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)"],seealso:["lusolve","lsolve","usolve","matrix","sparse","lup","qr"]},Zk={name:"symbolicEqual",category:"Algebra",syntax:["symbolicEqual(expr1, expr2)","symbolicEqual(expr1, expr2, options)"],description:"Returns true if the difference of the expressions simplifies to 0",examples:['symbolicEqual("x*y","y*x")','symbolicEqual("abs(x^2)", "x^2")','symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],seealso:["simplify","evaluate"]},Qk={name:"usolve",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolveAll","lup","lusolve","lsolve","matrix","sparse"]},Kk={name:"usolveAll",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolve","lup","lusolve","lsolve","matrix","sparse"]},eP={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]},tP={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i","3 cm + 2 inch",'"2.3" + "4"'],seealso:["subtract"]},rP={name:"cbrt",category:"Arithmetic",syntax:["cbrt(x)","cbrt(x, allRoots)"],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:["cbrt(64)","cube(4)","cbrt(-8)","cbrt(2 + 3i)","cbrt(8i)","cbrt(8i, true)","cbrt(27 m^3)"],seealso:["square","sqrt","cube","multiply"]},iP={name:"ceil",category:"Arithmetic",syntax:["ceil(x)","ceil(x, n)","ceil(unit, valuelessUnit)","ceil(unit, n, valuelessUnit)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)","ceil(3.241cm, cm)","ceil(3.241cm, 2, cm)"],seealso:["floor","fix","round"]},nP={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]},sP={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]},aP={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]},oP={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]},uP={name:"dotPow",category:"Operators",syntax:["x .^ y","dotPow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]},lP={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x)) # Euler's formula"],seealso:["expm","expm1","pow","log"]},cP={name:"expm",category:"Arithmetic",syntax:["exp(x)"],description:"Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.",examples:["expm([[0,2],[0,0]])"],seealso:["exp"]},hP={name:"expm1",category:"Arithmetic",syntax:["expm1(x)"],description:"Calculate the value of subtracting 1 from the exponential value.",examples:["expm1(2)","pow(e, 2) - 1","log(expm1(2) + 1)"],seealso:["exp","pow","log"]},fP={name:"fix",category:"Arithmetic",syntax:["fix(x)","fix(x, n)","fix(unit, valuelessUnit)","fix(unit, n, valuelessUnit)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)","fix(3.241cm, cm)","fix(3.241cm, 2, cm)"],seealso:["ceil","floor","round"]},dP={name:"floor",category:"Arithmetic",syntax:["floor(x)","floor(x, n)","floor(unit, valuelessUnit)","floor(unit, n, valuelessUnit)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)","floor(3.241cm, cm)","floor(3.241cm, 2, cm)"],seealso:["ceil","fix","round"]},pP={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]},mP={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenuse of a list with values.",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]},gP={name:"invmod",category:"Arithmetic",syntax:["invmod(a, b)"],description:"Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax ≣ 1 (mod b)",examples:["invmod(8, 12)","invmod(7, 13)","invmod(15151, 15122)"],seealso:["gcd","xgcd"]},vP={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]},yP={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log1p","log2","log10"]},bP={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]},xP={name:"log1p",category:"Arithmetic",syntax:["log1p(x)","log1p(x, base)"],description:"Calculate the logarithm of a `value+1`",examples:["log1p(2.5)","exp(log1p(1.4))","pow(10, 4)","log1p(9999, 10)","log1p(9999) / log(10)"],seealso:["exp","log","log2","log10"]},wP={name:"log2",category:"Arithmetic",syntax:["log2(x)"],description:"Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.",examples:["log2(0.03125)","log2(16)","log2(16) / log2(2)","pow(2, 4)"],seealso:["exp","log1p","log","log10"]},SP={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]},NP={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]},CP={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i)","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)",'norm([[1, 2], [3, 4]], "inf")','norm([[1, 2], [3, 4]], "fro")']},DP={name:"nthRoot",category:"Arithmetic",syntax:["nthRoot(a)","nthRoot(a, root)"],description:'Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".',examples:["4 ^ 3","nthRoot(64, 3)","nthRoot(9, 2)","sqrt(9)"],seealso:["nthRoots","pow","sqrt"]},AP={name:"nthRoots",category:"Arithmetic",syntax:["nthRoots(A)","nthRoots(A, root)"],description:'Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.',examples:["nthRoots(1)","nthRoots(1, 3)"],seealso:["sqrt","pow","nthRoot"]},EP={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3","2*2*2","1 + e ^ (pi * i)","pow([[1, 2], [4, 3]], 2)","pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]},MP={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)","round(unit, valuelessUnit)","round(unit, n, valuelessUnit)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)","round(3.241cm, 2, cm)","round([3.2, 3.8, -4.7])"],seealso:["ceil","floor","fix"]},TP={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>0, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]},FP={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","sqrtm","multiply","nthRoot","nthRoots","pow"]},_P={name:"sqrtm",category:"Arithmetic",syntax:["sqrtm(x)"],description:"Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.",examples:["sqrtm([[33, 24], [48, 57]])"],seealso:["sqrt","abs","square","multiply"]},OP={name:"sylvester",category:"Algebra",syntax:["sylvester(A,B,C)"],description:"Solves the real-valued Sylvester equation AX+XB=C for X",examples:["sylvester([[-1, -2], [1, 1]], [[-2, 1], [-1, 2]], [[-3, 2], [3, 0]])","A = [[-1, -2], [1, 1]]; B = [[2, -1], [1, -2]]; C = [[-3, 2], [3, 0]]","sylvester(A, B, C)"],seealso:["schur","lyap"]},BP={name:"schur",category:"Algebra",syntax:["schur(A)"],description:"Performs a real Schur decomposition of the real matrix A = UTU'",examples:["schur([[1, 0], [-4, 3]])","A = [[1, 0], [-4, 3]]","schur(A)"],seealso:["lyap","sylvester"]},kP={name:"lyap",category:"Algebra",syntax:["lyap(A,Q)"],description:"Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P",examples:["lyap([[-2, 0], [1, -4]], [[3, 1], [1, 3]])","A = [[-2, 0], [1, -4]]","Q = [[3, 1], [1, 3]]","lyap(A,Q)"],seealso:["schur","sylvester"]},PP={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]},zP={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]},RP={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]},LP={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]},IP={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]},$P={name:"bitAnd",category:"Bitwise",syntax:["x & y","bitAnd(x, y)"],description:"Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0",examples:["5 & 3","bitAnd(53, 131)","[1, 12, 31] & 42"],seealso:["bitNot","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},qP={name:"bitNot",category:"Bitwise",syntax:["~x","bitNot(x)"],description:"Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.",examples:["~1","~2","bitNot([2, -3, 4])"],seealso:["bitAnd","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},HP={name:"bitOr",category:"Bitwise",syntax:["x | y","bitOr(x, y)"],description:"Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.",examples:["5 | 3","bitOr([1, 2, 3], 4)"],seealso:["bitAnd","bitNot","bitXor","leftShift","rightArithShift","rightLogShift"]},UP={name:"bitXor",category:"Bitwise",syntax:["bitXor(x, y)"],description:"Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.",examples:["bitOr(1, 2)","bitXor([2, 3, 4], 4)"],seealso:["bitAnd","bitNot","bitOr","leftShift","rightArithShift","rightLogShift"]},VP={name:"leftShift",category:"Bitwise",syntax:["x << y","leftShift(x, y)"],description:"Bitwise left logical shift of a value x by y number of bits.",examples:["4 << 1","8 >> 1"],seealso:["bitAnd","bitNot","bitOr","bitXor","rightArithShift","rightLogShift"]},WP={name:"rightArithShift",category:"Bitwise",syntax:["x >> y","rightArithShift(x, y)"],description:"Bitwise right arithmetic shift of a value x by y number of bits.",examples:["8 >> 1","4 << 1","-12 >> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightLogShift"]},jP={name:"rightLogShift",category:"Bitwise",syntax:["x >>> y","rightLogShift(x, y)"],description:"Bitwise right logical shift of a value x by y number of bits.",examples:["8 >>> 1","4 << 1","-12 >>> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightArithShift"]},GP={name:"bellNumbers",category:"Combinatorics",syntax:["bellNumbers(n)"],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["bellNumbers(3)","bellNumbers(8)"],seealso:["stirlingS2"]},XP={name:"catalan",category:"Combinatorics",syntax:["catalan(n)"],description:"The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["catalan(3)","catalan(8)"],seealso:["bellNumbers"]},YP={name:"composition",category:"Combinatorics",syntax:["composition(n, k)"],description:"The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.",examples:["composition(5, 3)"],seealso:["combinations"]},JP={name:"stirlingS2",category:"Combinatorics",syntax:["stirlingS2(n, k)"],description:"he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:["stirlingS2(5, 3)"],seealso:["bellNumbers"]},ZP={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]},QP={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]},KP={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]},e5={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]},t5={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate(expression, scope)","evaluate([expr1, expr2, expr3, ...])","evaluate([expr1, expr2, expr3, ...], scope)"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(16)")','evaluate("2 inch to cm")','evaluate("sin(x * pi)", { "x": 1/2 })','evaluate(["width=2", "height=4","width*height"])'],seealso:["parser","parse","compile"]},r5={name:"parser",category:"Expression",syntax:["parser()"],description:"Create a parser object that keeps a context of variables and their values, allowing the evaluation of expressions in that context.",examples:["myParser = parser()",'myParser.evaluate("sqrt(3^2 + 4^2)")','myParser.set("x", 3)','myParser.evaluate("y = x + 3")','myParser.evaluate(["y = x + 3", "y = y + 1"])','myParser.get("y")'],seealso:["evaluate","parse","compile"]},i5={name:"parse",category:"Expression",syntax:["parse(expr)","parse(expr, options)","parse([expr1, expr2, expr3, ...])","parse([expr1, expr2, expr3, ...], options)"],description:"Parse an expression. Returns a node tree, which can be evaluated by invoking node.evaluate() or transformed into a functional object via node.compile().",examples:['node1 = parse("sqrt(3^2 + 4^2)")',"node1.evaluate()","code1 = node1.compile()","code1.evaluate()","scope = {a: 3, b: 4}",'node2 = parse("a * b")',"node2.evaluate(scope)","code2 = node2.compile()","code2.evaluate(scope)"],seealso:["parser","evaluate","compile"]},n5={name:"compile",category:"Expression",syntax:["compile(expr) ","compile([expr1, expr2, expr3, ...])"],description:"Parse and compile an expression. Returns a an object with a function evaluate([scope]) to evaluate the compiled expression.",examples:['code1 = compile("sqrt(3^2 + 4^2)")',"code1.evaluate() ",'code2 = compile("a * b")',"code2.evaluate({a: 3, b: 4})"],seealso:["parser","parse","evaluate"]},s5={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]},a5={name:"distance",category:"Geometry",syntax:["distance([x1, y1], [x2, y2])","distance([[x1, y1], [x2, y2]])"],description:"Calculates the Euclidean distance between two points.",examples:["distance([0,0], [4,4])","distance([[0,0], [4,4]])"],seealso:[]},o5={name:"intersect",category:"Geometry",syntax:["intersect(expr1, expr2, expr3, expr4)","intersect(expr1, expr2, expr3)"],description:"Computes the intersection point of lines and/or planes.",examples:["intersect([0, 0], [10, 10], [10, 0], [0, 10])","intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])"],seealso:[]},u5={name:"and",category:"Logical",syntax:["x and y","and(x, y)"],description:"Logical and. Test whether two values are both defined with a nonzero/nonempty value.",examples:["true and false","true and true","2 and 4"],seealso:["not","or","xor"]},l5={name:"not",category:"Logical",syntax:["not x","not(x)"],description:"Logical not. Flips the boolean value of given argument.",examples:["not true","not false","not 2","not 0"],seealso:["and","or","xor"]},c5={name:"nullish",category:"Logical",syntax:["x ?? y","nullish(x, y)"],description:"Nullish coalescing operator. Returns the right-hand operand when the left-hand operand is null or undefined, and otherwise returns the left-hand operand.",examples:["null ?? 42","undefined ?? 42","0 ?? 42","false ?? 42","null ?? undefined ?? 42"],seealso:["and","or","not"]},h5={name:"or",category:"Logical",syntax:["x or y","or(x, y)"],description:"Logical or. Test if at least one value is defined with a nonzero/nonempty value.",examples:["true or false","false or false","0 or 4"],seealso:["not","and","xor"]},f5={name:"xor",category:"Logical",syntax:["x xor y","xor(x, y)"],description:"Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.",examples:["true xor false","false xor false","true xor true","0 xor 4"],seealso:["not","and","or"]},d5={name:"mapSlices",category:"Matrix",syntax:["mapSlices(A, dim, callback)"],description:"Generate a matrix one dimension less than A by applying callback to each slice of A along dimension dim.",examples:["A = [[1, 2], [3, 4]]","mapSlices(A, 1, sum)","mapSlices(A, 2, prod)"],seealso:["map","forEach"]},p5={name:"column",category:"Matrix",syntax:["column(x, index)"],description:"Return a column from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","column(A, 1)","column(A, 2)"],seealso:["row","matrixFromColumns"]},m5={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},g5={name:"count",category:"Matrix",syntax:["count(x)"],description:"Count the number of elements of a matrix, array or string.",examples:["a = [1, 2; 3, 4; 5, 6]","count(a)","size(a)",'count("hello world")'],seealso:["size"]},v5={name:"cross",category:"Matrix",syntax:["cross(A, B)"],description:"Calculate the cross product for two vectors in three dimensional space.",examples:["cross([1, 1, 0], [0, 1, 1])","cross([3, -3, 1], [4, 9, 2])","cross([2, 3, 4], [5, 6, 7])"],seealso:["multiply","dot"]},y5={name:"ctranspose",category:"Matrix",syntax:["x'","ctranspose(x)"],description:"Complex Conjugate and Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","ctranspose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},b5={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},x5={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},w5={name:"diff",category:"Matrix",syntax:["diff(arr)","diff(arr, dim)"],description:["Create a new matrix or array with the difference of the passed matrix or array.","Dim parameter is optional and used to indicate the dimension of the array/matrix to apply the difference","If no dimension parameter is passed it is assumed as dimension 0","Dimension is zero-based in javascript and one-based in the parser","Arrays must be 'rectangular' meaning arrays like [1, 2]","If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays"],examples:["A = [1, 2, 4, 7, 0]","diff(A)","diff(A, 1)","B = [[1, 2], [3, 4]]","diff(B)","diff(B, 1)","diff(B, 2)","diff(B, bignumber(2))","diff([[1, 2], matrix([3, 4])], 2)"],seealso:["subtract","partitionSelect"]},S5={name:"dot",category:"Matrix",syntax:["dot(A, B)","A * B"],description:"Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn",examples:["dot([2, 4, 1], [2, 2, 3])","[2, 4, 1] * [2, 2, 3]"],seealso:["multiply","cross"]},N5={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and optionally eigenvectors of a square matrix",examples:["eigs([[5, 2.3], [2.3, 1]])","eigs([[1, 2, 3], [4, 5, 6], [7, 8, 9]], { precision: 1e-6, eigenvectors: false })"],seealso:["inv"]},C5={name:"filter",category:"Matrix",syntax:["filter(x, test)"],description:"Filter items in a matrix.",examples:["isPositive(x) = x > 0","filter([6, -2, -1, 4, 3], isPositive)","filter([6, -2, 0, 1, 0], x != 0)"],seealso:["sort","map","forEach"]},D5={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]},A5={name:"forEach",category:"Matrix",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["numberOfPets = {}","addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;",'forEach(["Dog","Cat","Cat"], addPet)',"numberOfPets"],seealso:["map","sort","filter"]},E5={name:"getMatrixDataType",category:"Matrix",syntax:["getMatrixDataType(x)"],description:'Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".',examples:["getMatrixDataType([1, 2, 3])","getMatrixDataType([[5 cm], [2 inch]])",'getMatrixDataType([1, "text"])',"getMatrixDataType([1, bignumber(4)])"],seealso:["matrix","sparse","typeOf"]},M5={name:"identity",category:"Matrix",syntax:["identity(n)","identity(m, n)","identity([m, n])"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["identity(3)","identity(3, 5)","a = [1, 2, 3; 4, 5, 6]","identity(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},T5={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","identity","ones","range","size","squeeze","subset","trace","transpose","zeros"]},F5={name:"pinv",category:"Matrix",syntax:["pinv(x)"],description:"Calculate the Moore–Penrose inverse of a matrix",examples:["pinv([1, 2; 3, 4])","pinv([[1, 0], [0, 1], [0, 1]])","pinv(4)"],seealso:["inv"]},_5={name:"kron",category:"Matrix",syntax:["kron(x, y)"],description:"Calculates the Kronecker product of 2 matrices or vectors.",examples:["kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])","kron([1,1], [2,3,4])"],seealso:["multiply","dot","cross"]},O5={name:"map",category:"Matrix",syntax:["map(x, callback)","map(x, y, ..., callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array or the matrices/arrays.",examples:["map([1, 2, 3], square)","map([1, 2], [3, 4], f(a,b) = a + b)"],seealso:["filter","forEach"]},B5={name:"matrixFromColumns",category:"Matrix",syntax:["matrixFromColumns(...arr)","matrixFromColumns(row1, row2)","matrixFromColumns(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual columns.",examples:["matrixFromColumns([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromRows","matrixFromFunction","zeros"]},k5={name:"matrixFromFunction",category:"Matrix",syntax:["matrixFromFunction(size, fn)","matrixFromFunction(size, fn, format)","matrixFromFunction(size, fn, format, datatype)","matrixFromFunction(size, format, fn)","matrixFromFunction(size, format, datatype, fn)"],description:"Create a matrix by evaluating a generating function at each index.",examples:["f(I) = I[1] - I[2]","matrixFromFunction([3,3], f)","g(I) = I[1] - I[2] == 1 ? 4 : 0",'matrixFromFunction([100, 100], "sparse", g)',"matrixFromFunction([5], random)"],seealso:["matrix","matrixFromRows","matrixFromColumns","zeros"]},P5={name:"matrixFromRows",category:"Matrix",syntax:["matrixFromRows(...arr)","matrixFromRows(row1, row2)","matrixFromRows(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual rows.",examples:["matrixFromRows([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromColumns","matrixFromFunction","zeros"]},z5={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","identity","inv","range","size","squeeze","subset","trace","transpose","zeros"]},R5={name:"partitionSelect",category:"Matrix",syntax:["partitionSelect(x, k)","partitionSelect(x, k, compare)"],description:"Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.",examples:["partitionSelect([5, 10, 1], 2)",'partitionSelect(["C", "B", "A", "D"], 1, compareText)',"arr = [5, 2, 1]","partitionSelect(arr, 0) # returns 1, arr is now: [1, 2, 5]","arr","partitionSelect(arr, 1, 'desc') # returns 2, arr is now: [5, 2, 1]","arr"],seealso:["sort"]},L5={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"range(1m, 1m, 3m)","a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","identity","inv","ones","size","squeeze","subset","trace","transpose","zeros"]},I5={name:"reshape",category:"Matrix",syntax:["reshape(x, sizes)"],description:"Reshape a multi dimensional array to fit the specified dimensions.",examples:["reshape([1, 2, 3, 4, 5, 6], [2, 3])","reshape([[1, 2], [3, 4]], [1, 4])","reshape([[1, 2], [3, 4]], [4])","reshape([1, 2, 3, 4], [-1, 2])"],seealso:["size","squeeze","resize"]},$5={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze","reshape"]},q5={name:"rotate",category:"Matrix",syntax:["rotate(w, theta)","rotate(w, theta, v)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotate([1, 0], pi / 2)",'rotate(matrix([1, 0]), unit("35deg"))','rotate([1, 0, 0], unit("90deg"), [0, 0, 1])','rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],seealso:["matrix","rotationMatrix"]},H5={name:"rotationMatrix",category:"Matrix",syntax:["rotationMatrix(theta)","rotationMatrix(theta, v)","rotationMatrix(theta, v, format)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotationMatrix(pi / 2)",'rotationMatrix(unit("45deg"), [0, 0, 1])','rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],seealso:["cos","sin"]},U5={name:"row",category:"Matrix",syntax:["row(x, index)"],description:"Return a row from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","row(A, 1)","row(A, 2)"],seealso:["column","matrixFromRows"]},V5={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","count","det","diag","identity","inv","ones","range","squeeze","subset","trace","transpose","zeros"]},W5={name:"sort",category:"Matrix",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"], "natural")',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]},j5={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","identity","inv","ones","range","size","subset","trace","transpose","zeros"]},G5={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation `l:u`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]","f[[1,2], [1,3]] = [9, 10; 11, 12]","f"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","trace","transpose","zeros"]},X5={name:"trace",category:"Matrix",syntax:["trace(A)"],description:"Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.",examples:["A = [1, 2, 3; -1, 2, 3; 2, 0, 3]","trace(A)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","transpose","zeros"]},Y5={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},J5={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose"]},Z5={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional Fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]},Q5={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse Fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]},K5={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["combinationsWithRep","permutations","factorial"]},ez={name:"combinationsWithRep",category:"Probability",syntax:["combinationsWithRep(n, k)"],description:"Compute the number of combinations of n items taken k at a time with replacements.",examples:["combinationsWithRep(7, 5)"],seealso:["combinations","permutations","factorial"]},tz={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5 * 4 * 3 * 2 * 1","3!"],seealso:["combinations","combinationsWithRep","permutations","gamma"]},rz={name:"gamma",category:"Probability",syntax:["gamma(n)"],description:"Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.",examples:["gamma(4)","3!","gamma(1/2)","sqrt(pi)"],seealso:["factorial"]},iz={name:"lgamma",category:"Probability",syntax:["lgamma(n)"],description:"Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.",examples:["lgamma(4)","lgamma(1/2)","lgamma(i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]},nz={name:"kldivergence",category:"Probability",syntax:["kldivergence(x, y)"],description:"Calculate the Kullback-Leibler (KL) divergence between two distributions.",examples:["kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])"],seealso:[]},sz={name:"multinomial",category:"Probability",syntax:["multinomial(A)"],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:["multinomial([1, 2, 1])"],seealso:["combinations","factorial"]},az={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","combinationsWithRep","factorial"]},oz={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)","pickRandom(array, number)","pickRandom(array, weights)","pickRandom(array, number, weights)","pickRandom(array, weights, number)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])","pickRandom([1, 3, 1, 6], 2)","pickRandom([1, 3, 1, 6], [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)"],seealso:["random","randomInt"]},uz={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["pickRandom","randomInt"]},lz={name:"randomInt",category:"Probability",syntax:["randomInt(max)","randomInt(min, max)","randomInt(size)","randomInt(size, max)","randomInt(size, min, max)"],description:"Return a random integer number",examples:["randomInt(10, 20)","randomInt([2, 3], 10)"],seealso:["pickRandom","random"]},cz={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compareNatural","compareText"]},hz={name:"compareNatural",category:"Relational",syntax:["compareNatural(x, y)"],description:"Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compareNatural(2, 3)","compareNatural(3, 2)","compareNatural(2, 2)","compareNatural(5cm, 40mm)",'compareNatural("2", "10")',"compareNatural(2 + 3i, 2 + 4i)","compareNatural([1, 2, 4], [1, 2, 3])","compareNatural([1, 5], [1, 2, 3])","compareNatural([1, 2], [1, 2])","compareNatural({a: 2}, {a: 4})"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare","compareText"]},fz={name:"compareText",category:"Relational",syntax:["compareText(x, y)"],description:"Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:['compareText("B", "A")','compareText("A", "B")','compareText("A", "A")','compareText("2", "10")','compare("2", "10")',"compare(2, 10)",'compareNatural("2", "10")','compareText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural"]},dz={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["deepEqual([1,3,4], [1,3,4])","deepEqual([1,3,4], [1,3])"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]},pz={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual","equalText"]},mz={name:"equalText",category:"Relational",syntax:["equalText(x, y)"],description:"Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.",examples:['equalText("Hello", "Hello")','equalText("a", "A")','equal("2e3", "2000")','equalText("2e3", "2000")','equalText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural","compareText","equal"]},gz={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not. Comparing a value with NaN returns false.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]},vz={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 >= 1+1","2 > 1+1","a = 3.2","b = 6-2.8","(a >= b)"],seealso:["equal","unequal","smallerEq","smaller","compare"]},yz={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not. Comparing a value with NaN returns false.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]},bz={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 <= 1+1","2 < 1+1","a = 3.2","b = 6-2.8","(a <= b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]},xz={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]},wz={name:"setCartesian",category:"Set",syntax:["setCartesian(set1, set2)"],description:"Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.",examples:["setCartesian([1, 2], [3, 4])"],seealso:["setUnion","setIntersect","setDifference","setPowerset"]},Sz={name:"setDifference",category:"Set",syntax:["setDifference(set1, set2)"],description:"Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setDifference([1, 2, 3, 4], [3, 4, 5, 6])","setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setSymDifference"]},Nz={name:"setDistinct",category:"Set",syntax:["setDistinct(set)"],description:"Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setDistinct([1, 1, 1, 2, 2, 3])"],seealso:["setMultiplicity"]},Cz={name:"setIntersect",category:"Set",syntax:["setIntersect(set1, set2)"],description:"Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIntersect([1, 2, 3, 4], [3, 4, 5, 6])","setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setDifference"]},Dz={name:"setIsSubset",category:"Set",syntax:["setIsSubset(set1, set2)"],description:"Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIsSubset([1, 2], [3, 4, 5, 6])","setIsSubset([3, 4], [3, 4, 5, 6])"],seealso:["setUnion","setIntersect","setDifference"]},Az={name:"setMultiplicity",category:"Set",syntax:["setMultiplicity(element, set)"],description:"Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setMultiplicity(1, [1, 2, 2, 4])","setMultiplicity(2, [1, 2, 2, 4])"],seealso:["setDistinct","setSize"]},Ez={name:"setPowerset",category:"Set",syntax:["setPowerset(set)"],description:"Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setPowerset([1, 2, 3])"],seealso:["setCartesian"]},Mz={name:"setSize",category:"Set",syntax:["setSize(set)","setSize(set, unique)"],description:'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',examples:["setSize([1, 2, 2, 4])","setSize([1, 2, 2, 4], true)"],seealso:["setUnion","setIntersect","setDifference"]},Tz={name:"setSymDifference",category:"Set",syntax:["setSymDifference(set1, set2)"],description:"Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])","setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setDifference"]},Fz={name:"setUnion",category:"Set",syntax:["setUnion(set1, set2)"],description:"Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setUnion([1, 2, 3, 4], [3, 4, 5, 6])","setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setIntersect","setDifference"]},_z={name:"zpk2tf",category:"Signal",syntax:["zpk2tf(z, p, k)"],description:"Compute the transfer function of a zero-pole-gain model.",examples:["zpk2tf([1, 2], [-1, -2], 1)","zpk2tf([1, 2], [-1, -2])","zpk2tf([1 - 3i, 2 + 2i], [-1, -2])"],seealso:[]},Oz={name:"freqz",category:"Signal",syntax:["freqz(b, a)","freqz(b, a, w)"],description:"Calculates the frequency response of a filter given its numerator and denominator coefficients.",examples:["freqz([1, 2], [1, 2, 3])","freqz([1, 2], [1, 2, 3], [0, 1])","freqz([1, 2], [1, 2, 3], 512)"],seealso:[]},Bz={name:"erf",category:"Special",syntax:["erf(x)"],description:"Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x",examples:["erf(0.2)","erf(-0.5)","erf(4)"],seealso:[]},kz={name:"zeta",category:"Special",syntax:["zeta(s)"],description:"Compute the Riemann Zeta Function using an infinite series and Riemann's Functional Equation for the entire complex plane",examples:["zeta(0.2)","zeta(-0.5)","zeta(4)"],seealso:[]},Pz={name:"mad",category:"Statistics",syntax:["mad(a, b, c, ...)","mad(A)"],description:"Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.",examples:["mad(10, 20, 30)","mad([1, 2, 3])"],seealso:["mean","median","std","abs"]},zz={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dimension)"],description:"Compute the maximum value of a list of values. If any NaN values are found, the function yields the last NaN in the input.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3])","max([2, 5; 4, 3], 1)","max([2, 5; 4, 3], 2)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","variance"]},Rz={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dimension)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3])","mean([2, 5; 4, 3], 1)","mean([2, 5; 4, 3], 2)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","variance"]},Lz={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","variance","quantileSeq"]},Iz={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dimension)"],description:"Compute the minimum value of a list of values. If any NaN values are found, the function yields the last NaN in the input.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3])","min([2, 5; 4, 3], 1)","min([2, 5; 4, 3], 2)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","variance"]},$z={name:"mode",category:"Statistics",syntax:["mode(a, b, c, ...)","mode(A)","mode(A, a, b, B, c, ...)"],description:"Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.",examples:["mode(2, 1, 4, 3, 1)","mode([1, 2.7, 3.2, 4, 2.7])","mode(1, 4, 6, 1, 6)"],seealso:["max","mean","min","median","prod","std","sum","variance"]},qz={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","variance"]},Hz={name:"quantileSeq",category:"Statistics",syntax:["quantileSeq(A, prob[, sorted])","quantileSeq(A, [prob1, prob2, ...][, sorted])","quantileSeq(A, N[, sorted])"],description:`Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber.
59
59
 
60
- In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.`,examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]},Uz={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, dimension)","std(A, normalization)","std(A, dimension, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]},Vz={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]},Wz={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)","sum(A, dimension)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","variance"]},jz={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, dimension)","variance(A, normalization)","variance(A, dimension, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]},Gz={name:"corr",category:"Statistics",syntax:["corr(A,B)"],description:"Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.",examples:["corr([2, 4, 6, 8],[1, 2, 3, 6])","corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))"],seealso:["max","mean","min","median","min","prod","std","sum"]},Xz={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]},Yz={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]},Jz={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]},Zz={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the inverse hyperbolic tangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]},Qz={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]},Kz={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the inverse hyperbolic cosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},eR={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]},tR={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},rR={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]},iR={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]},nR={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]},sR={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]},aR={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]},oR={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]},uR={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},lR={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]},cR={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]},hR={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]},fR={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]},dR={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]},pR={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]},mR={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]},gR={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},vR={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]},yR={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]},bR={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]},xR={name:"toBest",category:"Units",syntax:["toBest(x)","toBest(x, unitList)","toBest(x, unitList, options)"],description:"Converts to the most appropriate display unit.",examples:['toBest(unit(5000, "m"))','toBest(unit(3500000, "W"))','toBest(unit(0.000000123, "A"))','toBest(unit(10, "m"), "cm")','toBest(unit(10, "m"), "mm,km", {offset: 1.5})'],seealso:[]},wR={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},SR={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables, and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]},NR={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]},CR={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]},DR={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},AR={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]},ER={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]},MR={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]},TR={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]},FR={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},_R={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},OR={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]},BR={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "bigint")','numeric("4", "BigNumber")','numeric("4", "Fraction")','numeric(4, "Fraction")','numeric(fraction(2, 5), "number")'],seealso:["number","bigint","fraction","bignumber","string","format"]},kR={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},PR={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $1, $2, $3", [6, 9, 4])'],seealso:["format"]},zR={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]},RR={name:"solveODE",category:"Numeric",syntax:["solveODE(func, tspan, y0)","solveODE(func, tspan, y0, options)"],description:"Numerical Integration of Ordinary Differential Equations.",examples:["f(t,y) = y","tspan = [0, 4]","solveODE(f, tspan, 1)","solveODE(f, tspan, [1, 2])",'solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })'],seealso:["derivative","simplifyCore"]},OS={bignumber:wk,bigint:Sk,boolean:Nk,complex:Ck,createUnit:Dk,fraction:Ak,index:Ek,matrix:Mk,number:Tk,sparse:Fk,splitUnit:_k,string:Ok,unit:Bk,e:FS,E:FS,false:ak,i:ok,Infinity:uk,LN2:ck,LN10:lk,LOG2E:fk,LOG10E:hk,NaN:dk,null:pk,pi:_S,PI:_S,phi:mk,SQRT1_2:gk,SQRT2:vk,tau:yk,true:bk,version:xk,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant. Deprecated in favor of coulombConstant",examples:["coulombConstant"]},coulombConstant:{description:"Coulomb's constant",examples:["coulombConstant"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Bohr magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Bohr radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:Rk,lsolve:Ik,lsolveAll:$k,lup:qk,lusolve:Hk,leafCount:Lk,polynomialRoot:Uk,resolve:jk,simplify:Gk,simplifyConstant:Xk,simplifyCore:Yk,symbolicEqual:Zk,rationalize:Wk,slu:Jk,usolve:Qk,usolveAll:Kk,qr:Vk,abs:eP,add:tP,cbrt:rP,ceil:iP,cube:nP,divide:sP,dotDivide:aP,dotMultiply:oP,dotPow:uP,exp:lP,expm:cP,expm1:hP,fix:fP,floor:dP,gcd:pP,hypot:mP,lcm:vP,log:yP,log2:wP,log1p:xP,log10:bP,mod:SP,multiply:NP,norm:CP,nthRoot:DP,nthRoots:AP,pow:EP,round:MP,sign:TP,sqrt:FP,sqrtm:_P,square:PP,subtract:zP,unaryMinus:RP,unaryPlus:LP,xgcd:IP,invmod:gP,bitAnd:$P,bitNot:qP,bitOr:HP,bitXor:UP,leftShift:VP,rightArithShift:WP,rightLogShift:jP,bellNumbers:GP,catalan:XP,composition:YP,stirlingS2:JP,config:kk,import:Pk,typed:zk,arg:ZP,conj:QP,re:e5,im:KP,evaluate:t5,help:s5,parse:i5,parser:r5,compile:n5,distance:a5,intersect:o5,and:u5,not:l5,nullish:c5,or:h5,xor:f5,mapSlices:d5,concat:m5,count:g5,cross:v5,column:p5,ctranspose:y5,det:b5,diag:x5,diff:w5,dot:S5,getMatrixDataType:E5,identity:M5,filter:C5,flatten:D5,forEach:A5,inv:T5,pinv:F5,eigs:N5,kron:_5,matrixFromFunction:k5,matrixFromRows:P5,matrixFromColumns:B5,map:O5,ones:z5,partitionSelect:R5,range:L5,resize:$5,reshape:I5,rotate:q5,rotationMatrix:H5,row:U5,size:V5,sort:W5,squeeze:j5,subset:G5,trace:X5,transpose:Y5,zeros:J5,fft:Z5,ifft:Q5,sylvester:OP,schur:BP,lyap:kP,solveODE:RR,combinations:K5,combinationsWithRep:ez,factorial:tz,gamma:rz,kldivergence:nz,lgamma:iz,multinomial:sz,permutations:az,pickRandom:oz,random:uz,randomInt:lz,compare:cz,compareNatural:hz,compareText:fz,deepEqual:dz,equal:pz,equalText:mz,larger:gz,largerEq:vz,smaller:yz,smallerEq:bz,unequal:xz,setCartesian:wz,setDifference:Sz,setDistinct:Nz,setIntersect:Cz,setIsSubset:Dz,setMultiplicity:Az,setPowerset:Ez,setSize:Mz,setSymDifference:Tz,setUnion:Fz,zpk2tf:_z,freqz:Oz,erf:Bz,zeta:kz,cumsum:Vz,mad:Pz,max:zz,mean:Rz,median:Lz,min:Iz,mode:$z,prod:qz,quantileSeq:Hz,std:Uz,sum:Wz,variance:jz,corr:Gz,acos:Xz,acosh:Yz,acot:Jz,acoth:Zz,acsc:Qz,acsch:Kz,asec:eR,asech:tR,asin:rR,asinh:iR,atan:nR,atanh:aR,atan2:sR,cos:oR,cosh:uR,cot:lR,coth:cR,csc:hR,csch:fR,sec:dR,sech:pR,sin:mR,sinh:gR,tan:vR,tanh:yR,to:bR,toBest:xR,clone:SR,format:NR,bin:wR,oct:kR,hex:DR,isNaN:ER,isInteger:AR,isNegative:MR,isNumeric:TR,hasNumericValue:CR,isPositive:FR,isPrime:_R,isZero:OR,print:PR,typeOf:zR,numeric:BR},BS="help",LR=["typed","mathWithTransform","Help"],Wf=R(BS,LR,n=>{var{typed:e,mathWithTransform:t,Help:r}=n;return e(BS,{any:function(s){var a,o=s;if(typeof s!="string"){for(a in t)if(Te(t,a)&&s===t[a]){o=a;break}}var l=_r(OS,o);if(!l){var u=typeof o=="function"?o.name:o;throw new Error('No documentation found on "'+u+'"')}return new r(l)}})}),kS="chain",IR=["typed","Chain"],jf=R(kS,IR,n=>{var{typed:e,Chain:t}=n;return e(kS,{"":function(){return new t},any:function(i){return new t(i)}})}),PS="det",$R=["typed","matrix","subtractScalar","multiply","divideScalar","isZero","unaryMinus"],Gf=R(PS,$R,n=>{var{typed:e,matrix:t,subtractScalar:r,multiply:i,divideScalar:s,isZero:a,unaryMinus:o}=n;return e(PS,{any:function(c){return $e(c)},"Array | Matrix":function(c){var h;switch(Re(c)?h=c.size():Array.isArray(c)?(c=t(c),h=c.size()):h=[],h.length){case 0:return $e(c);case 1:if(h[0]===1)return $e(c.valueOf()[0]);if(h[0]===0)return 1;throw new RangeError("Matrix must be square (size: "+at(h)+")");case 2:{var f=h[0],d=h[1];if(f===d)return l(c.clone().valueOf(),f);if(d===0)return 1;throw new RangeError("Matrix must be square (size: "+at(h)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+at(h)+")")}}});function l(u,c,h){if(c===1)return $e(u[0][0]);if(c===2)return r(i(u[0][0],u[1][1]),i(u[1][0],u[0][1]));for(var f=!1,d=new Array(c).fill(0).map((N,D)=>D),p=0;p<c;p++){var m=d[p];if(a(u[m][p])){var y=void 0;for(y=p+1;y<c;y++)if(!a(u[d[y]][p])){m=d[y],d[y]=d[p],d[p]=m,f=!f;break}if(y===c)return u[m][p]}for(var v=u[m][p],S=p===0?1:u[d[p-1]][p-1],g=p+1;g<c;g++)for(var b=d[g],w=p+1;w<c;w++)u[b][w]=s(r(i(u[b][w],v),i(u[b][p],u[m][w])),S)}var x=u[d[c-1]][c-1];return f?o(x):x}}),zS="inv",qR=["typed","matrix","divideScalar","addScalar","multiply","unaryMinus","det","identity","abs"],Xf=R(zS,qR,n=>{var{typed:e,matrix:t,divideScalar:r,addScalar:i,multiply:s,unaryMinus:a,det:o,identity:l,abs:u}=n;return e(zS,{"Array | Matrix":function(f){var d=Re(f)?f.size():Ge(f);switch(d.length){case 1:if(d[0]===1)return Re(f)?t([r(1,f.valueOf()[0])]):[r(1,f[0])];throw new RangeError("Matrix must be square (size: "+at(d)+")");case 2:{var p=d[0],m=d[1];if(p===m)return Re(f)?t(c(f.valueOf(),p,m),f.storage()):c(f,p,m);throw new RangeError("Matrix must be square (size: "+at(d)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+at(d)+")")}},any:function(f){return r(1,f)}});function c(h,f,d){var p,m,y,v,S;if(f===1){if(v=h[0][0],v===0)throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,v)]]}else if(f===2){var g=o(h);if(g===0)throw Error("Cannot calculate inverse, determinant is zero");return[[r(h[1][1],g),r(a(h[0][1]),g)],[r(a(h[1][0]),g),r(h[0][0],g)]]}else{var b=h.concat();for(p=0;p<f;p++)b[p]=b[p].concat();for(var w=l(f).valueOf(),x=0;x<d;x++){var N=u(b[x][x]),D=x;for(p=x+1;p<f;)u(b[p][x])>N&&(N=u(b[p][x]),D=p),p++;if(N===0)throw Error("Cannot calculate inverse, determinant is zero");p=D,p!==x&&(S=b[x],b[x]=b[p],b[p]=S,S=w[x],w[x]=w[p],w[p]=S);var C=b[x],A=w[x];for(p=0;p<f;p++){var E=b[p],F=w[p];if(p!==x){if(E[x]!==0){for(y=r(a(E[x]),C[x]),m=x;m<d;m++)E[m]=i(E[m],s(y,C[m]));for(m=0;m<d;m++)F[m]=i(F[m],s(y,A[m]))}}else{for(y=C[x],m=x;m<d;m++)E[m]=r(E[m],y);for(m=0;m<d;m++)F[m]=r(F[m],y)}}}return w}}}),RS="pinv",HR=["typed","matrix","inv","deepEqual","equal","dotDivide","dot","ctranspose","divideScalar","multiply","add","Complex"],Yf=R(RS,HR,n=>{var{typed:e,matrix:t,inv:r,deepEqual:i,equal:s,dotDivide:a,dot:o,ctranspose:l,divideScalar:u,multiply:c,add:h,Complex:f}=n;return e(RS,{"Array | Matrix":function(g){var b=Re(g)?g.size():Ge(g);switch(b.length){case 1:return v(g)?l(g):b[0]===1?r(g):a(l(g),o(g,g));case 2:{if(v(g))return l(g);var w=b[0],x=b[1];if(w===x)try{return r(g)}catch(N){if(!(N instanceof Error&&N.message.match(/Cannot calculate inverse, determinant is zero/)))throw N}return Re(g)?t(d(g.valueOf(),w,x),g.storage()):d(g,w,x)}default:throw new RangeError("Matrix must be two dimensional (size: "+at(b)+")")}},any:function(g){return s(g,0)?$e(g):u(1,g)}});function d(S,g,b){var{C:w,F:x}=m(S,g,b),N=c(r(c(l(w),w)),l(w)),D=c(l(x),r(c(x,l(x))));return c(D,N)}function p(S,g,b){for(var w=$e(S),x=0,N=0;N<g;N++){if(b<=x)return w;for(var D=N;y(w[D][x]);)if(D++,g===D&&(D=N,x++,b===x))return w;[w[D],w[N]]=[w[N],w[D]];for(var C=w[N][x],A=0;A<b;A++)w[N][A]=a(w[N][A],C);for(var E=0;E<g;E++)if(E!==N){C=w[E][x];for(var F=0;F<b;F++)w[E][F]=h(w[E][F],c(-1,c(C,w[N][F])))}x++}return w}function m(S,g,b){var w=p(S,g,b),x=S.map((D,C)=>D.filter((A,E)=>E<g&&!y(o(w[E],w[E])))),N=w.filter((D,C)=>!y(o(w[C],w[C])));return{C:x,F:N}}function y(S){return s(h(S,f(1,1)),h(0,f(1,1)))}function v(S){return i(h(S,f(1,1)),h(c(S,0),f(1,1)))}});function UR(n){var{addScalar:e,subtract:t,flatten:r,multiply:i,multiplyScalar:s,divideScalar:a,sqrt:o,abs:l,bignumber:u,diag:c,size:h,reshape:f,inv:d,qr:p,usolve:m,usolveAll:y,equal:v,complex:S,larger:g,smaller:b,matrixFromColumns:w,dot:x}=n;function N(_,V,z,de){var ae=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,oe=D(_,V,z,de,ae);C(_,V,z,de,ae,oe);var{values:$,C:H}=A(_,V,z,de,ae);if(ae){var J=E(_,V,H,oe,$,z,de);return{values:$,eigenvectors:J}}return{values:$}}function D(_,V,z,de,ae){var oe=de==="BigNumber",$=de==="Complex",H=oe?u(0):0,J=oe?u(1):$?S(1):1,K=oe?u(1):1,te=oe?u(10):2,fe=s(te,te),le;ae&&(le=Array(V).fill(J));for(var Se=!1;!Se;){Se=!0;for(var _e=0;_e<V;_e++){for(var Be=H,Ee=H,Pe=0;Pe<V;Pe++)_e!==Pe&&(Be=e(Be,l(_[Pe][_e])),Ee=e(Ee,l(_[_e][Pe])));if(!v(Be,0)&&!v(Ee,0)){for(var q=K,Z=Be,ne=a(Ee,te),P=s(Ee,te);b(Z,ne);)Z=s(Z,fe),q=s(q,te);for(;g(Z,P);)Z=a(Z,fe),q=a(q,te);var W=b(a(e(Z,Ee),q),s(e(Be,Ee),.95));if(W){Se=!1;for(var Q=a(1,q),re=0;re<V;re++)_e!==re&&(_[_e][re]=s(_[_e][re],Q),_[re][_e]=s(_[re][_e],q));ae&&(le[_e]=s(le[_e],Q))}}}}return ae?c(le):null}function C(_,V,z,de,ae,oe){var $=de==="BigNumber",H=de==="Complex",J=$?u(0):H?S(0):0;$&&(z=u(z));for(var K=0;K<V-2;K++){for(var te=0,fe=J,le=K+1;le<V;le++){var Se=_[le][K];b(l(fe),l(Se))&&(fe=Se,te=le)}if(!b(l(fe),z)){if(te!==K+1){var _e=_[te];_[te]=_[K+1],_[K+1]=_e;for(var Be=0;Be<V;Be++){var Ee=_[Be][te];_[Be][te]=_[Be][K+1],_[Be][K+1]=Ee}if(ae){var Pe=oe[te];oe[te]=oe[K+1],oe[K+1]=Pe}}for(var q=K+2;q<V;q++){var Z=a(_[q][K],fe);if(Z!==0){for(var ne=0;ne<V;ne++)_[q][ne]=t(_[q][ne],s(Z,_[K+1][ne]));for(var P=0;P<V;P++)_[P][K+1]=e(_[P][K+1],s(Z,_[P][q]));if(ae)for(var W=0;W<V;W++)oe[q][W]=t(oe[q][W],s(Z,oe[K+1][W]))}}}}return oe}function A(_,V,z,de,ae){var oe=de==="BigNumber",$=de==="Complex",H=oe?u(1):$?S(1):1;oe&&(z=u(z));for(var J=$e(_),K=[],te=V,fe=[],le=ae?c(Array(V).fill(H)):void 0,Se=ae?c(Array(te).fill(H)):void 0,_e=0;_e<=100;){_e+=1;for(var Be=J[te-1][te-1],Ee=0;Ee<te;Ee++)J[Ee][Ee]=t(J[Ee][Ee],Be);var{Q:Pe,R:q}=p(J);J=i(q,Pe);for(var Z=0;Z<te;Z++)J[Z][Z]=e(J[Z][Z],Be);if(ae&&(Se=i(Se,Pe)),te===1||b(l(J[te-1][te-2]),z)){_e=0,K.push(J[te-1][te-1]),ae&&(fe.unshift([[1]]),k(Se,V),le=i(le,Se),te>1&&(Se=c(Array(te-1).fill(H)))),te-=1,J.pop();for(var ne=0;ne<te;ne++)J[ne].pop()}else if(te===2||b(l(J[te-2][te-3]),z)){_e=0;var P=F(J[te-2][te-2],J[te-2][te-1],J[te-1][te-2],J[te-1][te-1]);K.push(...P),ae&&(fe.unshift(O(J[te-2][te-2],J[te-2][te-1],J[te-1][te-2],J[te-1][te-1],P[0],P[1],z,de)),k(Se,V),le=i(le,Se),te>2&&(Se=c(Array(te-2).fill(H)))),te-=2,J.pop(),J.pop();for(var W=0;W<te;W++)J[W].pop(),J[W].pop()}if(te===0)break}if(K.sort((se,ce)=>+t(l(se),l(ce))),_e>100){var Q=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+K.join(", "));throw Q.values=K,Q.vectors=[],Q}var re=ae?i(le,B(fe,V)):void 0;return{values:K,C:re}}function E(_,V,z,de,ae,oe,$){var H=d(z),J=i(H,_,z),K=$==="BigNumber",te=$==="Complex",fe=K?u(0):te?S(0):0,le=K?u(1):te?S(1):1,Se=[],_e=[];for(var Be of ae){var Ee=T(Se,Be,v);Ee===-1?(Se.push(Be),_e.push(1)):_e[Ee]+=1}for(var Pe=[],q=Se.length,Z=Array(V).fill(fe),ne=c(Array(V).fill(le)),P=function(){var re=Se[W],se=t(J,i(re,ne)),ce=y(se,Z);for(ce.shift();ce.length<_e[W];){var ge=I(se,V,ce,oe,$);if(ge===null)break;ce.push(ge)}var xe=i(d(de),z);ce=ce.map(Ae=>i(xe,Ae)),Pe.push(...ce.map(Ae=>({value:re,vector:r(Ae)})))},W=0;W<q;W++)P();return Pe}function F(_,V,z,de){var ae=e(_,de),oe=t(s(_,de),s(V,z)),$=s(ae,.5),H=s(o(t(s(ae,ae),s(4,oe))),.5);return[e($,H),t($,H)]}function O(_,V,z,de,ae,oe,$,H){var J=H==="BigNumber",K=H==="Complex",te=J?u(0):K?S(0):0,fe=J?u(1):K?S(1):1;if(b(l(z),$))return[[fe,te],[te,fe]];if(g(l(t(ae,oe)),$))return[[t(ae,de),t(oe,de)],[z,z]];var le=t(_,ae),Se=t(de,ae);return b(l(V),$)&&b(l(Se),$)?[[le,fe],[z,te]]:[[V,te],[Se,fe]]}function k(_,V){for(var z=0;z<_.length;z++)_[z].push(...Array(V-_[z].length).fill(0));for(var de=_.length;de<V;de++)_.push(Array(V).fill(0)),_[de][de]=1;return _}function B(_,V){for(var z=[],de=0;de<V;de++)z[de]=Array(V).fill(0);var ae=0;for(var oe of _){for(var $=oe.length,H=0;H<$;H++)for(var J=0;J<$;J++)z[ae+H][ae+J]=oe[H][J];ae+=$}return z}function T(_,V,z){for(var de=0;de<_.length;de++)if(z(_[de],V))return de;return-1}function I(_,V,z,de,ae){for(var oe=ae==="BigNumber"?u(1e3):1e3,$,H=0;H<5;++H){$=U(V,z,ae);try{$=m(_,$)}catch{continue}if(g(Y($),oe))break}if(H>=5)return null;for(H=0;;){var J=m(_,$);if(b(Y(L($,[J])),de))break;if(++H>=10)return null;$=ee(J)}return $}function U(_,V,z){var de=z==="BigNumber",ae=z==="Complex",oe=Array(_).fill(0).map($=>2*Math.random()-1);return de&&(oe=oe.map($=>u($))),ae&&(oe=oe.map($=>S($))),oe=L(oe,V),ee(oe,z)}function L(_,V){var z=h(_);for(var de of V)de=f(de,z),_=t(_,i(a(x(de,_),x(de,de)),de));return _}function Y(_){return l(o(x(_,_)))}function ee(_,V){var z=V==="BigNumber",de=V==="Complex",ae=z?u(1):de?S(1):1;return i(a(ae,Y(_)),_)}return N}function VR(n){var{config:e,addScalar:t,subtract:r,abs:i,atan:s,cos:a,sin:o,multiplyScalar:l,inv:u,bignumber:c,multiply:h,add:f}=n;function d(C,A){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.relTol,F=arguments.length>3?arguments[3]:void 0,O=arguments.length>4?arguments[4]:void 0;if(F==="number")return p(C,E,O);if(F==="BigNumber")return m(C,E,O);throw TypeError("Unsupported data type: "+F)}function p(C,A,E){var F=C.length,O=Math.abs(A/F),k,B;if(E){B=new Array(F);for(var T=0;T<F;T++)B[T]=Array(F).fill(0),B[T][T]=1}for(var I=x(C);Math.abs(I[1])>=Math.abs(O);){var U=I[0][0],L=I[0][1];k=y(C[U][U],C[L][L],C[U][L]),C=w(C,k,U,L),E&&(B=S(B,k,U,L)),I=x(C)}for(var Y=Array(F).fill(0),ee=0;ee<F;ee++)Y[ee]=C[ee][ee];return D($e(Y),B,E)}function m(C,A,E){var F=C.length,O=i(A/F),k,B;if(E){B=new Array(F);for(var T=0;T<F;T++)B[T]=Array(F).fill(0),B[T][T]=1}for(var I=N(C);i(I[1])>=i(O);){var U=I[0][0],L=I[0][1];k=v(C[U][U],C[L][L],C[U][L]),C=b(C,k,U,L),E&&(B=g(B,k,U,L)),I=N(C)}for(var Y=Array(F).fill(0),ee=0;ee<F;ee++)Y[ee]=C[ee][ee];return D($e(Y),B,E)}function y(C,A,E){var F=A-C;return Math.abs(F)<=e.relTol?Math.PI/4:.5*Math.atan(2*E/(A-C))}function v(C,A,E){var F=r(A,C);return i(F)<=e.relTol?c(-1).acos().div(4):l(.5,s(h(2,E,u(F))))}function S(C,A,E,F){for(var O=C.length,k=Math.cos(A),B=Math.sin(A),T=Array(O).fill(0),I=Array(O).fill(0),U=0;U<O;U++)T[U]=k*C[U][E]-B*C[U][F],I[U]=B*C[U][E]+k*C[U][F];for(var L=0;L<O;L++)C[L][E]=T[L],C[L][F]=I[L];return C}function g(C,A,E,F){for(var O=C.length,k=a(A),B=o(A),T=Array(O).fill(c(0)),I=Array(O).fill(c(0)),U=0;U<O;U++)T[U]=r(l(k,C[U][E]),l(B,C[U][F])),I[U]=t(l(B,C[U][E]),l(k,C[U][F]));for(var L=0;L<O;L++)C[L][E]=T[L],C[L][F]=I[L];return C}function b(C,A,E,F){for(var O=C.length,k=c(a(A)),B=c(o(A)),T=l(k,k),I=l(B,B),U=Array(O).fill(c(0)),L=Array(O).fill(c(0)),Y=h(c(2),k,B,C[E][F]),ee=t(r(l(T,C[E][E]),Y),l(I,C[F][F])),_=f(l(I,C[E][E]),Y,l(T,C[F][F])),V=0;V<O;V++)U[V]=r(l(k,C[E][V]),l(B,C[F][V])),L[V]=t(l(B,C[E][V]),l(k,C[F][V]));C[E][E]=ee,C[F][F]=_,C[E][F]=c(0),C[F][E]=c(0);for(var z=0;z<O;z++)z!==E&&z!==F&&(C[E][z]=U[z],C[z][E]=U[z],C[F][z]=L[z],C[z][F]=L[z]);return C}function w(C,A,E,F){for(var O=C.length,k=Math.cos(A),B=Math.sin(A),T=k*k,I=B*B,U=Array(O).fill(0),L=Array(O).fill(0),Y=T*C[E][E]-2*k*B*C[E][F]+I*C[F][F],ee=I*C[E][E]+2*k*B*C[E][F]+T*C[F][F],_=0;_<O;_++)U[_]=k*C[E][_]-B*C[F][_],L[_]=B*C[E][_]+k*C[F][_];C[E][E]=Y,C[F][F]=ee,C[E][F]=0,C[F][E]=0;for(var V=0;V<O;V++)V!==E&&V!==F&&(C[E][V]=U[V],C[V][E]=U[V],C[F][V]=L[V],C[V][F]=L[V]);return C}function x(C){for(var A=C.length,E=0,F=[0,1],O=0;O<A;O++)for(var k=O+1;k<A;k++)Math.abs(E)<Math.abs(C[O][k])&&(E=Math.abs(C[O][k]),F=[O,k]);return[F,E]}function N(C){for(var A=C.length,E=0,F=[0,1],O=0;O<A;O++)for(var k=O+1;k<A;k++)i(E)<i(C[O][k])&&(E=i(C[O][k]),F=[O,k]);return[F,E]}function D(C,A,E){var F=C.length,O=Array(F),k;if(E){k=Array(F);for(var B=0;B<F;B++)k[B]=Array(F)}for(var T=0;T<F;T++){for(var I=0,U=C[0],L=0;L<C.length;L++)i(C[L])<i(U)&&(I=L,U=C[I]);if(O[T]=C.splice(I,1)[0],E)for(var Y=0;Y<F;Y++)k[T][Y]=A[Y][I],A[Y].splice(I,1)}if(!E)return{values:O};var ee=k.map((_,V)=>({value:O[V],vector:_}));return{values:O,eigenvectors:ee}}return d}var WR="eigs",jR=["config","typed","matrix","addScalar","equal","subtract","abs","atan","cos","sin","multiplyScalar","divideScalar","inv","bignumber","multiply","add","larger","column","flatten","number","complex","sqrt","diag","size","reshape","qr","usolve","usolveAll","im","re","smaller","matrixFromColumns","dot"],Jf=R(WR,jR,n=>{var{config:e,typed:t,matrix:r,addScalar:i,subtract:s,equal:a,abs:o,atan:l,cos:u,sin:c,multiplyScalar:h,divideScalar:f,inv:d,bignumber:p,multiply:m,add:y,larger:v,column:S,flatten:g,number:b,complex:w,sqrt:x,diag:N,size:D,reshape:C,qr:A,usolve:E,usolveAll:F,im:O,re:k,smaller:B,matrixFromColumns:T,dot:I}=n,U=VR({config:e,addScalar:i,subtract:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:h,inv:d,bignumber:p,multiply:m,add:y}),L=UR({addScalar:i,subtract:s,multiply:m,multiplyScalar:h,flatten:g,divideScalar:f,sqrt:x,abs:o,bignumber:p,diag:N,size:D,reshape:C,qr:A,inv:d,usolve:E,usolveAll:F,equal:a,complex:w,larger:v,smaller:B,matrixFromColumns:T,dot:I});return t("eigs",{Array:function(oe){return Y(r(oe))},"Array, number|BigNumber":function(oe,$){return Y(r(oe),{precision:$})},"Array, Object"(ae,oe){return Y(r(ae),oe)},Matrix:function(oe){return Y(oe,{matricize:!0})},"Matrix, number|BigNumber":function(oe,$){return Y(oe,{precision:$,matricize:!0})},"Matrix, Object":function(oe,$){var H={matricize:!0};return wt(H,$),Y(oe,H)}});function Y(ae){var oe,$=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},H="eigenvectors"in $?$.eigenvectors:!0,J=(oe=$.precision)!==null&&oe!==void 0?oe:e.relTol,K=ee(ae,J,H);return $.matricize&&(K.values=r(K.values),H&&(K.eigenvectors=K.eigenvectors.map(te=>{var{value:fe,vector:le}=te;return{value:fe,vector:r(le)}}))),H&&Object.defineProperty(K,"vectors",{enumerable:!1,get:()=>{throw new Error("eigs(M).vectors replaced with eigs(M).eigenvectors")}}),K}function ee(ae,oe,$){var H=ae.toArray(),J=ae.size();if(J.length!==2||J[0]!==J[1])throw new RangeError("Matrix must be square (size: ".concat(at(J),")"));var K=J[0];if(V(H,K,oe)&&(z(H,K),_(H,K,oe))){var te=de(ae,H,K);return U(H,K,oe,te,$)}var fe=de(ae,H,K);return L(H,K,oe,fe,$)}function _(ae,oe,$){for(var H=0;H<oe;H++)for(var J=H;J<oe;J++)if(v(p(o(s(ae[H][J],ae[J][H]))),$))return!1;return!0}function V(ae,oe,$){for(var H=0;H<oe;H++)for(var J=0;J<oe;J++)if(v(p(o(O(ae[H][J]))),$))return!1;return!0}function z(ae,oe){for(var $=0;$<oe;$++)for(var H=0;H<oe;H++)ae[$][H]=k(ae[$][H])}function de(ae,oe,$){var H=ae.datatype();if(H==="number"||H==="BigNumber"||H==="Complex")return H;for(var J=!1,K=!1,te=!1,fe=0;fe<$;fe++)for(var le=0;le<$;le++){var Se=oe[fe][le];if(Je(Se)||vn(Se))J=!0;else if(Xe(Se))K=!0;else if(ci(Se))te=!0;else throw TypeError("Unsupported type in Matrix: "+Dt(Se))}if(K&&te&&console.warn("Complex BigNumbers not supported, this operation will lose precission."),te){for(var _e=0;_e<$;_e++)for(var Be=0;Be<$;Be++)oe[_e][Be]=w(oe[_e][Be]);return"Complex"}if(K){for(var Ee=0;Ee<$;Ee++)for(var Pe=0;Pe<$;Pe++)oe[Ee][Pe]=p(oe[Ee][Pe]);return"BigNumber"}if(J){for(var q=0;q<$;q++)for(var Z=0;Z<$;Z++)oe[q][Z]=b(oe[q][Z]);return"number"}else throw TypeError("Matrix contains unsupported types only.")}}),LS="expm",GR=["typed","abs","add","identity","inv","multiply"],Zf=R(LS,GR,n=>{var{typed:e,abs:t,add:r,identity:i,inv:s,multiply:a}=n;return e(LS,{Matrix:function(h){var f=h.size();if(f.length!==2||f[0]!==f[1])throw new RangeError("Matrix must be square (size: "+at(f)+")");for(var d=f[0],p=1e-15,m=o(h),y=l(m,p),v=y.q,S=y.j,g=a(h,Math.pow(2,-S)),b=i(d),w=i(d),x=1,N=g,D=-1,C=1;C<=v;C++)C>1&&(N=a(N,g),D=-D),x=x*(v-C+1)/((2*v-C+1)*C),b=r(b,a(x,N)),w=r(w,a(x*D,N));for(var A=a(s(w),b),E=0;E<S;E++)A=a(A,A);return Ki(h)?h.createSparseMatrix(A):A}});function o(c){for(var h=c.size()[0],f=0,d=0;d<h;d++){for(var p=0,m=0;m<h;m++)p+=t(c.get([d,m]));f=Math.max(p,f)}return f}function l(c,h){for(var f=30,d=0;d<f;d++)for(var p=0;p<=d;p++){var m=d-p;if(u(c,p,m)<h)return{q:p,j:m}}throw new Error("Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)")}function u(c,h,f){for(var d=1,p=2;p<=h;p++)d*=p;for(var m=d,y=h+1;y<=2*h;y++)m*=y;var v=m*(2*h+1);return 8*Math.pow(c/Math.pow(2,f),2*h)*d*d/(m*v)}}),IS="sqrtm",XR=["typed","abs","add","multiply","map","sqrt","subtract","inv","size","max","identity"],Qf=R(IS,XR,n=>{var{typed:e,abs:t,add:r,multiply:i,map:s,sqrt:a,subtract:o,inv:l,size:u,max:c,identity:h}=n,f=1e3,d=1e-6;function p(m){var y,v=0,S=m,g=h(u(m));do{var b=S;if(S=i(.5,r(b,l(g))),g=i(.5,r(g,l(b))),y=c(t(o(S,b))),y>d&&++v>f)throw new Error("computing square root of matrix: iterative method could not converge")}while(y>d);return S}return e(IS,{"Array | Matrix":function(y){var v=Re(y)?y.size():Ge(y);switch(v.length){case 1:if(v[0]===1)return s(y,a);throw new RangeError("Matrix must be square (size: "+at(v)+")");case 2:{var S=v[0],g=v[1];if(S===g)return p(y);throw new RangeError("Matrix must be square (size: "+at(v)+")")}default:throw new RangeError("Matrix must be at most two dimensional (size: "+at(v)+")")}}})}),$S="sylvester",YR=["typed","schur","matrixFromColumns","matrix","multiply","range","concat","transpose","index","subset","add","subtract","identity","lusolve","abs"],Kf=R($S,YR,n=>{var{typed:e,schur:t,matrixFromColumns:r,matrix:i,multiply:s,range:a,concat:o,transpose:l,index:u,subset:c,add:h,subtract:f,identity:d,lusolve:p,abs:m}=n;return e($S,{"Matrix, Matrix, Matrix":y,"Array, Matrix, Matrix":function(S,g,b){return y(i(S),g,b)},"Array, Array, Matrix":function(S,g,b){return y(i(S),i(g),b)},"Array, Matrix, Array":function(S,g,b){return y(i(S),g,i(b))},"Matrix, Array, Matrix":function(S,g,b){return y(S,i(g),b)},"Matrix, Array, Array":function(S,g,b){return y(S,i(g),i(b))},"Matrix, Matrix, Array":function(S,g,b){return y(S,g,i(b))},"Array, Array, Array":function(S,g,b){return y(i(S),i(g),i(b)).toArray()}});function y(v,S,g){for(var b=S.size()[0],w=v.size()[0],x=t(v),N=x.T,D=x.U,C=t(s(-1,S)),A=C.T,E=C.U,F=s(s(l(D),g),E),O=a(0,w),k=[],B=(te,fe)=>o(te,fe,1),T=(te,fe)=>o(te,fe,0),I=0;I<b;I++)if(I<b-1&&m(c(A,u(I+1,I)))>1e-5){for(var U=T(c(F,u(O,I)),c(F,u(O,I+1))),L=0;L<I;L++)U=h(U,T(s(k[L],c(A,u(L,I))),s(k[L],c(A,u(L,I+1)))));var Y=s(d(w),s(-1,c(A,u(I,I)))),ee=s(d(w),s(-1,c(A,u(I+1,I)))),_=s(d(w),s(-1,c(A,u(I,I+1)))),V=s(d(w),s(-1,c(A,u(I+1,I+1)))),z=T(B(h(N,Y),ee),B(_,h(N,V))),de=p(z,U);k[I]=de.subset(u(a(0,w),0)),k[I+1]=de.subset(u(a(w,2*w),0)),I++}else{for(var ae=c(F,u(O,I)),oe=0;oe<I;oe++)ae=h(ae,s(k[oe],c(A,u(oe,I))));var $=c(A,u(I,I)),H=f(N,s($,d(w)));k[I]=p(H,ae)}var J=i(r(...k)),K=s(D,s(J,l(E)));return K}}),qS="schur",JR=["typed","matrix","identity","multiply","qr","norm","subtract"],ed=R(qS,JR,n=>{var{typed:e,matrix:t,identity:r,multiply:i,qr:s,norm:a,subtract:o}=n;return e(qS,{Array:function(c){var h=l(t(c));return{U:h.U.valueOf(),T:h.T.valueOf()}},Matrix:function(c){return l(c)}});function l(u){var c=u.size()[0],h=u,f=r(c),d=0,p;do{p=h;var m=s(h),y=m.Q,v=m.R;if(h=i(v,y),f=i(f,y),d++>100)break}while(a(o(h,p))>1e-4);return{U:f,T:h}}}),HS="lyap",ZR=["typed","matrix","sylvester","multiply","transpose"],td=R(HS,ZR,n=>{var{typed:e,matrix:t,sylvester:r,multiply:i,transpose:s}=n;return e(HS,{"Matrix, Matrix":function(o,l){return r(o,s(o),i(-1,l))},"Array, Matrix":function(o,l){return r(t(o),s(t(o)),i(-1,l))},"Matrix, Array":function(o,l){return r(o,s(t(o)),t(i(-1,l)))},"Array, Array":function(o,l){return r(t(o),s(t(o)),t(i(-1,l))).toArray()}})}),QR="divide",KR=["typed","matrix","multiply","equalScalar","divideScalar","inv"],rd=R(QR,KR,n=>{var{typed:e,matrix:t,multiply:r,equalScalar:i,divideScalar:s,inv:a}=n,o=pr({typed:e,equalScalar:i}),l=gi({typed:e});return e("divide",Dy({"Array | Matrix, Array | Matrix":function(c,h){return r(c,a(h))},"DenseMatrix, any":function(c,h){return l(c,h,s,!1)},"SparseMatrix, any":function(c,h){return o(c,h,s,!1)},"Array, any":function(c,h){return l(t(c),h,s,!1).valueOf()},"any, Array | Matrix":function(c,h){return r(c,a(h))}},s.signatures))}),US="distance",eL=["typed","addScalar","subtractScalar","divideScalar","multiplyScalar","deepEqual","sqrt","abs"],id=R(US,eL,n=>{var{typed:e,addScalar:t,subtractScalar:r,multiplyScalar:i,divideScalar:s,deepEqual:a,sqrt:o,abs:l}=n;return e(US,{"Array, Array, Array":function(w,x,N){if(w.length===2&&x.length===2&&N.length===2){if(!c(w))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(x))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!c(N))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(a(x,N))throw new TypeError("LinePoint1 should not be same with LinePoint2");var D=r(N[1],x[1]),C=r(x[0],N[0]),A=r(i(N[0],x[1]),i(x[0],N[1]));return y(w[0],w[1],D,C,A)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(w,x,N){if(Object.keys(w).length===2&&Object.keys(x).length===2&&Object.keys(N).length===2){if(!c(w))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(x))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!c(N))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if(a(p(x),p(N)))throw new TypeError("LinePoint1 should not be same with LinePoint2");if("pointX"in w&&"pointY"in w&&"lineOnePtX"in x&&"lineOnePtY"in x&&"lineTwoPtX"in N&&"lineTwoPtY"in N){var D=r(N.lineTwoPtY,x.lineOnePtY),C=r(x.lineOnePtX,N.lineTwoPtX),A=r(i(N.lineTwoPtX,x.lineOnePtY),i(x.lineOnePtX,N.lineTwoPtY));return y(w.pointX,w.pointY,D,C,A)}else throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(w,x){if(w.length===2&&x.length===3){if(!c(w))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!h(x))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return y(w[0],w[1],x[0],x[1],x[2])}else if(w.length===3&&x.length===6){if(!h(w))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!d(x))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return v(w[0],w[1],w[2],x[0],x[1],x[2],x[3],x[4],x[5])}else if(w.length===x.length&&w.length>0){if(!f(w))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!f(x))throw new TypeError("All values of an array should be numbers or BigNumbers");return S(w,x)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(w,x){if(Object.keys(w).length===2&&Object.keys(x).length===3){if(!c(w))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!h(x))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in w&&"pointY"in w&&"xCoeffLine"in x&&"yCoeffLine"in x&&"constant"in x)return y(w.pointX,w.pointY,x.xCoeffLine,x.yCoeffLine,x.constant);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===3&&Object.keys(x).length===6){if(!h(w))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!d(x))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in w&&"pointY"in w&&"x0"in x&&"y0"in x&&"z0"in x&&"a"in x&&"b"in x&&"c"in x)return v(w.pointX,w.pointY,w.pointZ,x.x0,x.y0,x.z0,x.a,x.b,x.c);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===2&&Object.keys(x).length===2){if(!c(w))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(x))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in w&&"pointOneY"in w&&"pointTwoX"in x&&"pointTwoY"in x)return S([w.pointOneX,w.pointOneY],[x.pointTwoX,x.pointTwoY]);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===3&&Object.keys(x).length===3){if(!h(w))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!h(x))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in w&&"pointOneY"in w&&"pointOneZ"in w&&"pointTwoX"in x&&"pointTwoY"in x&&"pointTwoZ"in x)return S([w.pointOneX,w.pointOneY,w.pointOneZ],[x.pointTwoX,x.pointTwoY,x.pointTwoZ]);throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},Array:function(w){if(!m(w))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return g(w)}});function u(b){return typeof b=="number"||Xe(b)}function c(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])}function h(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])&&u(b[2])}function f(b){return Array.isArray(b)||(b=p(b)),b.every(u)}function d(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])&&u(b[2])&&u(b[3])&&u(b[4])&&u(b[5])}function p(b){for(var w=Object.keys(b),x=[],N=0;N<w.length;N++)x.push(b[w[N]]);return x}function m(b){if(b[0].length===2&&u(b[0][0])&&u(b[0][1])){if(b.some(w=>w.length!==2||!u(w[0])||!u(w[1])))return!1}else if(b[0].length===3&&u(b[0][0])&&u(b[0][1])&&u(b[0][2])){if(b.some(w=>w.length!==3||!u(w[0])||!u(w[1])||!u(w[2])))return!1}else return!1;return!0}function y(b,w,x,N,D){var C=l(t(t(i(x,b),i(N,w)),D)),A=o(t(i(x,x),i(N,N)));return s(C,A)}function v(b,w,x,N,D,C,A,E,F){var O=[r(i(r(D,w),F),i(r(C,x),E)),r(i(r(C,x),A),i(r(N,b),F)),r(i(r(N,b),E),i(r(D,w),A))];O=o(t(t(i(O[0],O[0]),i(O[1],O[1])),i(O[2],O[2])));var k=o(t(t(i(A,A),i(E,E)),i(F,F)));return s(O,k)}function S(b,w){for(var x=b.length,N=0,D=0,C=0;C<x;C++)D=r(b[C],w[C]),N=t(i(D,D),N);return o(N)}function g(b){for(var w=[],x=[],N=[],D=0;D<b.length-1;D++)for(var C=D+1;C<b.length;C++)b[0].length===2?(x=[b[D][0],b[D][1]],N=[b[C][0],b[C][1]]):b[0].length===3&&(x=[b[D][0],b[D][1],b[D][2]],N=[b[C][0],b[C][1],b[C][2]]),w.push(S(x,N));return w}}),tL="intersect",rL=["typed","config","abs","add","addScalar","matrix","multiply","multiplyScalar","divideScalar","subtract","smaller","equalScalar","flatten","isZero","isNumeric"],nd=R(tL,rL,n=>{var{typed:e,config:t,abs:r,add:i,addScalar:s,matrix:a,multiply:o,multiplyScalar:l,divideScalar:u,subtract:c,smaller:h,equalScalar:f,flatten:d,isZero:p,isNumeric:m}=n;return e("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":v,"Matrix, Matrix, Matrix":function(E,F,O){var k=y(E.valueOf(),F.valueOf(),O.valueOf());return k===null?null:a(k)},"Matrix, Matrix, Matrix, Matrix":function(E,F,O,k){var B=v(E.valueOf(),F.valueOf(),O.valueOf(),k.valueOf());return B===null?null:a(B)}});function y(A,E,F){if(A=S(A),E=S(E),F=S(F),!b(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!b(E))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!w(F))throw new TypeError("Array with 4 numbers expected as third argument");return C(A[0],A[1],A[2],E[0],E[1],E[2],F[0],F[1],F[2],F[3])}function v(A,E,F,O){if(A=S(A),E=S(E),F=S(F),O=S(O),A.length===2){if(!g(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!g(E))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!g(F))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!g(O))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return x(A,E,F,O)}else if(A.length===3){if(!b(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!b(E))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!b(F))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!b(O))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return D(A[0],A[1],A[2],E[0],E[1],E[2],F[0],F[1],F[2],O[0],O[1],O[2])}else throw new TypeError("Arrays with two or thee dimensional points expected")}function S(A){return A.length===1?A[0]:A.length>1&&Array.isArray(A[0])&&A.every(E=>Array.isArray(E)&&E.length===1)?d(A):A}function g(A){return A.length===2&&m(A[0])&&m(A[1])}function b(A){return A.length===3&&m(A[0])&&m(A[1])&&m(A[2])}function w(A){return A.length===4&&m(A[0])&&m(A[1])&&m(A[2])&&m(A[3])}function x(A,E,F,O){var k=A,B=F,T=c(k,E),I=c(B,O),U=c(l(T[0],I[1]),l(I[0],T[1]));if(p(U)||h(r(U),t.relTol))return null;var L=l(I[0],k[1]),Y=l(I[1],k[0]),ee=l(I[0],B[1]),_=l(I[1],B[0]),V=u(s(c(c(L,Y),ee),_),U);return i(o(T,V),k)}function N(A,E,F,O,k,B,T,I,U,L,Y,ee){var _=l(c(A,E),c(F,O)),V=l(c(k,B),c(T,I)),z=l(c(U,L),c(Y,ee));return s(s(_,V),z)}function D(A,E,F,O,k,B,T,I,U,L,Y,ee){var _=N(A,T,L,T,E,I,Y,I,F,U,ee,U),V=N(L,T,O,A,Y,I,k,E,ee,U,B,F),z=N(A,T,O,A,E,I,k,E,F,U,B,F),de=N(L,T,L,T,Y,I,Y,I,ee,U,ee,U),ae=N(O,A,O,A,k,E,k,E,B,F,B,F),oe=c(l(_,V),l(z,de)),$=c(l(ae,de),l(V,V));if(p($))return null;var H=u(oe,$),J=u(s(_,l(H,V)),de),K=s(A,l(H,c(O,A))),te=s(E,l(H,c(k,E))),fe=s(F,l(H,c(B,F))),le=s(T,l(J,c(L,T))),Se=s(I,l(J,c(Y,I))),_e=s(U,l(J,c(ee,U)));return f(K,le)&&f(te,Se)&&f(fe,_e)?[K,te,fe]:null}function C(A,E,F,O,k,B,T,I,U,L){var Y=l(A,T),ee=l(O,T),_=l(E,I),V=l(k,I),z=l(F,U),de=l(B,U),ae=c(c(c(L,Y),_),z),oe=c(c(c(s(s(ee,V),de),Y),_),z),$=u(ae,oe),H=s(A,l($,c(O,A))),J=s(E,l($,c(k,E))),K=s(F,l($,c(B,F)));return[H,J,K]}}),VS="sum",iL=["typed","config","add","numeric"],bo=R(VS,iL,n=>{var{typed:e,config:t,add:r,numeric:i}=n;return e(VS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":a,"...":function(l){if(na(l))throw new TypeError("Scalar values expected in function sum");return s(l)}});function s(o){var l;return Fn(o,function(u){try{l=l===void 0?u:r(l,u)}catch(c){throw Br(c,"sum",u)}}),l===void 0&&(l=i(0,t.number)),typeof l=="string"&&(l=i(l,wn(l,t))),l}function a(o,l){try{var u=ku(o,l,r);return u}catch(c){throw Br(c,"sum")}}}),sd="cumsum",nL=["typed","add","unaryPlus"],xo=R(sd,nL,n=>{var{typed:e,add:t,unaryPlus:r}=n;return e(sd,{Array:i,Matrix:function(u){return u.create(i(u.valueOf(),u.datatype()))},"Array, number | BigNumber":a,"Matrix, number | BigNumber":function(u,c){return u.create(a(u.valueOf(),c),u.datatype())},"...":function(u){if(na(u))throw new TypeError("All values expected to be scalar in function cumsum");return i(u)}});function i(l){try{return s(l)}catch(u){throw Br(u,sd)}}function s(l){if(l.length===0)return[];for(var u=[r(l[0])],c=1;c<l.length;++c)u.push(t(u[c-1],l[c]));return u}function a(l,u){var c=Ge(l);if(u<0||u>=c.length)throw new Kr(u,c.length);try{return o(l,u)}catch(h){throw Br(h,sd)}}function o(l,u){var c,h,f;if(u<=0){var d=l[0][0];if(Array.isArray(d)){for(f=xb(l),h=[],c=0;c<f.length;c++)h[c]=o(f[c],u-1);return h}else return s(l)}else{for(h=[],c=0;c<l.length;c++)h[c]=o(l[c],u-1);return h}}}),WS="mean",sL=["typed","add","divide"],wo=R(WS,sL,n=>{var{typed:e,add:t,divide:r}=n;return e(WS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":i,"...":function(o){if(na(o))throw new TypeError("Scalar values expected in function mean");return s(o)}});function i(a,o){try{var l=ku(a,o,t),u=Array.isArray(a)?Ge(a):a.size();return r(l,u[o])}catch(c){throw Br(c,"mean")}}function s(a){var o,l=0;if(Fn(a,function(u){try{o=o===void 0?u:t(o,u),l++}catch(c){throw Br(c,"mean",u)}}),l===0)throw new Error("Cannot calculate the mean of an empty array");return r(o,l)}}),jS="median",aL=["typed","add","divide","compare","partitionSelect"],ad=R(jS,aL,n=>{var{typed:e,add:t,divide:r,compare:i,partitionSelect:s}=n;function a(u){try{u=gt(u.valueOf());var c=u.length;if(c===0)throw new Error("Cannot calculate median of an empty array");if(c%2===0){for(var h=c/2-1,f=s(u,h+1),d=u[h],p=0;p<h;++p)i(u[p],d)>0&&(d=u[p]);return l(d,f)}else{var m=s(u,(c-1)/2);return o(m)}}catch(y){throw Br(y,"median")}}var o=e({"number | BigNumber | Complex | Unit":function(c){return c}}),l=e({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(c,h){return r(t(c,h),2)}});return e(jS,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(c,h){throw new Error("median(A, dim) is not yet supported")},"...":function(c){if(na(c))throw new TypeError("Scalar values expected in function median");return a(c)}})}),GS="mad",oL=["typed","abs","map","median","subtract"],od=R(GS,oL,n=>{var{typed:e,abs:t,map:r,median:i,subtract:s}=n;return e(GS,{"Array | Matrix":a,"...":function(l){return a(l)}});function a(o){if(o=gt(o.valueOf()),o.length===0)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var l=i(o);return i(r(o,function(u){return t(s(u,l))}))}catch(u){throw u instanceof TypeError&&u.message.includes("median")?new TypeError(u.message.replace("median","mad")):Br(u,"mad")}}}),fv="unbiased",XS="variance",uL=["typed","add","subtract","multiply","divide","mapSlices","isNaN"],So=R(XS,uL,n=>{var{typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o}=n;return e(XS,{"Array | Matrix":function(h){return l(h,fv)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(h,f){return u(h,f,fv)},"Array | Matrix, number | BigNumber, string":u,"...":function(h){return l(h,fv)}});function l(c,h){var f,d=0;if(c.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(Fn(c,function(y){try{f=f===void 0?y:t(f,y),d++}catch(v){throw Br(v,"variance",y)}}),d===0)throw new Error("Cannot calculate variance of an empty array");var p=s(f,d);if(f=void 0,Fn(c,function(y){var v=r(y,p);f=f===void 0?i(v,v):t(f,i(v,v))}),o(f))return f;switch(h){case"uncorrected":return s(f,d);case"biased":return s(f,d+1);case"unbiased":{var m=Xe(f)?f.mul(0):0;return d===1?m:s(f,d-1)}default:throw new Error('Unknown normalization "'+h+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(c,h,f){try{if(c.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return a(c,h,d=>l(d,f))}catch(d){throw Br(d,"variance")}}}),YS="quantileSeq",lL=["typed","?bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger","mapSlices"],No=R(YS,lL,n=>{var{typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d}=n;return e(YS,{"Array | Matrix, number | BigNumber":(S,g)=>m(S,g,!1),"Array | Matrix, number | BigNumber, number":(S,g,b)=>p(S,g,!1,b,m),"Array | Matrix, number | BigNumber, boolean":m,"Array | Matrix, number | BigNumber, boolean, number":(S,g,b,w)=>p(S,g,b,w,m),"Array | Matrix, Array | Matrix":(S,g)=>y(S,g,!1),"Array | Matrix, Array | Matrix, number":(S,g,b)=>p(S,g,!1,b,y),"Array | Matrix, Array | Matrix, boolean":y,"Array | Matrix, Array | Matrix, boolean, number":(S,g,b,w)=>p(S,g,b,w,y)});function p(S,g,b,w,x){return d(S,w,N=>x(N,g,b))}function m(S,g,b){var w,x=S.valueOf();if(c(g,0))throw new Error("N/prob must be non-negative");if(h(g,1))return Je(g)?v(x,g,b):t(v(x,g,b));if(f(g,1)){if(!u(g))throw new Error("N must be a positive integer");if(f(g,4294967295))throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var N=r(g,1);w=[];for(var D=0;c(D,g);D++){var C=s(D+1,N);w.push(v(x,C,b))}return Je(g)?w:t(w)}}function y(S,g,b){for(var w=S.valueOf(),x=g.valueOf(),N=[],D=0;D<x.length;++D)N.push(v(w,x[D],b));return N}function v(S,g,b){var w=gt(S),x=w.length;if(x===0)throw new Error("Cannot calculate quantile of an empty sequence");var N=Je(g)?g*(x-1):g.times(x-1),D=Je(g)?Math.floor(N):N.floor().toNumber(),C=Je(g)?N%1:N.minus(D);if(u(N))return b?w[N]:o(w,Je(g)?N:N.valueOf());var A,E;if(b)A=w[D],E=w[D+1];else{E=o(w,D+1),A=w[D];for(var F=0;F<D;++F)l(w[F],A)>0&&(A=w[F])}return r(a(A,i(1,C)),a(E,C))}}),JS="std",cL=["typed","map","sqrt","variance"],Co=R(JS,cL,n=>{var{typed:e,map:t,sqrt:r,variance:i}=n;return e(JS,{"Array | Matrix":s,"Array | Matrix, string":s,"Array | Matrix, number | BigNumber":s,"Array | Matrix, number | BigNumber, string":s,"...":function(o){return s(o)}});function s(a,o){if(a.length===0)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{var l=i.apply(null,arguments);return Or(l)?t(l,r):r(l)}catch(u){throw u instanceof TypeError&&u.message.includes(" variance")?new TypeError(u.message.replace(" variance"," std")):u}}}),ZS="corr",hL=["typed","matrix","mean","sqrt","sum","add","subtract","multiply","pow","divide"],ud=R(ZS,hL,n=>{var{typed:e,matrix:t,sqrt:r,sum:i,add:s,subtract:a,multiply:o,pow:l,divide:u}=n;return e(ZS,{"Array, Array":function(d,p){return c(d,p)},"Matrix, Matrix":function(d,p){var m=c(d.toArray(),p.toArray());return Array.isArray(m)?t(m):m}});function c(f,d){var p=[];if(Array.isArray(f[0])&&Array.isArray(d[0])){if(f.length!==d.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same length.");for(var m=0;m<f.length;m++){if(f[m].length!==d[m].length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same number of elements.");p.push(h(f[m],d[m]))}return p}else{if(f.length!==d.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same number of elements.");return h(f,d)}}function h(f,d){var p=f.length,m=i(f),y=i(d),v=f.reduce((x,N,D)=>s(x,o(N,d[D])),0),S=i(f.map(x=>l(x,2))),g=i(d.map(x=>l(x,2))),b=a(o(p,v),o(m,y)),w=r(o(a(o(p,S),l(m,2)),a(o(p,g),l(y,2))));return u(b,w)}}),QS="combinations",fL=["typed"],ld=R(QS,fL,n=>{var{typed:e}=n;return e(QS,{"number, number":Wb,"BigNumber, BigNumber":function(r,i){var s=r.constructor,a,o,l=r.minus(i),u=new s(1);if(!KS(r)||!KS(i))throw new TypeError("Positive integer value expected in function combinations");if(i.gt(r))throw new TypeError("k must be less than n in function combinations");if(a=u,i.lt(l))for(o=u;o.lte(l);o=o.plus(u))a=a.times(i.plus(o)).dividedBy(o);else for(o=u;o.lte(i);o=o.plus(u))a=a.times(l.plus(o)).dividedBy(o);return a}})});function KS(n){return n.isInteger()&&n.gte(0)}var eN="combinationsWithRep",dL=["typed"],cd=R(eN,dL,n=>{var{typed:e}=n;return e(eN,{"number, number":function(r,i){if(!ke(r)||r<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!ke(i)||i<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(r<1)throw new TypeError("k must be less than or equal to n + k - 1");if(i<r-1){var s=sn(r,r+i-1);return s/sn(1,i)}var a=sn(i+1,r+i-1);return a/sn(1,r-1)},"BigNumber, BigNumber":function(r,i){var s=r.constructor,a,o,l=new s(1),u=r.minus(l);if(!tN(r)||!tN(i))throw new TypeError("Positive integer value expected in function combinationsWithRep");if(r.lt(l))throw new TypeError("k must be less than or equal to n + k - 1 in function combinationsWithRep");if(a=l,i.lt(u))for(o=l;o.lte(u);o=o.plus(l))a=a.times(i.plus(o)).dividedBy(o);else for(o=l;o.lte(i);o=o.plus(l))a=a.times(u.plus(o)).dividedBy(o);return a}})});function tN(n){return n.isInteger()&&n.gte(0)}var rN="gamma",pL=["typed","config","multiplyScalar","pow","BigNumber","Complex"],hd=R(rN,pL,n=>{var{typed:e,config:t,multiplyScalar:r,pow:i,BigNumber:s,Complex:a}=n;function o(u){if(u.im===0)return Lu(u.re);if(u.re<.5){var c=new a(1-u.re,-u.im),h=new a(Math.PI*u.re,Math.PI*u.im);return new a(Math.PI).div(h.sin()).div(o(c))}u=new a(u.re-1,u.im);for(var f=new a(oa[0],0),d=1;d<oa.length;++d){var p=new a(oa[d],0);f=f.add(p.div(u.add(d)))}var m=new a(u.re+Gb+.5,u.im),y=Math.sqrt(2*Math.PI),v=m.pow(u.add(.5)),S=m.neg().exp();return f.mul(y).mul(v).mul(S)}return e(rN,{number:Lu,Complex:o,BigNumber:function(c){if(c.isInteger())return c.isNegative()||c.isZero()?new s(1/0):l(c.minus(1));if(!c.isFinite())return new s(c.isNegative()?NaN:1/0);throw new Error("Integer BigNumber expected")}});function l(u){if(u<8)return new s([1,1,2,6,24,120,720,5040][u]);var c=t.precision+(Math.log(u.toNumber())|0),h=s.clone({precision:c});if(u%2===1)return u.times(l(new s(u-1)));for(var f=u,d=new h(u),p=u.toNumber();f>2;)f-=2,p+=f,d=d.times(p);return new s(d.toPrecision(s.precision))}}),iN="lgamma",mL=["Complex","typed"],fd=R(iN,mL,n=>{var{Complex:e,typed:t}=n,r=7,i=7,s=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return t(iN,{number:Iu,Complex:a,BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(u){var c=6.283185307179586,h=1.1447298858494002,f=.1;if(u.isNaN())return new e(NaN,NaN);if(u.im===0)return new e(Iu(u.re),0);if(u.re>=r||Math.abs(u.im)>=i)return o(u);if(u.re<=f){var d=rM(c,u.im)*Math.floor(.5*u.re+.25),p=u.mul(Math.PI).sin().log(),m=a(new e(1-u.re,-u.im));return new e(h,d).sub(p).sub(m)}else return u.im>=0?l(u):l(u.conjugate()).conjugate()}function o(u){for(var c=u.sub(.5).mul(u.log()).sub(u).add(Xb),h=new e(1,0).div(u),f=h.div(u),d=s[0],p=s[1],m=2*f.re,y=f.re*f.re+f.im*f.im,v=2;v<8;v++){var S=p;p=-y*d+s[v],d=m*d+S}var g=h.mul(f.mul(d).add(p));return c.add(g)}function l(u){var c=0,h=0,f=u;for(u=u.add(1);u.re<=r;){f=f.mul(u);var d=f.im<0?1:0;d!==0&&h===0&&c++,h=d,u=u.add(1)}return o(u).sub(f.log()).sub(new e(0,c*2*Math.PI*1))}}),nN="factorial",gL=["typed","gamma"],dd=R(nN,gL,n=>{var{typed:e,gamma:t}=n;return e(nN,{number:function(i){if(i<0)throw new Error("Value must be non-negative");return t(i+1)},BigNumber:function(i){if(i.isNegative())throw new Error("Value must be non-negative");return t(i.plus(1))},"Array | Matrix":e.referToSelf(r=>i=>et(i,r))})}),sN="kldivergence",vL=["typed","matrix","divide","sum","multiply","map","dotDivide","log","isNumeric"],pd=R(sN,vL,n=>{var{typed:e,matrix:t,divide:r,sum:i,multiply:s,map:a,dotDivide:o,log:l,isNumeric:u}=n;return e(sN,{"Array, Array":function(f,d){return c(t(f),t(d))},"Matrix, Array":function(f,d){return c(f,t(d))},"Array, Matrix":function(f,d){return c(t(f),d)},"Matrix, Matrix":function(f,d){return c(f,d)}});function c(h,f){var d=f.size().length,p=h.size().length;if(d>1)throw new Error("first object must be one dimensional");if(p>1)throw new Error("second object must be one dimensional");if(d!==p)throw new Error("Length of two vectors must be equal");var m=i(h);if(m===0)throw new Error("Sum of elements in first object must be non zero");var y=i(f);if(y===0)throw new Error("Sum of elements in second object must be non zero");var v=r(h,i(h)),S=r(f,i(f)),g=i(s(v,a(o(v,S),b=>l(b))));return u(g)?g:Number.NaN}}),aN="multinomial",yL=["typed","add","divide","multiply","factorial","isInteger","isPositive"],md=R(aN,yL,n=>{var{typed:e,add:t,divide:r,multiply:i,factorial:s,isInteger:a,isPositive:o}=n;return e(aN,{"Array | Matrix":function(u){var c=0,h=1;return Fn(u,function(f){if(!a(f)||!o(f))throw new TypeError("Positive integer value expected in function multinomial");c=t(c,f),h=i(h,s(f))}),r(s(c),h)}})}),oN="permutations",bL=["typed","factorial"],gd=R(oN,bL,n=>{var{typed:e,factorial:t}=n;return e(oN,{"number | BigNumber":t,"number, number":function(i,s){if(!ke(i)||i<0)throw new TypeError("Positive integer value expected in function permutations");if(!ke(s)||s<0)throw new TypeError("Positive integer value expected in function permutations");if(s>i)throw new TypeError("second argument k must be less than or equal to first argument n");return sn(i-s+1,i)},"BigNumber, BigNumber":function(i,s){var a,o;if(!uN(i)||!uN(s))throw new TypeError("Positive integer value expected in function permutations");if(s.gt(i))throw new TypeError("second argument k must be less than or equal to first argument n");var l=i.mul(0).add(1);for(a=l,o=i.minus(s).plus(1);o.lte(i);o=o.plus(1))a=a.times(o);return a}})});function uN(n){return n.isInteger()&&n.gte(0)}var dv={exports:{}};dv.exports,function(n){(function(e,t,r){function i(l){var u=this,c=o();u.next=function(){var h=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=h-(u.c=h|0)},u.c=1,u.s0=c(" "),u.s1=c(" "),u.s2=c(" "),u.s0-=c(l),u.s0<0&&(u.s0+=1),u.s1-=c(l),u.s1<0&&(u.s1+=1),u.s2-=c(l),u.s2<0&&(u.s2+=1),c=null}function s(l,u){return u.c=l.c,u.s0=l.s0,u.s1=l.s1,u.s2=l.s2,u}function a(l,u){var c=new i(l),h=u&&u.state,f=c.next;return f.int32=function(){return c.next()*4294967296|0},f.double=function(){return f()+(f()*2097152|0)*11102230246251565e-32},f.quick=f,h&&(typeof h=="object"&&s(h,c),f.state=function(){return s(c,{})}),f}function o(){var l=4022871197,u=function(c){c=String(c);for(var h=0;h<c.length;h++){l+=c.charCodeAt(h);var f=.02519603282416938*l;l=f>>>0,f-=l,f*=l,l=f>>>0,f-=l,l+=f*4294967296}return(l>>>0)*23283064365386963e-26};return u}t&&t.exports?t.exports=a:this.alea=a})(cs,n)}(dv);var xL=dv.exports,pv={exports:{}};pv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c<u.length+64;c++)l.x^=u.charCodeAt(c)|0,l.next()}function s(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xor128=a})(cs,n)}(pv);var wL=pv.exports,mv={exports:{}};mv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c<u.length+64;c++)l.x^=u.charCodeAt(c)|0,c==u.length&&(l.d=l.x<<10^l.x>>>4),l.next()}function s(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xorwow=a})(cs,n)}(mv);var SL=mv.exports,gv={exports:{}};gv.exports,function(n){(function(e,t,r){function i(o){var l=this;l.next=function(){var c=l.x,h=l.i,f,d;return f=c[h],f^=f>>>7,d=f^f<<24,f=c[h+1&7],d^=f^f>>>10,f=c[h+3&7],d^=f^f>>>3,f=c[h+4&7],d^=f^f<<7,f=c[h+7&7],f=f^f<<13,d^=f^f<<9,c[h]=d,l.i=h+1&7,d};function u(c,h){var f,d=[];if(h===(h|0))d[0]=h;else for(h=""+h,f=0;f<h.length;++f)d[f&7]=d[f&7]<<15^h.charCodeAt(f)+d[f+1&7]<<13;for(;d.length<8;)d.push(0);for(f=0;f<8&&d[f]===0;++f);for(f==8?d[7]=-1:d[f],c.x=d,c.i=0,f=256;f>0;--f)c.next()}u(l,o)}function s(o,l){return l.x=o.x.slice(),l.i=o.i,l}function a(o,l){o==null&&(o=+new Date);var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(c.x&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xorshift7=a})(cs,n)}(gv);var NL=gv.exports,vv={exports:{}};vv.exports,function(n){(function(e,t,r){function i(o){var l=this;l.next=function(){var c=l.w,h=l.X,f=l.i,d,p;return l.w=c=c+1640531527|0,p=h[f+34&127],d=h[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,p=h[f]=p^d,l.i=f,p+(c^c>>>16)|0};function u(c,h){var f,d,p,m,y,v=[],S=128;for(h===(h|0)?(d=h,h=null):(h=h+"\0",d=0,S=Math.max(S,h.length)),p=0,m=-32;m<S;++m)h&&(d^=h.charCodeAt((m+32)%h.length)),m===0&&(y=d),d^=d<<10,d^=d>>>15,d^=d<<4,d^=d>>>13,m>=0&&(y=y+1640531527|0,f=v[m&127]^=d+y,p=f==0?p+1:0);for(p>=128&&(v[(h&&h.length||0)&127]=-1),p=127,m=4*128;m>0;--m)d=v[p+34&127],f=v[p=p+1&127],d^=d<<13,f^=f<<17,d^=d>>>15,f^=f>>>12,v[p]=d^f;c.w=y,c.X=v,c.i=p}u(l,o)}function s(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function a(o,l){o==null&&(o=+new Date);var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(c.X&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xor4096=a})(cs,n)}(vv);var CL=vv.exports,yv={exports:{}};yv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.next=function(){var h=l.b,f=l.c,d=l.d,p=l.a;return h=h<<25^h>>>7^f,f=f-d|0,d=d<<24^d>>>8^p,p=p-h|0,l.b=h=h<<20^h>>>12^f,l.c=f=f-d|0,l.d=d<<16^f>>>16^p,l.a=p-h|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c<u.length+20;c++)l.b^=u.charCodeAt(c)|0,l.next()}function s(o,l){return l.a=o.a,l.b=o.b,l.c=o.c,l.d=o.d,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.tychei=a})(cs,n)}(yv);var DL=yv.exports,lN={exports:{}};const vd=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})),AL=b3(vd);(function(n){(function(e,t,r){var i=256,s=6,a=52,o="random",l=r.pow(i,s),u=r.pow(2,a),c=u*2,h=i-1,f;function d(b,w,x){var N=[];w=w==!0?{entropy:!0}:w||{};var D=v(y(w.entropy?[b,g(t)]:b??S(),3),N),C=new p(N),A=function(){for(var E=C.g(s),F=l,O=0;E<u;)E=(E+O)*i,F*=i,O=C.g(1);for(;E>=c;)E/=2,F/=2,O>>>=1;return(E+O)/F};return A.int32=function(){return C.g(4)|0},A.quick=function(){return C.g(4)/4294967296},A.double=A,v(g(C.S),t),(w.pass||x||function(E,F,O,k){return k&&(k.S&&m(k,C),E.state=function(){return m(C,{})}),O?(r[o]=E,F):E})(A,D,"global"in w?w.global:this==r,w.state)}function p(b){var w,x=b.length,N=this,D=0,C=N.i=N.j=0,A=N.S=[];for(x||(b=[x++]);D<i;)A[D]=D++;for(D=0;D<i;D++)A[D]=A[C=h&C+b[D%x]+(w=A[D])],A[C]=w;(N.g=function(E){for(var F,O=0,k=N.i,B=N.j,T=N.S;E--;)F=T[k=h&k+1],O=O*i+T[h&(T[k]=T[B=h&B+F])+(T[B]=F)];return N.i=k,N.j=B,O})(i)}function m(b,w){return w.i=b.i,w.j=b.j,w.S=b.S.slice(),w}function y(b,w){var x=[],N=typeof b,D;if(w&&N=="object")for(D in b)try{x.push(y(b[D],w-1))}catch{}return x.length?x:N=="string"?b:b+"\0"}function v(b,w){for(var x=b+"",N,D=0;D<x.length;)w[h&D]=h&(N^=w[h&D]*19)+x.charCodeAt(D++);return g(w)}function S(){try{var b;return f&&(b=f.randomBytes)?b=b(i):(b=new Uint8Array(i),(e.crypto||e.msCrypto).getRandomValues(b)),g(b)}catch{var w=e.navigator,x=w&&w.plugins;return[+new Date,e,x,e.screen,g(t)]}}function g(b){return String.fromCharCode.apply(0,b)}if(v(r.random(),t),n.exports){n.exports=d;try{f=AL}catch{}}else r["seed"+o]=d})(typeof self<"u"?self:cs,[],Math)})(lN);var EL=lN.exports,ML=xL,TL=wL,FL=SL,_L=NL,OL=CL,BL=DL,hs=EL;hs.alea=ML,hs.xor128=TL,hs.xorwow=FL,hs.xorshift7=_L,hs.xor4096=OL,hs.tychei=BL;var kL=hs;const cN=$c(kL);var PL=cN(Date.now());function pa(n){var e;function t(i){e=i===null?PL:cN(String(i))}t(n);function r(){return e()}return r}var hN="pickRandom",zL=["typed","config","?on"],yd=R(hN,zL,n=>{var{typed:e,config:t,on:r}=n,i=pa(t.randomSeed);return r&&r("config",function(a,o){a.randomSeed!==o.randomSeed&&(i=pa(a.randomSeed))}),e(hN,{"Array | Matrix":function(o){return s(o,{})},"Array | Matrix, Object":function(o,l){return s(o,l)},"Array | Matrix, number":function(o,l){return s(o,{number:l})},"Array | Matrix, Array | Matrix":function(o,l){return s(o,{weights:l})},"Array | Matrix, Array | Matrix, number":function(o,l,u){return s(o,{number:u,weights:l})},"Array | Matrix, number, Array | Matrix":function(o,l,u){return s(o,{number:l,weights:u})}});function s(a,o){var{number:l,weights:u,elementWise:c=!0}=o,h=typeof l>"u";h&&(l=1);var f=Re(a)?a.create:Re(u)?u.create:null;a=a.valueOf(),u&&(u=u.valueOf()),c===!0&&(a=gt(a),u=gt(u));var d=0;if(typeof u<"u"){if(u.length!==a.length)throw new Error("Weights must have the same length as possibles");for(var p=0,m=u.length;p<m;p++){if(!Je(u[p])||u[p]<0)throw new Error("Weights must be an array of positive numbers");d+=u[p]}}for(var y=a.length,v=[],S;v.length<l;){if(typeof u>"u")S=a[Math.floor(i()*y)];else for(var g=i()*d,b=0,w=a.length;b<w;b++)if(g-=u[b],g<0){S=a[b];break}v.push(S)}return h?v[0]:f?f(v):v}});function bv(n,e){var t=[];if(n=n.slice(0),n.length>1)for(var r=0,i=n.shift();r<i;r++)t.push(bv(n,e));else for(var s=0,a=n.shift();s<a;s++)t.push(e());return t}var fN="random",RL=["typed","config","?on"],bd=R(fN,RL,n=>{var{typed:e,config:t,on:r}=n,i=pa(t.randomSeed);return r&&r("config",function(o,l){o.randomSeed!==l.randomSeed&&(i=pa(o.randomSeed))}),e(fN,{"":()=>a(0,1),number:o=>a(0,o),"number, number":(o,l)=>a(o,l),"Array | Matrix":o=>s(o,0,1),"Array | Matrix, number":(o,l)=>s(o,0,l),"Array | Matrix, number, number":(o,l,u)=>s(o,l,u)});function s(o,l,u){var c=bv(o.valueOf(),()=>a(l,u));return Re(o)?o.create(c,"number"):c}function a(o,l){return o+i()*(l-o)}}),dN="randomInt",LL=["typed","config","log2","?on"],xd=R(dN,LL,n=>{var{typed:e,config:t,log2:r,on:i}=n,s=pa(t.randomSeed);return i&&i("config",function(u,c){u.randomSeed!==c.randomSeed&&(s=pa(u.randomSeed))}),e(dN,{"":()=>o(0,2),number:u=>o(0,u),"number, number":(u,c)=>o(u,c),bigint:u=>l(0n,u),"bigint, bigint":l,"Array | Matrix":u=>a(u,0,1),"Array | Matrix, number":(u,c)=>a(u,0,c),"Array | Matrix, number, number":(u,c,h)=>a(u,c,h)});function a(u,c,h){var f=bv(u.valueOf(),()=>o(c,h));return Re(u)?u.create(f,"number"):f}function o(u,c){return Math.floor(u+s()*(c-u))}function l(u,c){var h=2n**30n,f=c-u;if(f<=h)return u+BigInt(o(0,Number(f)));for(var d=r(f),p=f;p>=f;){p=0n;for(var m=0;m<d;++m)p=2n*p+(s()<.5?0n:1n)}return u+p}}),pN="stirlingS2",IL=["typed","addScalar","subtractScalar","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],wd=R(pN,IL,n=>{var{typed:e,addScalar:t,subtractScalar:r,multiplyScalar:i,divideScalar:s,pow:a,factorial:o,combinations:l,isNegative:u,isInteger:c,number:h,bignumber:f,larger:d}=n,p=[],m=[];return e(pN,{"number | BigNumber, number | BigNumber":function(v,S){if(!c(v)||u(v)||!c(S)||u(S))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(d(S,v))throw new TypeError("k must be less than or equal to n in function stirlingS2");var g=!(Je(v)&&Je(S)),b=g?m:p,w=g?f:h,x=h(v),N=h(S);if(b[x]&&b[x].length>N)return b[x][N];for(var D=0;D<=x;++D)if(b[D]||(b[D]=[w(D===0?1:0)]),D!==0)for(var C=b[D],A=b[D-1],E=C.length;E<=D&&E<=N;++E)E===D?C[E]=1:C[E]=t(i(w(E),A[E]),A[E-1]);return b[x][N]}})}),mN="bellNumbers",$L=["typed","addScalar","isNegative","isInteger","stirlingS2"],Sd=R(mN,$L,n=>{var{typed:e,addScalar:t,isNegative:r,isInteger:i,stirlingS2:s}=n;return e(mN,{"number | BigNumber":function(o){if(!i(o)||r(o))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var l=0,u=0;u<=o;u++)l=t(l,s(o,u));return l}})}),gN="catalan",qL=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],Nd=R(gN,qL,n=>{var{typed:e,addScalar:t,divideScalar:r,multiplyScalar:i,combinations:s,isNegative:a,isInteger:o}=n;return e(gN,{"number | BigNumber":function(u){if(!o(u)||a(u))throw new TypeError("Non-negative integer value expected in function catalan");return r(s(i(u,2),u),t(u,1))}})}),vN="composition",HL=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],Cd=R(vN,HL,n=>{var{typed:e,addScalar:t,combinations:r,isPositive:i,isNegative:s,isInteger:a,larger:o}=n;return e(vN,{"number | BigNumber, number | BigNumber":function(u,c){if(!a(u)||!i(u)||!a(c)||!i(c))throw new TypeError("Positive integer value expected in function composition");if(o(c,u))throw new TypeError("k must be less than or equal to n in function composition");return r(t(u,-1),t(c,-1))}})}),yN="leafCount",UL=["parse","typed"],Dd=R(yN,UL,n=>{var{parse:e,typed:t}=n;function r(i){var s=0;return i.forEach(a=>{s+=r(a)}),s||1}return t(yN,{Node:function(s){return r(s)}})});function bN(n){return ct(n)||qt(n)&&n.isUnary()&&ct(n.args[0])}function Ad(n){return!!(ct(n)||(qi(n)||qt(n))&&n.args.every(Ad)||Ai(n)&&Ad(n.content))}function xN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function xv(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?xN(Object(t),!0).forEach(function(r){Yt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):xN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var VL="simplifyUtil",WL=["FunctionNode","OperatorNode","SymbolNode"],wv=R(VL,WL,n=>{var{FunctionNode:e,OperatorNode:t,SymbolNode:r}=n,i=!0,s=!1,a="defaultF",o={add:{trivial:i,total:i,commutative:i,associative:i},unaryPlus:{trivial:i,total:i,commutative:i,associative:i},subtract:{trivial:s,total:i,commutative:s,associative:s},multiply:{trivial:i,total:i,commutative:i,associative:i},divide:{trivial:s,total:i,commutative:s,associative:s},paren:{trivial:i,total:i,commutative:i,associative:s},defaultF:{trivial:s,total:i,commutative:s,associative:s}},l={divide:{total:s},log:{total:s}},u={subtract:{total:s},abs:{trivial:i},log:{total:i}};function c(g,b){var w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o,x=a;if(typeof g=="string"?x=g:qt(g)?x=g.fn.toString():qi(g)?x=g.name:Ai(g)&&(x="paren"),Te(w,x)){var N=w[x];if(Te(N,b))return N[b];if(Te(o,x))return o[x][b]}if(Te(w,a)){var D=w[a];return Te(D,b)?D[b]:o[a][b]}if(Te(o,x)){var C=o[x];if(Te(C,b))return C[b]}return o[a][b]}function h(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o;return c(g,"commutative",b)}function f(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o;return c(g,"associative",b)}function d(g,b){var w=xv({},g);for(var x in b)Te(g,x)?w[x]=xv(xv({},b[x]),g[x]):w[x]=b[x];return w}function p(g,b){if(!g.args||g.args.length===0)return g;g.args=m(g,b);for(var w=0;w<g.args.length;w++)p(g.args[w],b)}function m(g,b){var w,x=[],N=function(C){for(var A=0;A<C.args.length;A++){var E=C.args[A];qt(E)&&w===E.op?N(E):x.push(E)}};return f(g,b)?(w=g.op,N(g),x):g.args}function y(g,b){if(!(!g.args||g.args.length===0)){for(var w=S(g),x=g.args.length,N=0;N<x;N++)y(g.args[N],b);if(x>2&&f(g,b)){for(var D=g.args.pop();g.args.length>0;)D=w([g.args.pop(),D]);g.args=D.args}}}function v(g,b){if(!(!g.args||g.args.length===0)){for(var w=S(g),x=g.args.length,N=0;N<x;N++)v(g.args[N],b);if(x>2&&f(g,b)){for(var D=g.args.shift();g.args.length>0;)D=w([D,g.args.shift()]);g.args=D.args}}}function S(g){return qt(g)?function(b){try{return new t(g.op,g.fn,b,g.implicit)}catch(w){return console.error(w),[]}}:function(b){return new e(new r(g.name),b)}}return{createMakeNodeFunction:S,hasProperty:c,isCommutative:h,isAssociative:f,mergeContext:d,flatten:p,allChildren:m,unflattenr:y,unflattenl:v,defaultContext:o,realContext:l,positiveContext:u}}),jL="simplify",GL=["typed","parse","equal","resolve","simplifyConstant","simplifyCore","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode","replacer"],Ed=R(jL,GL,n=>{var{typed:e,parse:t,equal:r,resolve:i,simplifyConstant:s,simplifyCore:a,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:h,ObjectNode:f,OperatorNode:d,ParenthesisNode:p,SymbolNode:m,replacer:y}=n,{hasProperty:v,isCommutative:S,isAssociative:g,mergeContext:b,flatten:w,unflattenr:x,unflattenl:N,createMakeNodeFunction:D,defaultContext:C,realContext:A,positiveContext:E}=wv({FunctionNode:c,OperatorNode:d,SymbolNode:m});e.addConversion({from:"Object",to:"Map",convert:Us});var F=e("simplify",{Node:L,"Node, Map":($,H)=>L($,!1,H),"Node, Map, Object":($,H,J)=>L($,!1,H,J),"Node, Array":L,"Node, Array, Map":L,"Node, Array, Map, Object":L});e.removeConversion({from:"Object",to:"Map",convert:Us}),F.defaultContext=C,F.realContext=A,F.positiveContext=E;function O($){return $.transform(function(H){return Ai(H)?O(H.content):H})}var k={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};F.rules=[a,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(cl*v) -> v * (-cl)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(cl*v) -> (-cl) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*cl) -> v * (-cl)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" vd * ( vd * n1 + n2)",r:"vd^2 * n1 + vd * n2"},{s:" vd * (vd^n4 * n1 + n2) -> vd^(1+n4) * n1 + vd * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * ( vd * n1 + n2) -> vd^(n3+1) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * (vd^n4 * n1 + n2) -> vd^(n3+n4) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},s,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"vd*n + vd",r:"vd*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*vd + vd -> (n+1)*vd",assuming:{multiply:{commutative:!1}}},{s:"vd + n*vd -> (1+n)*vd",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n^n1 * n -> n^(n1+1)",assuming:{divide:{total:!0},multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*cd + cd",r:"(n+1)*cd"},{s:"cd*n + cd -> cd*(n+1)",assuming:{multiply:{commutative:!1}}},{s:"cd + cd*n -> cd*(1+n)",assuming:{multiply:{commutative:!1}}},s,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"ce+ve -> ve+ce",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"vd*cd -> cd*vd",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{l:"n+-(n1)",r:"n-(n1)"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];function B($,H){var J={};if($.s){var K=$.s.split("->");if(K.length===2)J.l=K[0],J.r=K[1];else throw SyntaxError("Could not parse rule: "+$.s)}else J.l=$.l,J.r=$.r;J.l=O(t(J.l)),J.r=O(t(J.r));for(var te of["imposeContext","repeat","assuming"])te in $&&(J[te]=$[te]);if($.evaluate&&(J.evaluate=t($.evaluate)),g(J.l,H)){var fe=!S(J.l,H),le;fe&&(le=U());var Se=D(J.l),_e=U();J.expanded={},J.expanded.l=Se([J.l,_e]),w(J.expanded.l,H),x(J.expanded.l,H),J.expanded.r=Se([J.r,_e]),fe&&(J.expandedNC1={},J.expandedNC1.l=Se([le,J.l]),J.expandedNC1.r=Se([le,J.r]),J.expandedNC2={},J.expandedNC2.l=Se([le,J.expanded.l]),J.expandedNC2.r=Se([le,J.expanded.r]))}return J}function T($,H){for(var J=[],K=0;K<$.length;K++){var te=$[K],fe=void 0,le=typeof te;switch(le){case"string":te={s:te};case"object":fe=B(te,H);break;case"function":fe=te;break;default:throw TypeError("Unsupported type of rule: "+le)}J.push(fe)}return J}var I=0;function U(){return new m("_p"+I++)}function L($,H){var J=arguments.length>2&&arguments[2]!==void 0?arguments[2]:La(),K=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},te=K.consoleDebug;H=T(H||F.rules,K.context);var fe=i($,J);fe=O(fe);for(var le={},Se=fe.toString({parenthesis:"all"});!le[Se];){le[Se]=!0,I=0;var _e=Se;te&&console.log("Working on: ",Se);for(var Be=0;Be<H.length;Be++){var Ee="";if(typeof H[Be]=="function"?(fe=H[Be](fe,K),te&&(Ee=H[Be].name)):(w(fe,K.context),fe=ee(fe,H[Be],K.context),te&&(Ee="".concat(H[Be].l.toString()," -> ").concat(H[Be].r.toString()))),te){var Pe=fe.toString({parenthesis:"all"});Pe!==_e&&(console.log("Applying",Ee,"produced",Pe),_e=Pe)}N(fe,K.context)}Se=fe.toString({parenthesis:"all"})}return fe}function Y($,H,J){var K=$;if($)for(var te=0;te<$.length;++te){var fe=ee($[te],H,J);fe!==$[te]&&(K===$&&(K=$.slice()),K[te]=fe)}return K}function ee($,H,J){if(H.assuming){for(var K in H.assuming)for(var te in H.assuming[K])if(v(K,te,J)!==H.assuming[K][te])return $}var fe=b(H.imposeContext,J),le=$;if(le instanceof d||le instanceof c){var Se=Y(le.args,H,J);Se!==le.args&&(le=le.clone(),le.args=Se)}else if(le instanceof p){if(le.content){var _e=ee(le.content,H,J);_e!==le.content&&(le=new p(_e))}}else if(le instanceof l){var Be=Y(le.items,H,J);Be!==le.items&&(le=new l(Be))}else if(le instanceof o){var Ee=le.object;le.object&&(Ee=ee(le.object,H,J));var Pe=le.index;le.index&&(Pe=ee(le.index,H,J)),(Ee!==le.object||Pe!==le.index)&&(le=new o(Ee,Pe))}else if(le instanceof h){var q=Y(le.dimensions,H,J);q!==le.dimensions&&(le=new h(q))}else if(le instanceof f){var Z=!1,ne={};for(var P in le.properties)ne[P]=ee(le.properties[P],H,J),ne[P]!==le.properties[P]&&(Z=!0);Z&&(le=new f(ne))}var W=H.r,Q=ae(H.l,le,fe)[0];if(!Q&&H.expanded&&(W=H.expanded.r,Q=ae(H.expanded.l,le,fe)[0]),!Q&&H.expandedNC1&&(W=H.expandedNC1.r,Q=ae(H.expandedNC1.l,le,fe)[0],Q||(W=H.expandedNC2.r,Q=ae(H.expandedNC2.l,le,fe)[0])),Q){var re=le.implicit;le=W.clone(),re&&"implicit"in W&&(le.implicit=!0),le=le.transform(function(se){return se.isSymbolNode&&Te(Q.placeholders,se.name)?Q.placeholders[se.name].clone():se})}return H.repeat&&le!==$&&(le=ee(le,H,J)),le}function _($,H){var J=[],K,te,fe=D($);if(S($,H))for(var le=0;le<$.args.length;le++)te=$.args.slice(0),te.splice(le,1),K=te.length===1?te[0]:fe(te),J.push(fe([$.args[le],K]));else for(var Se=1;Se<$.args.length;Se++){var _e=$.args[0];Se>1&&(_e=fe($.args.slice(0,Se))),te=$.args.slice(Se),K=te.length===1?te[0]:fe(te),J.push(fe([_e,K]))}return J}function V($,H){var J={placeholders:{}};if(!$.placeholders&&!H.placeholders)return J;if($.placeholders){if(!H.placeholders)return $}else return H;for(var K in $.placeholders)if(Te($.placeholders,K)&&(J.placeholders[K]=$.placeholders[K],Te(H.placeholders,K)&&!oe($.placeholders[K],H.placeholders[K])))return null;for(var te in H.placeholders)Te(H.placeholders,te)&&(J.placeholders[te]=H.placeholders[te]);return J}function z($,H){var J=[];if($.length===0||H.length===0)return J;for(var K,te=0;te<$.length;te++)for(var fe=0;fe<H.length;fe++)K=V($[te],H[fe]),K&&J.push(K);return J}function de($){if($.length===0)return $;for(var H=$.reduce(z),J=[],K={},te=0;te<H.length;te++){var fe=JSON.stringify(H[te],y);K[fe]||(K[fe]=!0,J.push(H[te]))}return J}function ae($,H,J,K){var te=[{placeholders:{}}];if($ instanceof d&&H instanceof d||$ instanceof c&&H instanceof c){if($ instanceof d){if($.op!==H.op||$.fn!==H.fn)return[]}else if($ instanceof c&&$.name!==H.name)return[];if(H.args.length===1&&$.args.length===1||!g(H,J)&&H.args.length===$.args.length||K){for(var fe=[],le=0;le<$.args.length;le++){var Se=ae($.args[le],H.args[le],J);if(Se.length===0)break;fe.push(Se)}if(fe.length!==$.args.length){if(!S(H,J)||$.args.length===1)return[];if($.args.length>2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var _e=ae($.args[0],H.args[1],J);if(_e.length===0)return[];var Be=ae($.args[1],H.args[0],J);if(Be.length===0)return[];fe=[_e,Be]}te=de(fe)}else if(H.args.length>=2&&$.args.length===2){for(var Ee=_(H,J),Pe=[],q=0;q<Ee.length;q++){var Z=ae($,Ee[q],J,!0);Pe=Pe.concat(Z)}return Pe}else{if($.args.length>2)throw Error("Unexpected non-binary associative function: "+$.toString());return[]}}else if($ instanceof m){if($.name.length===0)throw new Error("Symbol in rule has 0 length...!?");if(k[$.name]){if($.name!==H.name)return[]}else switch($.name[1]>="a"&&$.name[1]<="z"?$.name.substring(0,2):$.name[0]){case"n":case"_p":te[0].placeholders[$.name]=H;break;case"c":case"cl":if(ct(H))te[0].placeholders[$.name]=H;else return[];break;case"v":if(!ct(H))te[0].placeholders[$.name]=H;else return[];break;case"vl":if(Xt(H))te[0].placeholders[$.name]=H;else return[];break;case"cd":if(bN(H))te[0].placeholders[$.name]=H;else return[];break;case"vd":if(!bN(H))te[0].placeholders[$.name]=H;else return[];break;case"ce":if(Ad(H))te[0].placeholders[$.name]=H;else return[];break;case"ve":if(!Ad(H))te[0].placeholders[$.name]=H;else return[];break;default:throw new Error("Invalid symbol in rule: "+$.name)}}else if($ instanceof u){if(!r($.value,H.value))return[]}else return[];return te}function oe($,H){if($ instanceof u&&H instanceof u){if(!r($.value,H.value))return!1}else if($ instanceof m&&H instanceof m){if($.name!==H.name)return!1}else if($ instanceof d&&H instanceof d||$ instanceof c&&H instanceof c){if($ instanceof d){if($.op!==H.op||$.fn!==H.fn)return!1}else if($ instanceof c&&$.name!==H.name)return!1;if($.args.length!==H.args.length)return!1;for(var J=0;J<$.args.length;J++)if(!oe($.args[J],H.args[J]))return!1}else return!1;return!0}return F}),XL="simplifyConstant",YL=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],Md=R(XL,YL,n=>{var{typed:e,config:t,mathWithTransform:r,matrix:i,fraction:s,bignumber:a,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:h,ObjectNode:f,OperatorNode:d,SymbolNode:p}=n,{isCommutative:m,isAssociative:y,allChildren:v,createMakeNodeFunction:S}=wv({FunctionNode:c,OperatorNode:d,SymbolNode:p}),g=e("simplifyConstant",{Node:B=>N(k(B,{})),"Node, Object":function(T,I){return N(k(T,I))}});function b(B){return vn(B)?B.valueOf():B instanceof Array?B.map(b):Re(B)?i(b(B.valueOf())):B}function w(B,T,I){try{return r[B].apply(null,T)}catch{return T=T.map(b),C(r[B].apply(null,T),I)}}var x=e({Fraction:E,number:function(T){return T<0?A(new u(-T)):new u(T)},BigNumber:function(T){return T<0?A(new u(-T)):new u(T)},bigint:function(T){return T<0n?A(new u(-T)):new u(T)},Complex:function(T){throw new Error("Cannot convert Complex number to Node")},string:function(T){return new u(T)},Matrix:function(T){return new l(T.valueOf().map(I=>x(I)))}});function N(B){return bt(B)?B:x(B)}function D(B,T){var I=T&&T.exactFractions!==!1;if(I&&isFinite(B)&&s){var U=s(B),L=T&&typeof T.fractionsLimit=="number"?T.fractionsLimit:1/0;if(U.valueOf()===B&&U.n<L&&U.d<L)return U}return B}var C=e({"string, Object":function(T,I){var U=wn(T,t);if(U==="BigNumber")return a===void 0&&rv(),a(T);if(U==="bigint")return BigInt(T);if(U==="Fraction")return s===void 0&&Cx(),s(T);var L=parseFloat(T);return D(L,I)},"Fraction, Object":function(T,I){return T},"BigNumber, Object":function(T,I){return T},"number, Object":function(T,I){return D(T,I)},"bigint, Object":function(T,I){return T},"Complex, Object":function(T,I){return T.im!==0?T:D(T.re,I)},"Matrix, Object":function(T,I){return i(D(T.valueOf()))},"Array, Object":function(T,I){return T.map(D)}});function A(B){return new d("-","unaryMinus",[B])}function E(B){var T=L=>t.number==="BigNumber"&&a?a(L):Number(L),I=B.s*B.n,U=I<0n?new d("-","unaryMinus",[new u(-T(I))]):new u(T(I));return B.d===1n?U:new d("/","divide",[U,new u(T(B.d))])}function F(B,T,I){if(!xn(T))return new o(N(B),N(T));if(Vr(B)||Re(B)){for(var U=Array.from(T.dimensions);U.length>0;)if(ct(U[0])&&typeof U[0].value!="string"){var L=C(U.shift().value,I);Vr(B)?B=B.items[L-1]:(B=B.valueOf()[L-1],B instanceof Array&&(B=i(B)))}else if(U.length>1&&ct(U[1])&&typeof U[1].value!="string"){var Y=C(U[1].value,I),ee=[],_=Vr(B)?B.items:B.valueOf();for(var V of _)if(Vr(V))ee.push(V.items[Y-1]);else if(Re(B))ee.push(V[Y-1]);else break;if(ee.length===_.length)Vr(B)?B=new l(ee):B=i(ee),U.splice(1,1);else break}else break;return U.length===T.dimensions.length?new o(N(B),T):U.length>0?(T=new h(U),new o(N(B),T)):B}if(js(B)&&T.dimensions.length===1&&ct(T.dimensions[0])){var z=T.dimensions[0].value;return z in B.properties?B.properties[z]:new u}return new o(N(B),T)}function O(B,T,I,U){var L=T.shift(),Y=T.reduce((ee,_)=>{if(!bt(_)){var V=ee.pop();if(bt(V))return[V,_];try{return ee.push(w(B,[V,_],U)),ee}catch{ee.push(V)}}ee.push(N(ee.pop()));var z=ee.length===1?ee[0]:I(ee);return[I([z,N(_)])]},[L]);return Y.length===1?Y[0]:I([Y[0],x(Y[1])])}function k(B,T){switch(B.type){case"SymbolNode":return B;case"ConstantNode":switch(typeof B.value){case"number":return C(B.value,T);case"bigint":return C(B.value,T);case"string":return B.value;default:if(!isNaN(B.value))return C(B.value,T)}return B;case"FunctionNode":if(r[B.name]&&r[B.name].rawArgs)return B;{var I=["add","multiply"];if(!I.includes(B.name)){var U=B.args.map(K=>k(K,T));if(!U.some(bt))try{return w(B.name,U,T)}catch{}if(B.name==="size"&&U.length===1&&Vr(U[0])){for(var L=[],Y=U[0];Vr(Y);)L.push(Y.items.length),Y=Y.items[0];return i(L)}return new c(B.name,U.map(N))}}case"OperatorNode":{var ee=B.fn.toString(),_,V,z=S(B);if(qt(B)&&B.isUnary())_=[k(B.args[0],T)],bt(_[0])?V=z(_):V=w(ee,_,T);else if(y(B,T.context))if(_=v(B,T.context),_=_.map(K=>k(K,T)),m(ee,T.context)){for(var de=[],ae=[],oe=0;oe<_.length;oe++)bt(_[oe])?ae.push(_[oe]):de.push(_[oe]);de.length>1?(V=O(ee,de,z,T),ae.unshift(V),V=O(ee,ae,z,T)):V=O(ee,_,z,T)}else V=O(ee,_,z,T);else _=B.args.map(K=>k(K,T)),V=O(ee,_,z,T);return V}case"ParenthesisNode":return k(B.content,T);case"AccessorNode":return F(k(B.object,T),k(B.index,T),T);case"ArrayNode":{var $=B.items.map(K=>k(K,T));return $.some(bt)?new l($.map(N)):i($)}case"IndexNode":return new h(B.dimensions.map(K=>g(K,T)));case"ObjectNode":{var H={};for(var J in B.properties)H[J]=g(B.properties[J],T);return new f(H)}case"AssignmentNode":case"BlockNode":case"FunctionAssignmentNode":case"RangeNode":case"ConditionalNode":default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(B.type))}}return g}),wN="simplifyCore",JL=["typed","parse","equal","isZero","add","subtract","multiply","divide","pow","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Td=R(wN,JL,n=>{var{typed:e,parse:t,equal:r,isZero:i,add:s,subtract:a,multiply:o,divide:l,pow:u,AccessorNode:c,ArrayNode:h,ConstantNode:f,FunctionNode:d,IndexNode:p,ObjectNode:m,OperatorNode:y,ParenthesisNode:v,SymbolNode:S}=n,g=new f(0),b=new f(1),w=new f(!0),x=new f(!1);function N(E){return qt(E)&&["and","not","or"].includes(E.op)}var{hasProperty:D,isCommutative:C}=wv({FunctionNode:d,OperatorNode:y,SymbolNode:S});function A(E){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},O=F?F.context:void 0;if(D(E,"trivial",O)){if(qi(E)&&E.args.length===1)return A(E.args[0],F);var k=!1,B=0;if(E.forEach(ae=>{++B,B===1&&(k=A(ae,F))}),B===1)return k}var T=E;if(qi(T)){var I=t4(T.name);if(I){if(T.args.length>2&&D(T,"associative",O))for(;T.args.length>2;){var U=T.args.pop(),L=T.args.pop();T.args.push(new y(I,T.name,[U,L]))}T=new y(I,T.name,T.args)}else return new d(A(T.fn),T.args.map(ae=>A(ae,F)))}if(qt(T)&&T.isUnary()){var Y=A(T.args[0],F);if(T.op==="~"&&qt(Y)&&Y.isUnary()&&Y.op==="~"||T.op==="not"&&qt(Y)&&Y.isUnary()&&Y.op==="not"&&N(Y.args[0]))return Y.args[0];var ee=!0;if(T.op==="-"&&qt(Y)&&(Y.isBinary()&&Y.fn==="subtract"&&(T=new y("-","subtract",[Y.args[1],Y.args[0]]),ee=!1),Y.isUnary()&&Y.op==="-"))return Y.args[0];if(ee)return new y(T.op,T.fn,[Y])}if(qt(T)&&T.isBinary()){var _=A(T.args[0],F),V=A(T.args[1],F);if(T.op==="+"){if(ct(_)&&i(_.value))return V;if(ct(V)&&i(V.value))return _;qt(V)&&V.isUnary()&&V.op==="-"&&(V=V.args[0],T=new y("-","subtract",[_,V]))}if(T.op==="-")return qt(V)&&V.isUnary()&&V.op==="-"?A(new y("+","add",[_,V.args[0]]),F):ct(_)&&i(_.value)?A(new y("-","unaryMinus",[V])):ct(V)&&i(V.value)?_:new y(T.op,T.fn,[_,V]);if(T.op==="*"){if(ct(_)){if(i(_.value))return g;if(r(_.value,1))return V}if(ct(V)){if(i(V.value))return g;if(r(V.value,1))return _;if(C(T,O))return new y(T.op,T.fn,[V,_],T.implicit)}return new y(T.op,T.fn,[_,V],T.implicit)}if(T.op==="/")return ct(_)&&i(_.value)?g:ct(V)&&r(V.value,1)?_:new y(T.op,T.fn,[_,V]);if(T.op==="^"&&ct(V)){if(i(V.value))return b;if(r(V.value,1))return _}if(T.op==="and"){if(ct(_))if(_.value){if(N(V))return V;if(ct(V))return V.value?w:x}else return x;if(ct(V))if(V.value){if(N(_))return _}else return x}if(T.op==="or"){if(ct(_)){if(_.value)return w;if(N(V))return V}if(ct(V)){if(V.value)return w;if(N(_))return _}}return new y(T.op,T.fn,[_,V])}if(qt(T))return new y(T.op,T.fn,T.args.map(ae=>A(ae,F)));if(Vr(T))return new h(T.items.map(ae=>A(ae,F)));if(en(T))return new c(A(T.object,F),A(T.index,F));if(xn(T))return new p(T.dimensions.map(ae=>A(ae,F)));if(js(T)){var z={};for(var de in T.properties)z[de]=A(T.properties[de],F);return new m(z)}return T}return e(wN,{Node:A,"Node,Object":A})}),ZL="resolve",QL=["typed","parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],Fd=R(ZL,QL,n=>{var{typed:e,parse:t,ConstantNode:r,FunctionNode:i,OperatorNode:s,ParenthesisNode:a}=n;function o(l,u){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;if(!u)return l;if(Xt(l)){if(c.has(l.name)){var h=Array.from(c).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(h,"}"))}var f=u.get(l.name);if(bt(f)){var d=new Set(c);return d.add(l.name),o(f,u,d)}else return typeof f=="number"?t(String(f)):f!==void 0?new r(f):l}else if(qt(l)){var p=l.args.map(function(y){return o(y,u,c)});return new s(l.op,l.fn,p,l.implicit)}else{if(Ai(l))return new a(o(l.content,u,c));if(qi(l)){var m=l.args.map(function(y){return o(y,u,c)});return new i(l.name,m)}}return l.map(y=>o(y,u,c))}return e("resolve",{Node:o,"Node, Map | null | undefined":o,"Node, Object":(l,u)=>o(l,Us(u)),"Array | Matrix":e.referToSelf(l=>u=>u.map(c=>l(c))),"Array | Matrix, null | undefined":e.referToSelf(l=>u=>u.map(c=>l(c))),"Array, Object":e.referTo("Array,Map",l=>(u,c)=>l(u,Us(c))),"Matrix, Object":e.referTo("Matrix,Map",l=>(u,c)=>l(u,Us(c))),"Array | Matrix, Map":e.referToSelf(l=>(u,c)=>u.map(h=>l(h,c)))})}),SN="symbolicEqual",KL=["parse","simplify","typed","OperatorNode"],_d=R(SN,KL,n=>{var{parse:e,simplify:t,typed:r,OperatorNode:i}=n;function s(a,o){var l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},u=new i("-","subtract",[a,o]),c=t(u,{},l);return ct(c)&&!c.value}return r(SN,{"Node, Node":s,"Node, Node, Object":s})}),NN="derivative",e8=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],Od=R(NN,e8,n=>{var{typed:e,config:t,parse:r,simplify:i,equal:s,isZero:a,numeric:o,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:h,SymbolNode:f}=n;function d(b,w){var x=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{simplify:!0},N=new Map,D=w.name;function C(E){var F=N.get(E);if(F!==void 0)return F;var O=v(C,E,D);return N.set(E,O),O}var A=S(b,C);return x.simplify?i(A):A}function p(b){var w=r(b);if(!w.isSymbolNode)throw new TypeError("Invalid variable. "+"Cannot parse ".concat(JSON.stringify(b)," into a variable in function derivative"));return w}var m=e(NN,{"Node, SymbolNode":d,"Node, SymbolNode, Object":d,"Node, string":(b,w)=>d(b,p(w)),"Node, string, Object":(b,w,x)=>d(b,p(w),x)});m._simplify=!0,m.toTex=function(b){return y.apply(null,b.args)};var y=e("_derivTex",{"Node, SymbolNode":function(w,x){return ct(w)&&Dt(w.value)==="string"?y(r(w.value).toString(),x.toString(),1):y(w.toTex(),x.toString(),1)},"Node, ConstantNode":function(w,x){if(Dt(x.value)==="string")return y(w,r(x.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(w,x,N){return y(w.toString(),x.name,N.value)},"string, string, number":function(w,x,N){var D;return N===1?D="{d\\over d"+x+"}":D="{d^{"+N+"}\\over d"+x+"^{"+N+"}}",D+"\\left[".concat(w,"\\right]")}}),v=e("_isConst",{"function, ConstantNode, string":function(){return!0},"function, SymbolNode, string":function(w,x,N){return x.name!==N},"function, ParenthesisNode, string":function(w,x,N){return w(x.content,N)},"function, FunctionAssignmentNode, string":function(w,x,N){return x.params.includes(N)?w(x.expr,N):!0},"function, FunctionNode | OperatorNode, string":function(w,x,N){return x.args.every(D=>w(D,N))}}),S=e("_derivative",{"ConstantNode, function":function(){return g(0)},"SymbolNode, function":function(w,x){return x(w)?g(0):g(1)},"ParenthesisNode, function":function(w,x){return new h(S(w.content,x))},"FunctionAssignmentNode, function":function(w,x){return x(w)?g(0):S(w.expr,x)},"FunctionNode, function":function(w,x){if(x(w))return g(0);var N=w.args[0],D,C=!1,A=!1,E;switch(w.name){case"cbrt":C=!0,E=new c("*","multiply",[g(3),new c("^","pow",[N,new c("/","divide",[g(2),g(3)])])]);break;case"sqrt":case"nthRoot":if(w.args.length===1)C=!0,E=new c("*","multiply",[g(2),new u("sqrt",[N])]);else if(w.args.length===2)return D=new c("/","divide",[g(1),w.args[1]]),S(new c("^","pow",[N,D]),x);break;case"log10":D=g(10);case"log":if(!D&&w.args.length===1)E=N.clone(),C=!0;else if(w.args.length===1&&D||w.args.length===2&&x(w.args[1]))E=new c("*","multiply",[N.clone(),new u("log",[D||w.args[1]])]),C=!0;else if(w.args.length===2)return S(new c("/","divide",[new u("log",[N]),new u("log",[w.args[1]])]),x);break;case"pow":if(w.args.length===2)return S(new c("^","pow",[N,w.args[1]]),x);break;case"exp":E=new u("exp",[N.clone()]);break;case"sin":E=new u("cos",[N.clone()]);break;case"cos":E=new c("-","unaryMinus",[new u("sin",[N.clone()])]);break;case"tan":E=new c("^","pow",[new u("sec",[N.clone()]),g(2)]);break;case"sec":E=new c("*","multiply",[w,new u("tan",[N.clone()])]);break;case"csc":A=!0,E=new c("*","multiply",[w,new u("cot",[N.clone()])]);break;case"cot":A=!0,E=new c("^","pow",[new u("csc",[N.clone()]),g(2)]);break;case"asin":C=!0,E=new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])]);break;case"acos":C=!0,A=!0,E=new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])]);break;case"atan":C=!0,E=new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)]);break;case"asec":C=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acsc":C=!0,A=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acot":C=!0,A=!0,E=new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)]);break;case"sinh":E=new u("cosh",[N.clone()]);break;case"cosh":E=new u("sinh",[N.clone()]);break;case"tanh":E=new c("^","pow",[new u("sech",[N.clone()]),g(2)]);break;case"sech":A=!0,E=new c("*","multiply",[w,new u("tanh",[N.clone()])]);break;case"csch":A=!0,E=new c("*","multiply",[w,new u("coth",[N.clone()])]);break;case"coth":A=!0,E=new c("^","pow",[new u("csch",[N.clone()]),g(2)]);break;case"asinh":C=!0,E=new u("sqrt",[new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)])]);break;case"acosh":C=!0,E=new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])]);break;case"atanh":C=!0,E=new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])]);break;case"asech":C=!0,A=!0,E=new c("*","multiply",[N.clone(),new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])])]);break;case"acsch":C=!0,A=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acoth":C=!0,A=!0,E=new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])]);break;case"abs":E=new c("/","divide",[new u(new f("abs"),[N.clone()]),N.clone()]);break;case"gamma":default:throw new Error('Cannot process function "'+w.name+'" in derivative: the function is not supported, undefined, or the number of arguments passed to it are not supported')}var F,O;C?(F="/",O="divide"):(F="*",O="multiply");var k=S(N,x);return A&&(k=new c("-","unaryMinus",[k])),new c(F,O,[k,E])},"OperatorNode, function":function(w,x){if(x(w))return g(0);if(w.op==="+")return new c(w.op,w.fn,w.args.map(function(T){return S(T,x)}));if(w.op==="-"){if(w.isUnary())return new c(w.op,w.fn,[S(w.args[0],x)]);if(w.isBinary())return new c(w.op,w.fn,[S(w.args[0],x),S(w.args[1],x)])}if(w.op==="*"){var N=w.args.filter(function(T){return x(T)});if(N.length>0){var D=w.args.filter(function(T){return!x(T)}),C=D.length===1?D[0]:new c("*","multiply",D),A=N.concat(S(C,x));return new c("*","multiply",A)}return new c("+","add",w.args.map(function(T){return new c("*","multiply",w.args.map(function(I){return I===T?S(I,x):I.clone()}))}))}if(w.op==="/"&&w.isBinary()){var E=w.args[0],F=w.args[1];return x(F)?new c("/","divide",[S(E,x),F]):x(E)?new c("*","multiply",[new c("-","unaryMinus",[E]),new c("/","divide",[S(F,x),new c("^","pow",[F.clone(),g(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[S(E,x),F.clone()]),new c("*","multiply",[E.clone(),S(F,x)])]),new c("^","pow",[F.clone(),g(2)])])}if(w.op==="^"&&w.isBinary()){var O=w.args[0],k=w.args[1];if(x(O))return ct(O)&&(a(O.value)||s(O.value,1))?g(0):new c("*","multiply",[w,new c("*","multiply",[new u("log",[O.clone()]),S(k.clone(),x)])]);if(x(k)){if(ct(k)){if(a(k.value))return g(0);if(s(k.value,1))return S(O,x)}var B=new c("^","pow",[O.clone(),new c("-","subtract",[k,g(1)])]);return new c("*","multiply",[k.clone(),new c("*","multiply",[S(O,x),B])])}return new c("*","multiply",[new c("^","pow",[O.clone(),k.clone()]),new c("+","add",[new c("*","multiply",[S(O,x),new c("/","divide",[k.clone(),O.clone()])]),new c("*","multiply",[S(k,x),new u("log",[O.clone()])])])])}throw new Error('Cannot process operator "'+w.op+'" in derivative: the operator is not supported, undefined, or the number of arguments passed to it are not supported')}});function g(b,w){return new l(o(b,wn(String(b),t)))}return m}),CN="rationalize",t8=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyConstant","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],Bd=R(CN,t8,n=>{var{config:e,typed:t,equal:r,isZero:i,add:s,subtract:a,multiply:o,divide:l,pow:u,parse:c,simplifyConstant:h,simplifyCore:f,simplify:d,fraction:p,bignumber:m,mathWithTransform:y,matrix:v,AccessorNode:S,ArrayNode:g,ConstantNode:b,FunctionNode:w,IndexNode:x,ObjectNode:N,OperatorNode:D,SymbolNode:C,ParenthesisNode:A}=n;function E(T){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,L=O(),Y=F(T,I,!0,L.firstRules),ee=Y.variables.length,_={exactFractions:!1},V={exactFractions:!0};if(T=Y.expression,ee>=1){T=k(T);var z,de,ae=!0,oe=!1;T=d(T,L.firstRules,{},_);for(var $;de=ae?L.distrDivRules:L.sucDivRules,T=d(T,de,{},V),ae=!ae,$=T.toString(),$!==z;)oe=!0,z=$;oe&&(T=d(T,L.firstRulesAgain,{},_)),T=d(T,L.finalRules,{},_)}var H=[],J={};return T.type==="OperatorNode"&&T.isBinary()&&T.op==="/"?(ee===1&&(T.args[0]=B(T.args[0],H),T.args[1]=B(T.args[1])),U&&(J.numerator=T.args[0],J.denominator=T.args[1])):(ee===1&&(T=B(T,H)),U&&(J.numerator=T,J.denominator=null)),U?(J.coefficients=H,J.variables=Y.variables,J.expression=T,J):T}return t(CN,{Node:E,"Node, boolean":(T,I)=>E(T,{},I),"Node, Object":E,"Node, Object, boolean":E});function F(T,I,U,L){var Y=[],ee=d(T,L,I,{exactFractions:!1});U=!!U;var _="+-*"+(U?"/":"");z(ee);var V={};return V.expression=ee,V.variables=Y,V;function z(de){var ae=de.type;if(ae==="FunctionNode")throw new Error("There is an unsolved function call");if(ae==="OperatorNode")if(de.op==="^"){if(de.args[1].type!=="ConstantNode"||!ke(parseFloat(de.args[1].value)))throw new Error("There is a non-integer exponent");z(de.args[0])}else{if(!_.includes(de.op))throw new Error("Operator "+de.op+" invalid in polynomial expression");for(var oe=0;oe<de.args.length;oe++)z(de.args[oe])}else if(ae==="SymbolNode"){var $=de.name,H=Y.indexOf($);H===-1&&Y.push($)}else if(ae==="ParenthesisNode")z(de.content);else if(ae!=="ConstantNode")throw new Error("type "+ae+" is not allowed in polynomial expression")}}function O(){var T=[f,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},h,{l:"n*(n1^-1)",r:"n/n1"},{l:"n*n1^-n2",r:"n/n1^n2"},{l:"n1^-1",r:"1/n1"},{l:"n*(n1/n2)",r:"(n*n1)/n2"},{l:"1*n",r:"n"}],I=[{l:"(-n1)/(-n2)",r:"n1/n2"},{l:"(-n1)*(-n2)",r:"n1*n2"},{l:"n1--n2",r:"n1+n2"},{l:"n1-n2",r:"n1+(-n2)"},{l:"(n1+n2)*n3",r:"(n1*n3 + n2*n3)"},{l:"n1*(n2+n3)",r:"(n1*n2+n1*n3)"},{l:"c1*n + c2*n",r:"(c1+c2)*n"},{l:"c1*n + n",r:"(c1+1)*n"},{l:"c1*n - c2*n",r:"(c1-c2)*n"},{l:"c1*n - n",r:"(c1-1)*n"},{l:"v/c",r:"(1/c)*v"},{l:"v/-c",r:"-(1/c)*v"},{l:"-v*-c",r:"c*v"},{l:"-v*c",r:"-c*v"},{l:"v*-c",r:"-c*v"},{l:"v*c",r:"c*v"},{l:"-(-n1*n2)",r:"(n1*n2)"},{l:"-(n1*n2)",r:"(-n1*n2)"},{l:"-(-n1+n2)",r:"(n1-n2)"},{l:"-(n1+n2)",r:"(-n1-n2)"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"},{l:"-(-n1/n2)",r:"(n1/n2)"},{l:"-(n1/n2)",r:"(-n1/n2)"}],U=[{l:"(n1/n2 + n3/n4)",r:"((n1*n4 + n3*n2)/(n2*n4))"},{l:"(n1/n2 + n3)",r:"((n1 + n3*n2)/n2)"},{l:"(n1 + n2/n3)",r:"((n1*n3 + n2)/n3)"}],L=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],Y={};return Y.firstRules=T.concat(I,L),Y.distrDivRules=U,Y.sucDivRules=L,Y.firstRulesAgain=T.concat(I),Y.finalRules=[f,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},h,{l:"n*-n^n1",r:"-n^(n1+1)"},{l:"n*n^n1",r:"n^(n1+1)"},{l:"n^n1*-n^n2",r:"-n^(n1+n2)"},{l:"n^n1*n^n2",r:"n^(n1+n2)"},{l:"n^n1*-n",r:"-n^(n1+1)"},{l:"n^n1*n",r:"n^(n1+1)"},{l:"n^n1/-n",r:"-n^(n1-1)"},{l:"n^n1/n",r:"n^(n1-1)"},{l:"n/-n^n1",r:"-n^(1-n1)"},{l:"n/n^n1",r:"n^(1-n1)"},{l:"n^n1/-n^n2",r:"n^(n1-n2)"},{l:"n^n1/n^n2",r:"n^(n1-n2)"},{l:"n1+(-n2*n3)",r:"n1-n2*n3"},{l:"v*(-c)",r:"-c*v"},{l:"n1+-n2",r:"n1-n2"},{l:"v*c",r:"c*v"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"}],Y}function k(T,I,U){var L=T.type,Y=arguments.length>1;if(L==="OperatorNode"&&T.isBinary()){var ee=!1,_;if(T.op==="^"&&(T.args[0].type==="ParenthesisNode"||T.args[0].type==="OperatorNode")&&T.args[1].type==="ConstantNode"&&(_=parseFloat(T.args[1].value),ee=_>=2&&ke(_)),ee){if(_>2){var V=T.args[0],z=new D("^","pow",[T.args[0].cloneDeep(),new b(_-1)]);T=new D("*","multiply",[V,z])}else T=new D("*","multiply",[T.args[0],T.args[0].cloneDeep()]);Y&&(U==="content"?I.content=T:I.args[U]=T)}}if(L==="ParenthesisNode")k(T.content,T,"content");else if(L!=="ConstantNode"&&L!=="SymbolNode")for(var de=0;de<T.args.length;de++)k(T.args[de],T,de);if(!Y)return T}function B(T,I){I===void 0&&(I=[]),I[0]=0;var U={};U.cte=1,U.oper="+",U.fire="";var L=0,Y="";$(T,null,U),L=I.length-1;for(var ee=!0,_,V=L;V>=0;V--)if(I[V]!==0){var z=new b(ee?I[V]:Math.abs(I[V])),de=I[V]<0?"-":"+";if(V>0){var ae=new C(Y);if(V>1){var oe=new b(V);ae=new D("^","pow",[ae,oe])}I[V]===-1&&ee?z=new D("-","unaryMinus",[ae]):Math.abs(I[V])===1?z=ae:z=new D("*","multiply",[z,ae])}ee?_=z:de==="+"?_=new D("+","add",[_,z]):_=new D("-","subtract",[_,z]),ee=!1}if(ee)return new b(0);return _;function $(H,J,K){var te=H.type;if(te==="FunctionNode")throw new Error("There is an unsolved function call");if(te==="OperatorNode"){if(!"+-*^".includes(H.op))throw new Error("Operator "+H.op+" invalid");if(J!==null){if((H.fn==="unaryMinus"||H.fn==="pow")&&J.fn!=="add"&&J.fn!=="subtract"&&J.fn!=="multiply")throw new Error("Invalid "+H.op+" placing");if((H.fn==="subtract"||H.fn==="add"||H.fn==="multiply")&&J.fn!=="add"&&J.fn!=="subtract")throw new Error("Invalid "+H.op+" placing");if((H.fn==="subtract"||H.fn==="add"||H.fn==="unaryMinus")&&K.noFil!==0)throw new Error("Invalid "+H.op+" placing")}(H.op==="^"||H.op==="*")&&(K.fire=H.op);for(var fe=0;fe<H.args.length;fe++)H.fn==="unaryMinus"&&(K.oper="-"),(H.op==="+"||H.fn==="subtract")&&(K.fire="",K.cte=1,K.oper=fe===0?"+":H.op),K.noFil=fe,$(H.args[fe],H,K)}else if(te==="SymbolNode"){if(H.name!==Y&&Y!=="")throw new Error("There is more than one variable");if(Y=H.name,J===null){I[1]=1;return}if(J.op==="^"&&K.noFil!==0)throw new Error("In power the variable should be the first parameter");if(J.op==="*"&&K.noFil!==1)throw new Error("In multiply the variable should be the second parameter");(K.fire===""||K.fire==="*")&&(L<1&&(I[1]=0),I[1]+=K.cte*(K.oper==="+"?1:-1),L=Math.max(1,L))}else if(te==="ConstantNode"){var le=parseFloat(H.value);if(J===null){I[0]=le;return}if(J.op==="^"){if(K.noFil!==1)throw new Error("Constant cannot be powered");if(!ke(le)||le<=0)throw new Error("Non-integer exponent is not allowed");for(var Se=L+1;Se<le;Se++)I[Se]=0;le>L&&(I[le]=0),I[le]+=K.cte*(K.oper==="+"?1:-1),L=Math.max(le,L);return}K.cte=le,K.fire===""&&(I[0]+=K.cte*(K.oper==="+"?1:-1))}else throw new Error("Type "+te+" is not allowed")}}}),DN="zpk2tf",r8=["typed","add","multiply","Complex","number"],kd=R(DN,r8,n=>{var{typed:e,add:t,multiply:r,Complex:i,number:s}=n;return e(DN,{"Array,Array,number":function(u,c,h){return a(u,c,h)},"Array,Array":function(u,c){return a(u,c,1)},"Matrix,Matrix,number":function(u,c,h){return a(u.valueOf(),c.valueOf(),h)},"Matrix,Matrix":function(u,c){return a(u.valueOf(),c.valueOf(),1)}});function a(l,u,c){l.some(S=>S.type==="BigNumber")&&(l=l.map(S=>s(S))),u.some(S=>S.type==="BigNumber")&&(u=u.map(S=>s(S)));for(var h=[i(1,0)],f=[i(1,0)],d=0;d<l.length;d++){var p=l[d];typeof p=="number"&&(p=i(p,0)),h=o(h,[i(1,0),i(-p.re,-p.im)])}for(var m=0;m<u.length;m++){var y=u[m];typeof y=="number"&&(y=i(y,0)),f=o(f,[i(1,0),i(-y.re,-y.im)])}for(var v=0;v<h.length;v++)h[v]=r(h[v],c);return[h,f]}function o(l,u){for(var c=[],h=0;h<l.length+u.length-1;h++){c[h]=i(0,0);for(var f=0;f<l.length;f++)h-f>=0&&h-f<u.length&&(c[h]=t(c[h],r(l[f],u[h-f])))}return c}}),AN="freqz",i8=["typed","add","multiply","Complex","divide","matrix"],Pd=R(AN,i8,n=>{var{typed:e,add:t,multiply:r,Complex:i,divide:s,matrix:a}=n;return e(AN,{"Array, Array":function(c,h){var f=l(512);return o(c,h,f)},"Array, Array, Array":function(c,h,f){return o(c,h,f)},"Array, Array, number":function(c,h,f){if(f<0)throw new Error("w must be a positive number");var d=l(f);return o(c,h,d)},"Matrix, Matrix":function(c,h){var f=l(512),{w:d,h:p}=o(c.valueOf(),h.valueOf(),f);return{w:a(d),h:a(p)}},"Matrix, Matrix, Matrix":function(c,h,f){var{h:d}=o(c.valueOf(),h.valueOf(),f.valueOf());return{h:a(d),w:a(f)}},"Matrix, Matrix, number":function(c,h,f){if(f<0)throw new Error("w must be a positive number");var d=l(f),{h:p}=o(c.valueOf(),h.valueOf(),d);return{h:a(p),w:a(d)}}});function o(u,c,h){for(var f=[],d=[],p=0;p<h.length;p++){for(var m=i(0,0),y=i(0,0),v=0;v<u.length;v++)m=t(m,r(u[v],i(Math.cos(-v*h[p]),Math.sin(-v*h[p]))));for(var S=0;S<c.length;S++)y=t(y,r(c[S],i(Math.cos(-S*h[p]),Math.sin(-S*h[p]))));f.push(m),d.push(y)}for(var g=[],b=0;b<f.length;b++)g.push(s(f[b],d[b]));return{h:g,w:h}}function l(u){for(var c=[],h=0;h<u;h++)c.push(h/u*Math.PI);return c}}),n8="reviver",s8=["classes"],zd=R(n8,s8,n=>{var{classes:e}=n;return function(r,i){var s=e[i&&i.mathjs];return s&&typeof s.fromJSON=="function"?s.fromJSON(i):i}}),a8="replacer",o8=[],Rd=R(a8,o8,()=>function(e,t){return typeof t=="number"&&(!isFinite(t)||isNaN(t))?{mathjs:"number",value:String(t)}:typeof t=="bigint"?{mathjs:"bigint",value:String(t)}:t}),u8="14.9.1",Ld=R("true",[],()=>!0),Id=R("false",[],()=>!1),$d=R("null",[],()=>null),qd=ei("Infinity",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1/0):1/0}),Hd=ei("NaN",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(NaN):NaN}),Ud=ei("pi",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?sv(t):PT}),Vd=ei("tau",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?K3(t):zT}),Wd=ei("e",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?Z3(t):RT}),jd=ei("phi",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?Q3(t):LT}),Gd=ei("LN2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(2).ln():Math.LN2}),Xd=ei("LN10",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(10).ln():Math.LN10}),Yd=ei("LOG2E",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1).div(new t(2).ln()):Math.LOG2E}),Jd=ei("LOG10E",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1).div(new t(10).ln()):Math.LOG10E}),Zd=ei("SQRT1_2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t("0.5").sqrt():Math.SQRT1_2}),Qd=ei("SQRT2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(2).sqrt():Math.SQRT2}),Kd=ei("i",["Complex"],n=>{var{Complex:e}=n;return e.I}),Sv=R("PI",["pi"],n=>{var{pi:e}=n;return e}),Nv=R("E",["e"],n=>{var{e}=n;return e}),ep=R("version",[],()=>u8);function ei(n,e,t){return R(n,e,t,{recreateOnConfigChange:!0})}var tp=Ze("speedOfLight","299792458","m s^-1"),rp=Ze("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),ip=Ze("planckConstant","6.62607015e-34","J s"),np=Ze("reducedPlanckConstant","1.0545718176461565e-34","J s"),sp=Ze("magneticConstant","1.25663706212e-6","N A^-2"),ap=Ze("electricConstant","8.8541878128e-12","F m^-1"),op=Ze("vacuumImpedance","376.730313667","ohm"),up=Ze("coulomb","8.987551792261171e9","N m^2 C^-2"),lp=Ze("coulombConstant","8.987551792261171e9","N m^2 C^-2"),cp=Ze("elementaryCharge","1.602176634e-19","C"),hp=Ze("bohrMagneton","9.2740100783e-24","J T^-1"),fp=Ze("conductanceQuantum","7.748091729863649e-5","S"),dp=Ze("inverseConductanceQuantum","12906.403729652257","ohm"),pp=Ze("magneticFluxQuantum","2.0678338484619295e-15","Wb"),mp=Ze("nuclearMagneton","5.0507837461e-27","J T^-1"),gp=Ze("klitzing","25812.807459304513","ohm"),vp=Ze("bohrRadius","5.29177210903e-11","m"),yp=Ze("classicalElectronRadius","2.8179403262e-15","m"),bp=Ze("electronMass","9.1093837015e-31","kg"),xp=Ze("fermiCoupling","1.1663787e-5","GeV^-2"),wp=Qp("fineStructure",.0072973525693),Sp=Ze("hartreeEnergy","4.3597447222071e-18","J"),Np=Ze("protonMass","1.67262192369e-27","kg"),Cp=Ze("deuteronMass","3.3435830926e-27","kg"),Dp=Ze("neutronMass","1.6749271613e-27","kg"),Ap=Ze("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),Ep=Ze("rydberg","10973731.568160","m^-1"),Mp=Ze("thomsonCrossSection","6.6524587321e-29","m^2"),Tp=Qp("weakMixingAngle",.2229),Fp=Qp("efimovFactor",22.7),_p=Ze("atomicMass","1.66053906660e-27","kg"),Op=Ze("avogadro","6.02214076e23","mol^-1"),Bp=Ze("boltzmann","1.380649e-23","J K^-1"),kp=Ze("faraday","96485.33212331001","C mol^-1"),Pp=Ze("firstRadiation","3.7417718521927573e-16","W m^2"),zp=Ze("loschmidt","2.686780111798444e25","m^-3"),Rp=Ze("gasConstant","8.31446261815324","J K^-1 mol^-1"),Lp=Ze("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),Ip=Ze("molarVolume","0.022413969545014137","m^3 mol^-1"),$p=Qp("sackurTetrode",-1.16487052358),qp=Ze("secondRadiation","0.014387768775039337","m K"),Hp=Ze("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),Up=Ze("wienDisplacement","2.897771955e-3","m K"),Vp=Ze("molarMass","0.99999999965e-3","kg mol^-1"),Wp=Ze("molarMassC12","11.9999999958e-3","kg mol^-1"),jp=Ze("gravity","9.80665","m s^-2"),Gp=Ze("planckLength","1.616255e-35","m"),Xp=Ze("planckMass","2.176435e-8","kg"),Yp=Ze("planckTime","5.391245e-44","s"),Jp=Ze("planckCharge","1.87554603778e-18","C"),Zp=Ze("planckTemperature","1.416785e+32","K");function Ze(n,e,t){var r=["config","Unit","BigNumber"];return R(n,r,i=>{var{config:s,Unit:a,BigNumber:o}=i,l=s.number==="BigNumber"?new o(e):parseFloat(e),u=new a(l,t);return u.fixPrefix=!0,u})}function Qp(n,e){var t=["config","BigNumber"];return R(n,t,r=>{var{config:i,BigNumber:s}=r;return i.number==="BigNumber"?new s(e):e})}function EN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function l8(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?EN(Object(t),!0).forEach(function(r){Yt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):EN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var c8="mapSlices",h8=["typed","isInteger"],Kp=R(c8,h8,n=>{var{typed:e,isInteger:t}=n,r=la({typed:e,isInteger:t});return e("mapSlices",{"...any":function(s){var a=s[1];Je(a)?s[1]=a-1:Xe(a)&&(s[1]=a.minus(1));try{return r.apply(null,s)}catch(o){throw kr(o)}}})},l8({isTransformFunction:!0},la.meta)),f8="column",d8=["typed","Index","matrix","range"],em=R(f8,d8,n=>{var{typed:e,Index:t,matrix:r,range:i}=n,s=to({typed:e,Index:t,matrix:r,range:i});return e("column",{"...any":function(o){var l=o.length-1,u=o[l];Je(u)&&(o[l]=u-1);try{return s.apply(null,o)}catch(c){throw kr(c)}}})},{isTransformFunction:!0});function Cv(n,e,t){var r=n.filter(function(l){return Xt(l)&&!(l.name in e)&&!t.has(l.name)})[0];if(!r)throw new Error('No undefined variable found in inline expression "'+n+'"');var i=r.name,s=new Map,a=new wy(t,s,new Set([i])),o=n.compile();return function(u){return s.set(i,u),o.evaluate(a)}}var p8="transformCallback",m8=["typed"],Dv=R(p8,m8,n=>{var{typed:e}=n;return function(r,i){return e.isTypedFunction(r)?t(r,i):MN(r,r.length,i)};function t(r,i){var s=Object.fromEntries(Object.entries(r.signatures).map(a=>{var[o,l]=a,u=o.split(",").length;return e.isTypedFunction(l)?[o,t(l,i)]:[o,MN(l,u,i)]}));return typeof r.name=="string"?e(r.name,s):e(s)}});function MN(n,e,t){return e===t?n:e===t+1?function(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=i.slice(0,t),o=TN(i[t]);return n(...a,o)}:e>t+1?function(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=i.slice(0,t),o=TN(i[t]),l=i.slice(t+1);return n(...a,o,...l)}:n}function TN(n){return n.map(e=>e+1)}var g8="filter",v8=["typed"],tm=R(g8,v8,n=>{var{typed:e}=n;function t(i,s,a){var o=ro({typed:e}),l=Dv({typed:e});if(i.length===0)return o();var u=i[0];if(i.length===1)return o(u);var c=i.length-1,h=i[c];return u&&(u=r(u,a)),h&&(Xt(h)||rs(h)?h=r(h,a):h=Cv(h,s,a)),o(u,l(h,c))}t.rawArgs=!0;function r(i,s){return i.compile().evaluate(s)}return t},{isTransformFunction:!0}),y8="forEach",b8=["typed"],rm=R(y8,b8,n=>{var{typed:e}=n,t=io({typed:e}),r=Dv({typed:e});function i(a,o,l){if(a.length===0)return t();var u=a[0];if(a.length===1)return t(u);var c=a.length-1,h=a[c];return u&&(u=s(u,l)),h&&(Xt(h)||rs(h)?h=s(h,l):h=Cv(h,o,l)),t(u,r(h,c))}i.rawArgs=!0;function s(a,o){return a.compile().evaluate(o)}return i},{isTransformFunction:!0}),x8="index",w8=["Index","getMatrixDataType"],im=R(x8,w8,n=>{var{Index:e,getMatrixDataType:t}=n;return function(){for(var i=[],s=0,a=arguments.length;s<a;s++){var o=arguments[s];if(Ia(o))o.start--,o.end-=o.step>0?0:2;else if(o&&o.isSet===!0)o=o.map(function(u){return u-1});else if(St(o)||Re(o))t(o)!=="boolean"&&(o=o.map(function(u){return u-1}));else if(Je(o)||ts(o))o--;else if(Xe(o))o=o.toNumber()-1;else if(typeof o!="string")throw new TypeError("Dimension must be an Array, Matrix, number, bigint, string, or Range");i[s]=o}var l=new e;return e.apply(l,i),l}},{isTransformFunction:!0}),S8="map",N8=["typed"],nm=R(S8,N8,n=>{var{typed:e}=n,t=no({typed:e}),r=Dv({typed:e});function i(s,a,o){if(s.length===0)return t();if(s.length===1)return t(s[0]);var l=s.length-1,u=s.slice(0,l),c=s[l];return u=u.map(f=>h(f,o)),c&&(Xt(c)||rs(c)?c=h(c,o):c=Cv(c,a,o)),t(...u,r(c,l));function h(f,d){return f.compile().evaluate(d)}}return i.rawArgs=!0,i},{isTransformFunction:!0});function C8(n){return Je(n)?n-1:Xe(n)?n.minus(1):n}function D8(n){return Je(n)||Xe(n)}function Bn(n){if(n.length===2&&Or(n[0])){n=n.slice();var e=n[1];D8(e)&&(n[1]=C8(e))}return n}var A8="max",E8=["typed","config","numeric","larger","isNaN"],sm=R(A8,E8,n=>{var{typed:e,config:t,numeric:r,larger:i,isNaN:s}=n,a=po({typed:e,config:t,numeric:r,larger:i,isNaN:s});return e("max",{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),M8="mean",T8=["typed","add","divide"],am=R(M8,T8,n=>{var{typed:e,add:t,divide:r}=n,i=wo({typed:e,add:t,divide:r});return e("mean",{"...any":function(a){a=Bn(a);try{return i.apply(null,a)}catch(o){throw kr(o)}}})},{isTransformFunction:!0}),F8="min",_8=["typed","config","numeric","smaller","isNaN"],om=R(F8,_8,n=>{var{typed:e,config:t,numeric:r,smaller:i,isNaN:s}=n,a=mo({typed:e,config:t,numeric:r,smaller:i,isNaN:s});return e("min",{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),O8="range",B8=["typed","config","?matrix","?bignumber","equal","smaller","smallerEq","larger","largerEq","add","isZero","isPositive"],um=R(O8,B8,n=>{var{typed:e,config:t,matrix:r,bignumber:i,equal:s,smaller:a,smallerEq:o,larger:l,largerEq:u,add:c,isZero:h,isPositive:f}=n,d=ao({typed:e,config:t,matrix:r,bignumber:i,equal:s,smaller:a,smallerEq:o,larger:l,largerEq:u,add:c,isZero:h,isPositive:f});return e("range",{"...any":function(m){var y=m.length-1,v=m[y];return typeof v!="boolean"&&m.push(!0),d.apply(null,m)}})},{isTransformFunction:!0}),k8="row",P8=["typed","Index","matrix","range"],lm=R(k8,P8,n=>{var{typed:e,Index:t,matrix:r,range:i}=n,s=oo({typed:e,Index:t,matrix:r,range:i});return e("row",{"...any":function(o){var l=o.length-1,u=o[l];Je(u)&&(o[l]=u-1);try{return s.apply(null,o)}catch(c){throw kr(c)}}})},{isTransformFunction:!0}),z8="subset",R8=["typed","matrix","zeros","add"],cm=R(z8,R8,n=>{var{typed:e,matrix:t,zeros:r,add:i}=n,s=uo({typed:e,matrix:t,zeros:r,add:i});return e("subset",{"...any":function(o){try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),L8="concat",I8=["typed","matrix","isInteger"],hm=R(L8,I8,n=>{var{typed:e,matrix:t,isInteger:r}=n,i=eo({typed:e,matrix:t,isInteger:r});return e("concat",{"...any":function(a){var o=a.length-1,l=a[o];Je(l)?a[o]=l-1:Xe(l)&&(a[o]=l.minus(1));try{return i.apply(null,a)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),FN="diff",$8=["typed","matrix","subtract","number","bignumber"],fm=R(FN,$8,n=>{var{typed:e,matrix:t,subtract:r,number:i,bignumber:s}=n,a=so({typed:e,matrix:t,subtract:r,number:i,bignumber:s});return e(FN,{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),q8="std",H8=["typed","map","sqrt","variance"],dm=R(q8,H8,n=>{var{typed:e,map:t,sqrt:r,variance:i}=n,s=Co({typed:e,map:t,sqrt:r,variance:i});return e("std",{"...any":function(o){o=Bn(o);try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),_N="sum",U8=["typed","config","add","numeric"],pm=R(_N,U8,n=>{var{typed:e,config:t,add:r,numeric:i}=n,s=bo({typed:e,config:t,add:r,numeric:i});return e(_N,{"...any":function(o){o=Bn(o);try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),V8="quantileSeq",W8=["typed","bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger","mapSlices"],mm=R(V8,W8,n=>{var{typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d}=n,p=No({typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d});return e("quantileSeq",{"Array | Matrix, number | BigNumber":p,"Array | Matrix, number | BigNumber, number":(y,v,S)=>p(y,v,m(S)),"Array | Matrix, number | BigNumber, boolean":p,"Array | Matrix, number | BigNumber, boolean, number":(y,v,S,g)=>p(y,v,S,m(g)),"Array | Matrix, Array | Matrix":p,"Array | Matrix, Array | Matrix, number":(y,v,S)=>p(y,v,m(S)),"Array | Matrix, Array | Matrix, boolean":p,"Array | Matrix, Array | Matrix, boolean, number":(y,v,S,g)=>p(y,v,S,m(g))});function m(y){return Bn([[],y])[1]}},{isTransformFunction:!0}),ON="cumsum",j8=["typed","add","unaryPlus"],gm=R(ON,j8,n=>{var{typed:e,add:t,unaryPlus:r}=n,i=xo({typed:e,add:t,unaryPlus:r});return e(ON,{"...any":function(a){if(a.length===2&&Or(a[0])){var o=a[1];Je(o)?a[1]=o-1:Xe(o)&&(a[1]=o.minus(1))}try{return i.apply(null,a)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),BN="variance",G8=["typed","add","subtract","multiply","divide","mapSlices","isNaN"],vm=R(BN,G8,n=>{var{typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o}=n,l=So({typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o});return e(BN,{"...any":function(c){c=Bn(c);try{return l.apply(null,c)}catch(h){throw kr(h)}}})},{isTransformFunction:!0}),kN="print",X8=["typed","matrix","zeros","add"],ym=R(kN,X8,n=>{var{typed:e,matrix:t,zeros:r,add:i}=n,s=co({typed:e,matrix:t,zeros:r,add:i});return e(kN,{"string, Object | Array":function(l,u){return s(a(l),u)},"string, Object | Array, number | Object":function(l,u,c){return s(a(l),u,c)}});function a(o){return o.replace(Xx,l=>{var u=l.slice(1).split("."),c=u.map(function(h){return!isNaN(h)&&h.length>0?parseInt(h)-1:h});return"$"+c.join(".")})}},{isTransformFunction:!0}),Y8="and",J8=["typed","matrix","zeros","add","equalScalar","not","concat"],bm=R(Y8,J8,n=>{var{typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a}=n,o=fo({typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a});function l(u,c,h){var f=u[0].compile().evaluate(h);if(!Or(f)&&!o(f,!0))return!1;var d=u[1].compile().evaluate(h);return o(f,d)}return l.rawArgs=!0,l},{isTransformFunction:!0}),Z8="or",Q8=["typed","matrix","equalScalar","DenseMatrix","concat"],xm=R(Z8,Q8,n=>{var{typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s}=n,a=Ka({typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)&&a(h,!1))return!0;var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0}),K8="nullish",eI=["typed","matrix","size","flatten","deepEqual"],wm=R(K8,eI,n=>{var{typed:e,matrix:t,size:r,flatten:i,deepEqual:s}=n,a=Qa({typed:e,matrix:t,size:r,flatten:i,deepEqual:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)&&h!=null&&h!==void 0)return h;var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0}),tI="bitAnd",rI=["typed","matrix","zeros","add","equalScalar","not","concat"],Sm=R(tI,rI,n=>{var{typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a}=n,o=Ja({typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a});function l(u,c,h){var f=u[0].compile().evaluate(h);if(!Or(f)){if(isNaN(f))return NaN;if(f===0||f===!1)return 0}var d=u[1].compile().evaluate(h);return o(f,d)}return l.rawArgs=!0,l},{isTransformFunction:!0}),iI="bitOr",nI=["typed","matrix","equalScalar","DenseMatrix","concat"],Nm=R(iI,nI,n=>{var{typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s}=n,a=Za({typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)){if(isNaN(h))return NaN;if(h===-1)return-1;if(h===!0)return 1}var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0});const sI=Object.freeze(Object.defineProperty({__proto__:null,createAbs:cl,createAccessorNode:nf,createAcos:ph,createAcosh:mh,createAcot:gh,createAcoth:vh,createAcsc:yh,createAcsch:bh,createAdd:Yh,createAddScalar:fl,createAnd:fo,createAndTransform:bm,createArg:Il,createArrayNode:af,createAsec:xh,createAsech:wh,createAsin:Sh,createAsinh:Nh,createAssignmentNode:lf,createAtan:Ch,createAtan2:Dh,createAtanh:Ah,createAtomicMass:_p,createAvogadro:Op,createBellNumbers:Sd,createBigNumberClass:wu,createBigint:Zu,createBignumber:el,createBin:gc,createBitAnd:Ja,createBitAndTransform:Sm,createBitNot:Rl,createBitOr:Za,createBitOrTransform:Nm,createBitXor:Ll,createBlockNode:hf,createBohrMagneton:hp,createBohrRadius:vp,createBoltzmann:Bp,createBoolean:Ku,createCatalan:Nd,createCbrt:pl,createCeil:ml,createChain:jf,createChainClass:Vf,createClassicalElectronRadius:yp,createClone:Bu,createColumn:to,createColumnTransform:em,createCombinations:ld,createCombinationsWithRep:cd,createCompare:Ic,createCompareNatural:qc,createCompareText:Hc,createCompile:kf,createComplex:tl,createComplexClass:Su,createComposition:Cd,createConcat:eo,createConcatTransform:hm,createConditionalNode:df,createConductanceQuantum:fp,createConj:$l,createConstantNode:mf,createCorr:ud,createCos:Eh,createCosh:Mh,createCot:Th,createCoth:Fh,createCoulomb:up,createCoulombConstant:lp,createCount:Wl,createCreateUnit:dh,createCross:jl,createCsc:_h,createCsch:Oh,createCtranspose:ac,createCube:gl,createCumSum:xo,createCumSumTransform:gm,createDeepEqual:eh,createDenseMatrixClass:Ou,createDerivative:Od,createDet:Gf,createDeuteronMass:Cp,createDiag:Gl,createDiff:so,createDiffTransform:fm,createDistance:id,createDivide:rd,createDivideScalar:Nc,createDot:Qh,createDotDivide:Fc,createDotMultiply:Pl,createDotPow:Tc,createE:Wd,createEfimovFactor:Fp,createEigs:Jf,createElectricConstant:ap,createElectronMass:bp,createElementaryCharge:cp,createEqual:Vc,createEqualScalar:Xu,createEqualText:Wc,createErf:hc,createEvaluate:Pf,createExp:vl,createExpm:Zf,createExpm1:yl,createFactorial:dd,createFalse:Id,createFaraday:kp,createFermiCoupling:xp,createFft:uc,createFibonacciHeapClass:oh,createFilter:ro,createFilterTransform:tm,createFineStructure:wp,createFirstRadiation:Pp,createFix:bl,createFlatten:Xl,createFloor:Ga,createForEach:io,createForEachTransform:rm,createFormat:mc,createFraction:rl,createFractionClass:Nu,createFreqz:Pd,createFunctionAssignmentNode:vf,createFunctionNode:Of,createGamma:hd,createGasConstant:Rp,createGcd:wl,createGetMatrixDataType:Yl,createGravitationConstant:rp,createGravity:jp,createHartreeEnergy:Sp,createHasNumericValue:Hu,createHelp:Wf,createHelpClass:Uf,createHex:yc,createHypot:Jh,createI:Kd,createIdentity:Jl,createIfft:lc,createIm:ql,createImmutableDenseMatrixClass:sh,createIndex:ef,createIndexClass:ah,createIndexNode:bf,createIndexTransform:im,createInfinity:qd,createIntersect:nd,createInv:Xf,createInverseConductanceQuantum:dp,createInvmod:kl,createIsInteger:zu,createIsNaN:Wu,createIsNegative:$u,createIsNumeric:qu,createIsPositive:Uu,createIsPrime:wc,createIsZero:Vu,createKldivergence:pd,createKlitzing:gp,createKron:Zl,createLN10:Xd,createLN2:Gd,createLOG10E:Jd,createLOG2E:Yd,createLarger:Zc,createLargerEq:Kc,createLcm:Nl,createLeafCount:Dd,createLeftShift:Pc,createLgamma:fd,createLog:Ac,createLog10:Cl,createLog1p:Ec,createLog2:Dl,createLoschmidt:zp,createLsolve:_c,createLsolveAll:Bc,createLup:Lf,createLusolve:qf,createLyap:td,createMad:od,createMagneticConstant:sp,createMagneticFluxQuantum:pp,createMap:no,createMapSlices:la,createMapSlicesTransform:Kp,createMapTransform:nm,createMatrix:il,createMatrixClass:Du,createMatrixFromColumns:al,createMatrixFromFunction:nl,createMatrixFromRows:sl,createMax:po,createMaxTransform:sm,createMean:wo,createMeanTransform:am,createMedian:ad,createMin:mo,createMinTransform:om,createMod:Xa,createMode:dc,createMolarMass:Vp,createMolarMassC12:Wp,createMolarPlanckConstant:Lp,createMolarVolume:Ip,createMultinomial:md,createMultiply:El,createMultiplyScalar:Al,createNaN:Hd,createNeutronMass:Dp,createNode:tf,createNorm:Zh,createNot:Ul,createNthRoot:Ml,createNthRoots:Mc,createNuclearMagneton:mp,createNull:$d,createNullish:Qa,createNullishTransform:wm,createNumber:Ju,createNumeric:Sc,createObjectNode:wf,createOct:vc,createOnes:Ql,createOperatorNode:Nf,createOr:Ka,createOrTransform:xm,createParenthesisNode:Df,createParse:Bf,createParser:Rf,createParserClass:zf,createPartitionSelect:ih,createPermutations:gd,createPhi:jd,createPi:Ud,createPickRandom:yd,createPinv:Yf,createPlanckCharge:Jp,createPlanckConstant:ip,createPlanckLength:Gp,createPlanckMass:Xp,createPlanckTemperature:Zp,createPlanckTime:Yp,createPolynomialRoot:Hf,createPow:Cc,createPrint:co,createPrintTransform:ym,createProd:pc,createProtonMass:Np,createQr:If,createQuantileSeq:No,createQuantileSeqTransform:mm,createQuantumOfCirculation:Ap,createRandom:bd,createRandomInt:xd,createRange:ao,createRangeClass:Cu,createRangeNode:Ef,createRangeTransform:um,createRationalize:Bd,createRe:Hl,createReducedPlanckConstant:np,createRelationalNode:Tf,createReplacer:Rd,createReshape:Kl,createResize:ec,createResolve:Fd,createResultSet:fu,createReviver:zd,createRightArithShift:zc,createRightLogShift:Rc,createRotate:tc,createRotationMatrix:rc,createRound:Dc,createRow:oo,createRowTransform:lm,createRydberg:Ep,createSQRT1_2:Zd,createSQRT2:Qd,createSackurTetrode:$p,createSchur:ed,createSec:Bh,createSech:kh,createSecondRadiation:qp,createSetCartesian:Ih,createSetDifference:$h,createSetDistinct:qh,createSetIntersect:Hh,createSetIsSubset:Uh,createSetMultiplicity:Vh,createSetPowerset:Wh,createSetSize:jh,createSetSymDifference:Gh,createSetUnion:Xh,createSign:Tl,createSimplify:Ed,createSimplifyConstant:Md,createSimplifyCore:Td,createSin:Ph,createSinh:zh,createSize:ic,createSlu:$f,createSmaller:Gc,createSmallerEq:Yc,createSolveODE:cc,createSort:nh,createSpaClass:uh,createSparse:fh,createSparseMatrixClass:Yu,createSpeedOfLight:tp,createSplitUnit:ol,createSqrt:Fl,createSqrtm:Qf,createSquare:_l,createSqueeze:nc,createStd:Co,createStdTransform:dm,createStefanBoltzmann:Hp,createStirlingS2:wd,createString:Qu,createSubset:uo,createSubsetTransform:cm,createSubtract:Ol,createSubtractScalar:dl,createSum:bo,createSumTransform:pm,createSylvester:Kf,createSymbolNode:Ff,createSymbolicEqual:_d,createTan:Rh,createTanh:Lh,createTau:Vd,createThomsonCrossSection:Mp,createTo:bc,createToBest:xc,createTrace:Kh,createTranspose:sc,createTrue:Ld,createTypeOf:ju,createTyped:uu,createUnaryMinus:ul,createUnaryPlus:ll,createUnequal:rh,createUnitClass:ch,createUnitFunction:hh,createUppercaseE:Nv,createUppercasePi:Sv,createUsolve:Oc,createUsolveAll:kc,createVacuumImpedance:op,createVariance:So,createVarianceTransform:vm,createVersion:ep,createWeakMixingAngle:Tp,createWienDisplacement:Up,createXgcd:Bl,createXor:Vl,createZeros:oc,createZeta:fc,createZpk2tf:kd},Symbol.toStringTag,{value:"Module"}));var Ce=wu({config:pe}),Ct=Su({}),Av=Wd({BigNumber:Ce,config:pe}),PN=Id({}),zN=wp({BigNumber:Ce,config:pe}),kn=Nu({}),Ev=Kd({Complex:Ct}),RN=qd({BigNumber:Ce,config:pe}),LN=Xd({BigNumber:Ce,config:pe}),IN=Jd({BigNumber:Ce,config:pe}),Do=Du({}),$N=Hd({BigNumber:Ce,config:pe}),qN=$d({}),HN=jd({BigNumber:Ce,config:pe}),UN=Cu({}),Mv=fu({}),VN=Zd({BigNumber:Ce,config:pe}),WN=$p({BigNumber:Ce,config:pe}),Tv=Vd({BigNumber:Ce,config:pe}),jN=Ld({}),GN=ep({}),tt=Ou({Matrix:Do}),XN=Fp({BigNumber:Ce,config:pe}),YN=Gd({BigNumber:Ce,config:pe}),Cm=Ud({BigNumber:Ce,config:pe}),Fv=Rd({}),JN=Qd({BigNumber:Ce,config:pe}),j=uu({BigNumber:Ce,Complex:Ct,DenseMatrix:tt,Fraction:kn}),ZN=Tp({BigNumber:Ce,config:pe}),Cr=cl({typed:j}),QN=ph({Complex:Ct,config:pe,typed:j}),KN=gh({BigNumber:Ce,typed:j}),eC=yh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),Jt=fl({typed:j}),tC=Il({typed:j}),rC=wh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),iC=Nh({typed:j}),_v=Ch({typed:j}),nC=Ah({Complex:Ct,config:pe,typed:j}),sC=Zu({typed:j}),aC=Rl({typed:j}),oC=Ku({typed:j}),uC=Bu({typed:j}),Ao=ld({typed:j}),Eo=tl({Complex:Ct,typed:j}),Pn=$l({typed:j}),Dm=Eh({typed:j}),lC=Th({BigNumber:Ce,typed:j}),cC=_h({BigNumber:Ce,typed:j}),hC=gl({typed:j}),nt=Xu({config:pe,typed:j}),fC=hc({typed:j}),Ov=vl({typed:j}),dC=yl({Complex:Ct,typed:j}),pC=ro({typed:j}),zn=Xl({typed:j}),mC=io({typed:j}),ma=mc({typed:j}),Am=Yl({typed:j}),gC=yc({format:ma,typed:j}),Em=ql({typed:j}),Pr=zu({typed:j}),on=$u({config:pe,typed:j}),Rn=Uu({config:pe,typed:j}),ti=Vu({equalScalar:nt,typed:j}),vC=Yd({BigNumber:Ce,config:pe}),yC=fd({Complex:Ct,typed:j}),bC=Cl({Complex:Ct,config:pe,typed:j}),Mm=Dl({Complex:Ct,config:pe,typed:j}),Ln=no({typed:j}),Ht=Al({typed:j}),Mo=Ul({typed:j}),ji=Ju({typed:j}),xC=vc({format:ma,typed:j}),wC=yd({config:pe,typed:j}),SC=co({typed:j}),NC=bd({config:pe,typed:j}),Tm=Hl({typed:j}),CC=Bh({BigNumber:Ce,typed:j}),Bv=Tl({BigNumber:Ce,Fraction:kn,complex:Eo,typed:j}),To=Ph({typed:j}),Zt=Yu({Matrix:Do,equalScalar:nt,typed:j}),DC=ol({typed:j}),AC=_l({typed:j}),EC=Qu({typed:j}),ri=dl({typed:j}),MC=Rh({typed:j}),kv=xc({typed:j}),Fm=ju({typed:j}),TC=mh({Complex:Ct,config:pe,typed:j}),FC=bh({BigNumber:Ce,typed:j}),_C=xh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),zr=el({BigNumber:Ce,typed:j}),OC=cd({typed:j}),BC=Mh({typed:j}),kC=Oh({BigNumber:Ce,typed:j}),Gi=Wu({typed:j}),PC=wc({typed:j}),fs=la({isInteger:Pr,typed:j}),aI=fs,we=il({DenseMatrix:tt,Matrix:Do,SparseMatrix:Zt,typed:j}),zC=nl({isZero:ti,matrix:we,typed:j}),RC=Ql({BigNumber:Ce,config:pe,matrix:we,typed:j}),LC=xd({config:pe,log2:Mm,typed:j}),Pv=Kl({isInteger:Pr,matrix:we,typed:j}),IC=kh({BigNumber:Ce,typed:j}),$C=zh({typed:j}),qC=fh({SparseMatrix:Zt,typed:j}),vi=Fl({Complex:Ct,config:pe,typed:j}),HC=nc({typed:j}),UC=Lh({typed:j}),ga=sc({matrix:we,typed:j}),zv=Bl({BigNumber:Ce,config:pe,matrix:we,typed:j}),lr=oc({BigNumber:Ce,config:pe,matrix:we,typed:j}),VC=vh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),WC=Sh({Complex:Ct,config:pe,typed:j}),jC=gc({format:ma,typed:j}),dt=eo({isInteger:Pr,matrix:we,typed:j}),GC=Fh({BigNumber:Ce,typed:j}),_m=ac({conj:Pn,transpose:ga,typed:j}),Rv=Gl({DenseMatrix:tt,SparseMatrix:Zt,matrix:we,typed:j}),XC=Pl({concat:dt,equalScalar:nt,matrix:we,multiplyScalar:Ht,typed:j}),Rr=Vc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,equalScalar:nt,matrix:we,typed:j}),va=rl({Fraction:kn,typed:j}),un=Jl({BigNumber:Ce,DenseMatrix:tt,SparseMatrix:Zt,config:pe,matrix:we,typed:j}),In=qu({typed:j}),YC=Zl({matrix:we,multiplyScalar:Ht,typed:j}),Fo=Kc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,matrix:we,typed:j}),JC=Pc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ZC=dc({isNaN:Gi,isNumeric:In,typed:j}),QC=Ml({BigNumber:Ce,concat:dt,equalScalar:nt,matrix:we,typed:j}),ii=Sc({bignumber:zr,fraction:va,number:ji}),Lv=pc({config:pe,multiplyScalar:Ht,numeric:ii,typed:j}),KC=ec({config:pe,matrix:we}),eD=zc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ds=Dc({BigNumber:Ce,DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,typed:j,zeros:lr}),Qt=ic({matrix:we,config:pe,typed:j}),Dr=Gc({DenseMatrix:tt,SparseMatrix:Zt,bignumber:zr,concat:dt,config:pe,matrix:we,typed:j}),tD=bc({concat:dt,matrix:we,typed:j}),Oi=ul({typed:j}),rD=rh({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,equalScalar:nt,matrix:we,typed:j}),iD=Vl({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,matrix:we,typed:j}),ht=Yh({DenseMatrix:tt,SparseMatrix:Zt,addScalar:Jt,concat:dt,equalScalar:nt,matrix:we,typed:j}),nD=Dh({BigNumber:Ce,DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),sD=Ja({concat:dt,equalScalar:nt,matrix:we,typed:j}),aD=Za({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),oD=Ll({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,matrix:we,typed:j}),Iv=pl({BigNumber:Ce,Complex:Ct,Fraction:kn,config:pe,isNegative:on,matrix:we,typed:j,unaryMinus:Oi}),$n=Ic({BigNumber:Ce,DenseMatrix:tt,Fraction:kn,concat:dt,config:pe,equalScalar:nt,matrix:we,typed:j}),$v=Hc({concat:dt,matrix:we,typed:j}),uD=Wl({prod:Lv,size:Qt,typed:j}),ya=eh({equal:Rr,typed:j}),Rt=Nc({numeric:ii,typed:j}),ba=Fc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,divideScalar:Rt,equalScalar:nt,matrix:we,typed:j}),lD=Wc({compareText:$v,isZero:ti,typed:j}),qv=Ga({DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),cD=wl({BigNumber:Ce,DenseMatrix:tt,concat:dt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),hD=Hu({isNumeric:In,typed:j}),fD=Jh({abs:Cr,addScalar:Jt,divideScalar:Rt,isPositive:Rn,multiplyScalar:Ht,smaller:Dr,sqrt:vi,typed:j}),Hv=sh({DenseMatrix:tt,smaller:Dr}),mr=ah({ImmutableDenseMatrix:Hv,getMatrixDataType:Am}),Ar=Zc({DenseMatrix:tt,SparseMatrix:Zt,bignumber:zr,concat:dt,config:pe,matrix:we,typed:j}),Om=Ac({Complex:Ct,config:pe,divideScalar:Rt,typeOf:Fm,typed:j}),Uv=_c({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),Bm=al({flatten:zn,matrix:we,size:Qt,typed:j}),km=po({config:pe,isNaN:Gi,larger:Ar,numeric:ii,typed:j}),dD=mo({config:pe,isNaN:Gi,numeric:ii,smaller:Dr,typed:j}),Vv=Xa({DenseMatrix:tt,concat:dt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),pD=Mc({Complex:Ct,config:pe,divideScalar:Rt,typed:j}),mD=Qa({deepEqual:ya,flatten:zn,matrix:we,size:Qt,typed:j}),gD=Ka({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),_o=ih({compare:$n,isNaN:Gi,isNumeric:In,typed:j}),Pm=If({addScalar:Jt,complex:Eo,conj:Pn,divideScalar:Rt,equal:Rr,identity:un,isZero:ti,matrix:we,multiplyScalar:Ht,sign:Bv,sqrt:vi,subtractScalar:ri,typed:j,unaryMinus:Oi,zeros:lr}),vD=Rc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ps=Yc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,matrix:we,typed:j}),Gr=uo({add:ht,matrix:we,typed:j,zeros:lr}),Wt=Ol({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,subtractScalar:ri,typed:j,unaryMinus:Oi}),yD=Kh({add:ht,matrix:we,typed:j}),zm=Oc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),bD=Nd({addScalar:Jt,combinations:Ao,divideScalar:Rt,isInteger:Pr,isNegative:on,multiplyScalar:Ht,typed:j}),Bi=qc({compare:$n,typed:j}),xD=Cd({addScalar:Jt,combinations:Ao,isInteger:Pr,isNegative:on,isPositive:Rn,larger:Ar,typed:j}),wD=so({matrix:we,number:ji,subtract:Wt,typed:j}),SD=id({abs:Cr,addScalar:Jt,deepEqual:ya,divideScalar:Rt,multiplyScalar:Ht,sqrt:vi,subtractScalar:ri,typed:j}),Oo=Qh({addScalar:Jt,conj:Pn,multiplyScalar:Ht,size:Qt,typed:j}),Wv=oh({larger:Ar,smaller:Dr}),jv=ef({Index:mr,typed:j}),ND=kl({BigNumber:Ce,add:ht,config:pe,equal:Rr,isInteger:Pr,mod:Vv,smaller:Dr,typed:j,xgcd:zv}),CD=Nl({concat:dt,equalScalar:nt,matrix:we,typed:j}),DD=Ec({Complex:Ct,config:pe,divideScalar:Rt,log:Om,typed:j}),AD=Bc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),ED=sl({flatten:zn,matrix:we,size:Qt,typed:j}),xt=El({addScalar:Jt,dot:Oo,equalScalar:nt,matrix:we,multiplyScalar:Ht,typed:j}),ms=ao({bignumber:zr,matrix:we,add:ht,config:pe,equal:Rr,isPositive:Rn,isZero:ti,larger:Ar,largerEq:Fo,smaller:Dr,smallerEq:ps,typed:j}),MD=oo({Index:mr,matrix:we,range:ms,typed:j}),TD=Ih({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),FD=qh({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),_D=Uh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),OD=Wh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),Gv=$f({SparseMatrix:Zt,abs:Cr,add:ht,divideScalar:Rt,larger:Ar,largerEq:Fo,multiply:xt,subtract:Wt,transpose:ga,typed:j}),BD=nh({compare:$n,compareNatural:Bi,matrix:we,typed:j}),Rm=ll({config:pe,numeric:ii,typed:j}),Xv=kc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),kD=kd({Complex:Ct,add:ht,multiply:xt,number:ji,typed:j}),PD=fo({concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),Lm=ml({DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),Yv=to({Index:mr,matrix:we,range:ms,typed:j}),zD=jl({matrix:we,multiply:xt,subtract:Wt,typed:j}),Jv=Gf({divideScalar:Rt,isZero:ti,matrix:we,multiply:xt,subtractScalar:ri,typed:j,unaryMinus:Oi}),Zv=bl({Complex:Ct,DenseMatrix:tt,ceil:Lm,equalScalar:nt,floor:qv,matrix:we,typed:j,zeros:lr}),qn=Xf({abs:Cr,addScalar:Jt,det:Jv,divideScalar:Rt,identity:un,matrix:we,multiply:xt,typed:j,unaryMinus:Oi}),RD=Yf({Complex:Ct,add:ht,ctranspose:_m,deepEqual:ya,divideScalar:Rt,dot:Oo,dotDivide:ba,equal:Rr,inv:qn,matrix:we,multiply:xt,typed:j}),yi=Cc({Complex:Ct,config:pe,fraction:va,identity:un,inv:qn,matrix:we,multiply:xt,number:ji,typed:j}),Qv=$h({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),LD=Vh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),Kv=Gh({Index:mr,concat:dt,setDifference:Qv,size:Qt,subset:Gr,typed:j}),e0=uh({FibonacciHeap:Wv,addScalar:Jt,equalScalar:nt}),ID=Qf({abs:Cr,add:ht,identity:un,inv:qn,map:Ln,max:km,multiply:xt,size:Qt,sqrt:vi,subtract:Wt,typed:j}),Im=bo({add:ht,config:pe,numeric:ii,typed:j}),qe=ch({BigNumber:Ce,Complex:Ct,Fraction:kn,abs:Cr,addScalar:Jt,config:pe,divideScalar:Rt,equal:Rr,fix:Zv,format:ma,isNumeric:In,multiplyScalar:Ht,number:ji,pow:yi,round:ds,subtractScalar:ri,toBest:kv}),$D=op({BigNumber:Ce,Unit:qe,config:pe}),qD=Up({BigNumber:Ce,Unit:qe,config:pe}),HD=_p({BigNumber:Ce,Unit:qe,config:pe}),UD=hp({BigNumber:Ce,Unit:qe,config:pe}),VD=Bp({BigNumber:Ce,Unit:qe,config:pe}),WD=fp({BigNumber:Ce,Unit:qe,config:pe}),jD=up({BigNumber:Ce,Unit:qe,config:pe}),GD=dh({Unit:qe,typed:j}),XD=Cp({BigNumber:Ce,Unit:qe,config:pe}),YD=Tc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,equalScalar:nt,matrix:we,pow:yi,typed:j}),JD=ap({BigNumber:Ce,Unit:qe,config:pe}),ZD=cp({BigNumber:Ce,Unit:qe,config:pe}),QD=Zf({abs:Cr,add:ht,identity:un,inv:qn,multiply:xt,typed:j}),KD=kp({BigNumber:Ce,Unit:qe,config:pe}),t0=uc({addScalar:Jt,ceil:Lm,conj:Pn,divideScalar:Rt,dotDivide:ba,exp:Ov,i:Ev,log2:Mm,matrix:we,multiplyScalar:Ht,pow:yi,tau:Tv,typed:j}),$m=hd({BigNumber:Ce,Complex:Ct,config:pe,multiplyScalar:Ht,pow:yi,typed:j}),eA=rp({BigNumber:Ce,Unit:qe,config:pe}),tA=Sp({BigNumber:Ce,Unit:qe,config:pe}),rA=lc({conj:Pn,dotDivide:ba,fft:t0,typed:j}),iA=dp({BigNumber:Ce,Unit:qe,config:pe}),nA=gp({BigNumber:Ce,Unit:qe,config:pe}),sA=zp({BigNumber:Ce,Unit:qe,config:pe}),aA=sp({BigNumber:Ce,Unit:qe,config:pe}),oA=Vp({BigNumber:Ce,Unit:qe,config:pe}),uA=Lp({BigNumber:Ce,Unit:qe,config:pe}),lA=Dp({BigNumber:Ce,Unit:qe,config:pe}),cA=mp({BigNumber:Ce,Unit:qe,config:pe}),hA=Jp({BigNumber:Ce,Unit:qe,config:pe}),fA=Gp({BigNumber:Ce,Unit:qe,config:pe}),dA=Zp({BigNumber:Ce,Unit:qe,config:pe}),pA=Np({BigNumber:Ce,Unit:qe,config:pe}),mA=Ap({BigNumber:Ce,Unit:qe,config:pe}),gA=np({BigNumber:Ce,Unit:qe,config:pe}),vA=Ep({BigNumber:Ce,Unit:qe,config:pe}),yA=qp({BigNumber:Ce,Unit:qe,config:pe}),bA=jh({compareNatural:Bi,typed:j}),xA=tp({BigNumber:Ce,Unit:qe,config:pe}),wA=Hp({BigNumber:Ce,Unit:qe,config:pe}),SA=Mp({BigNumber:Ce,Unit:qe,config:pe}),NA=Op({BigNumber:Ce,Unit:qe,config:pe}),CA=vp({BigNumber:Ce,Unit:qe,config:pe}),DA=lp({BigNumber:Ce,Unit:qe,config:pe}),cr=rd({divideScalar:Rt,equalScalar:nt,inv:qn,matrix:we,multiply:xt,typed:j}),AA=bp({BigNumber:Ce,Unit:qe,config:pe}),xa=dd({gamma:$m,typed:j}),EA=Pp({BigNumber:Ce,Unit:qe,config:pe}),MA=jp({BigNumber:Ce,Unit:qe,config:pe}),TA=nd({abs:Cr,add:ht,addScalar:Jt,config:pe,divideScalar:Rt,equalScalar:nt,flatten:zn,isNumeric:In,isZero:ti,matrix:we,multiply:xt,multiplyScalar:Ht,smaller:Dr,subtract:Wt,typed:j}),r0=Lf({DenseMatrix:tt,Spa:e0,SparseMatrix:Zt,abs:Cr,addScalar:Jt,divideScalar:Rt,equalScalar:nt,larger:Ar,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j,unaryMinus:Oi}),FA=pp({BigNumber:Ce,Unit:qe,config:pe}),_A=Wp({BigNumber:Ce,Unit:qe,config:pe}),OA=md({add:ht,divide:cr,factorial:xa,isInteger:Pr,isPositive:Rn,multiply:xt,typed:j}),BA=gd({factorial:xa,typed:j}),kA=Xp({BigNumber:Ce,Unit:qe,config:pe}),PA=Hf({add:ht,cbrt:Iv,divide:cr,equalScalar:nt,im:Em,isZero:ti,multiply:xt,re:Tm,sqrt:vi,subtract:Wt,typeOf:Fm,typed:j,unaryMinus:Oi}),i0=Hh({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),zA=cc({abs:Cr,add:ht,bignumber:zr,divide:cr,isNegative:on,isPositive:Rn,larger:Ar,map:Ln,matrix:we,max:km,multiply:xt,smaller:Dr,subtract:Wt,typed:j,unaryMinus:Oi}),n0=wd({bignumber:zr,addScalar:Jt,combinations:Ao,divideScalar:Rt,factorial:xa,isInteger:Pr,isNegative:on,larger:Ar,multiplyScalar:Ht,number:ji,pow:yi,subtractScalar:ri,typed:j}),RA=hh({Unit:qe,typed:j}),LA=Sd({addScalar:Jt,isInteger:Pr,isNegative:on,stirlingS2:n0,typed:j}),IA=xo({add:ht,typed:j,unaryPlus:Rm}),s0=Jf({abs:Cr,add:ht,addScalar:Jt,atan:_v,bignumber:zr,column:Yv,complex:Eo,config:pe,cos:Dm,diag:Rv,divideScalar:Rt,dot:Oo,equal:Rr,flatten:zn,im:Em,inv:qn,larger:Ar,matrix:we,matrixFromColumns:Bm,multiply:xt,multiplyScalar:Ht,number:ji,qr:Pm,re:Tm,reshape:Pv,sin:To,size:Qt,smaller:Dr,sqrt:vi,subtract:Wt,typed:j,usolve:zm,usolveAll:Xv}),$A=xp({BigNumber:Ce,Unit:qe,config:pe}),qA=Rp({BigNumber:Ce,Unit:qe,config:pe}),HA=pd({divide:cr,dotDivide:ba,isNumeric:In,log:Om,map:Ln,matrix:we,multiply:xt,sum:Im,typed:j}),a0=qf({DenseMatrix:tt,lsolve:Uv,lup:r0,matrix:we,slu:Gv,typed:j,usolve:zm}),o0=wo({add:ht,divide:cr,typed:j}),UA=Ip({BigNumber:Ce,Unit:qe,config:pe}),VA=ip({BigNumber:Ce,Unit:qe,config:pe}),WA=No({bignumber:zr,add:ht,compare:$n,divide:cr,isInteger:Pr,larger:Ar,mapSlices:fs,multiply:xt,partitionSelect:_o,smaller:Dr,smallerEq:ps,subtract:Wt,typed:j}),jA=Xh({Index:mr,concat:dt,setIntersect:i0,setSymDifference:Kv,size:Qt,subset:Gr,typed:j}),qm=So({add:ht,divide:cr,isNaN:Gi,mapSlices:fs,multiply:xt,subtract:Wt,typed:j}),GA=yp({BigNumber:Ce,Unit:qe,config:pe}),u0=ad({add:ht,compare:$n,divide:cr,partitionSelect:_o,typed:j}),XA=ud({add:ht,divide:cr,matrix:we,mean:o0,multiply:xt,pow:yi,sqrt:vi,subtract:Wt,sum:Im,typed:j}),YA=Pd({Complex:Ct,add:ht,divide:cr,matrix:we,multiply:xt,typed:j}),JA=od({abs:Cr,map:Ln,median:u0,subtract:Wt,typed:j}),ZA=Co({map:Ln,sqrt:vi,typed:j,variance:qm}),QA=fc({BigNumber:Ce,Complex:Ct,add:ht,config:pe,divide:cr,equal:Rr,factorial:xa,gamma:$m,isNegative:on,multiply:xt,pi:Cm,pow:yi,sin:To,smallerEq:ps,subtract:Wt,typed:j}),Hm=Zh({abs:Cr,add:ht,conj:Pn,ctranspose:_m,eigs:s0,equalScalar:nt,larger:Ar,matrix:we,multiply:xt,pow:yi,smaller:Dr,sqrt:vi,typed:j}),l0=rc({BigNumber:Ce,DenseMatrix:tt,SparseMatrix:Zt,addScalar:Jt,config:pe,cos:Dm,matrix:we,multiplyScalar:Ht,norm:Hm,sin:To,typed:j,unaryMinus:Oi}),KA=Yp({BigNumber:Ce,Unit:qe,config:pe}),c0=ed({identity:un,matrix:we,multiply:xt,norm:Hm,qr:Pm,subtract:Wt,typed:j}),e2=tc({multiply:xt,rotationMatrix:l0,typed:j}),h0=Kf({abs:Cr,add:ht,concat:dt,identity:un,index:jv,lusolve:a0,matrix:we,matrixFromColumns:Bm,multiply:xt,range:ms,schur:c0,subset:Gr,subtract:Wt,transpose:ga,typed:j}),t2=td({matrix:we,multiply:xt,sylvester:h0,transpose:ga,typed:j}),wa={},Bo={},r2={},gr=tf({mathWithTransform:Bo}),gs=wf({Node:gr}),Xi=Nf({Node:gr}),Hn=Df({Node:gr}),f0=Tf({Node:gr}),vs=af({Node:gr}),d0=hf({Node:gr,ResultSet:Mv}),p0=df({Node:gr}),ln=mf({Node:gr}),m0=Ef({Node:gr}),i2=zd({classes:r2}),Um=Vf({math:wa,typed:j}),g0=vf({Node:gr,typed:j}),n2=jf({Chain:Um,typed:j}),ys=nf({Node:gr,subset:Gr}),v0=lf({matrix:we,Node:gr,subset:Gr}),bs=bf({Node:gr,size:Qt}),cn=Ff({Unit:qe,Node:gr,math:wa}),hn=Of({Node:gr,SymbolNode:cn,math:wa}),bi=Bf({AccessorNode:ys,ArrayNode:vs,AssignmentNode:v0,BlockNode:d0,ConditionalNode:p0,ConstantNode:ln,FunctionAssignmentNode:g0,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,RangeNode:m0,RelationalNode:f0,SymbolNode:cn,config:pe,numeric:ii,typed:j}),y0=Fd({ConstantNode:ln,FunctionNode:hn,OperatorNode:Xi,ParenthesisNode:Hn,parse:bi,typed:j}),Vm=Md({bignumber:zr,fraction:va,AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,SymbolNode:cn,config:pe,mathWithTransform:Bo,matrix:we,typed:j}),s2=kf({parse:bi,typed:j}),Wm=Td({AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,add:ht,divide:cr,equal:Rr,isZero:ti,multiply:xt,parse:bi,pow:yi,subtract:Wt,typed:j}),jm=Pf({parse:bi,typed:j}),b0=Uf({evaluate:jm}),x0=zf({evaluate:jm,parse:bi}),ko=Ed({AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,equal:Rr,parse:bi,replacer:Fv,resolve:y0,simplifyConstant:Vm,simplifyCore:Wm,typed:j}),a2=_d({OperatorNode:Xi,parse:bi,simplify:ko,typed:j}),o2=Dd({parse:bi,typed:j}),u2=Rf({Parser:x0,typed:j}),l2=Bd({bignumber:zr,fraction:va,AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,add:ht,config:pe,divide:cr,equal:Rr,isZero:ti,mathWithTransform:Bo,matrix:we,multiply:xt,parse:bi,pow:yi,simplify:ko,simplifyConstant:Vm,simplifyCore:Wm,subtract:Wt,typed:j}),c2=Od({ConstantNode:ln,FunctionNode:hn,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,config:pe,equal:Rr,isZero:ti,numeric:ii,parse:bi,simplify:ko,typed:j}),h2=Wf({Help:b0,mathWithTransform:Bo,typed:j});wt(wa,{e:Av,false:PN,fineStructure:zN,i:Ev,Infinity:RN,LN10:LN,LOG10E:IN,NaN:$N,null:qN,phi:HN,SQRT1_2:VN,sackurTetrode:WN,tau:Tv,true:jN,E:Av,version:GN,efimovFactor:XN,LN2:YN,pi:Cm,replacer:Fv,reviver:i2,SQRT2:JN,typed:j,PI:Cm,weakMixingAngle:ZN,abs:Cr,acos:QN,acot:KN,acsc:eC,addScalar:Jt,arg:tC,asech:rC,asinh:iC,atan:_v,atanh:nC,bigint:sC,bitNot:aC,boolean:oC,clone:uC,combinations:Ao,complex:Eo,conj:Pn,cos:Dm,cot:lC,csc:cC,cube:hC,equalScalar:nt,erf:fC,exp:Ov,expm1:dC,filter:pC,flatten:zn,forEach:mC,format:ma,getMatrixDataType:Am,hex:gC,im:Em,isInteger:Pr,isNegative:on,isPositive:Rn,isZero:ti,LOG2E:vC,lgamma:yC,log10:bC,log2:Mm,map:Ln,multiplyScalar:Ht,not:Mo,number:ji,oct:xC,pickRandom:wC,print:SC,random:NC,re:Tm,sec:CC,sign:Bv,sin:To,splitUnit:DC,square:AC,string:EC,subtractScalar:ri,tan:MC,toBest:kv,typeOf:Fm,acosh:TC,acsch:FC,asec:_C,bignumber:zr,chain:n2,combinationsWithRep:OC,cosh:BC,csch:kC,isNaN:Gi,isPrime:PC,mapSlices:fs,matrix:we,matrixFromFunction:zC,ones:RC,randomInt:LC,reshape:Pv,sech:IC,sinh:$C,sparse:qC,sqrt:vi,squeeze:HC,tanh:UC,transpose:ga,xgcd:zv,zeros:lr,acoth:VC,asin:WC,bin:jC,concat:dt,coth:GC,ctranspose:_m,diag:Rv,dotMultiply:XC,equal:Rr,fraction:va,identity:un,isNumeric:In,kron:YC,largerEq:Fo,leftShift:JC,mode:ZC,nthRoot:QC,numeric:ii,prod:Lv,resize:KC,rightArithShift:eD,round:ds,size:Qt,smaller:Dr,to:tD,unaryMinus:Oi,unequal:rD,xor:iD,add:ht,atan2:nD,bitAnd:sD,bitOr:aD,bitXor:oD,cbrt:Iv,compare:$n,compareText:$v,count:uD,deepEqual:ya,divideScalar:Rt,dotDivide:ba,equalText:lD,floor:qv,gcd:cD,hasNumericValue:hD,hypot:fD,larger:Ar,log:Om,lsolve:Uv,matrixFromColumns:Bm,max:km,min:dD,mod:Vv,nthRoots:pD,nullish:mD,or:gD,partitionSelect:_o,qr:Pm,rightLogShift:vD,smallerEq:ps,subset:Gr,subtract:Wt,trace:yD,usolve:zm,catalan:bD,compareNatural:Bi,composition:xD,diff:wD,distance:SD,dot:Oo,index:jv,invmod:ND,lcm:CD,log1p:DD,lsolveAll:AD,matrixFromRows:ED,multiply:xt,range:ms,row:MD,setCartesian:TD,setDistinct:FD,setIsSubset:_D,setPowerset:OD,slu:Gv,sort:BD,unaryPlus:Rm,usolveAll:Xv,zpk2tf:kD,and:PD,ceil:Lm,column:Yv,cross:zD,det:Jv,fix:Zv,inv:qn,pinv:RD,pow:yi,setDifference:Qv,setMultiplicity:LD,setSymDifference:Kv,sqrtm:ID,sum:Im,vacuumImpedance:$D,wienDisplacement:qD,atomicMass:HD,bohrMagneton:UD,boltzmann:VD,conductanceQuantum:WD,coulomb:jD,createUnit:GD,deuteronMass:XD,dotPow:YD,electricConstant:JD,elementaryCharge:ZD,expm:QD,faraday:KD,fft:t0,gamma:$m,gravitationConstant:eA,hartreeEnergy:tA,ifft:rA,inverseConductanceQuantum:iA,klitzing:nA,loschmidt:sA,magneticConstant:aA,molarMass:oA,molarPlanckConstant:uA,neutronMass:lA,nuclearMagneton:cA,planckCharge:hA,planckLength:fA,planckTemperature:dA,protonMass:pA,quantumOfCirculation:mA,reducedPlanckConstant:gA,rydberg:vA,secondRadiation:yA,setSize:bA,speedOfLight:xA,stefanBoltzmann:wA,thomsonCrossSection:SA,avogadro:NA,bohrRadius:CA,coulombConstant:DA,divide:cr,electronMass:AA,factorial:xa,firstRadiation:EA,gravity:MA,intersect:TA,lup:r0,magneticFluxQuantum:FA,molarMassC12:_A,multinomial:OA,parse:bi,permutations:BA,planckMass:kA,polynomialRoot:PA,resolve:y0,setIntersect:i0,simplifyConstant:Vm,solveODE:zA,stirlingS2:n0,unit:RA,bellNumbers:LA,compile:s2,cumsum:IA,eigs:s0,fermiCoupling:$A,gasConstant:qA,kldivergence:HA,lusolve:a0,mean:o0,molarVolume:UA,planckConstant:VA,quantileSeq:WA,setUnion:jA,simplifyCore:Wm,variance:qm,classicalElectronRadius:GA,evaluate:jm,median:u0,simplify:ko,symbolicEqual:a2,corr:XA,freqz:YA,leafCount:o2,mad:JA,parser:u2,rationalize:l2,std:ZA,zeta:QA,derivative:c2,norm:Hm,rotationMatrix:l0,help:h2,planckTime:KA,schur:c0,rotate:e2,sylvester:h0,lyap:t2,config:pe}),wt(Bo,wa,{mapSlices:Kp({isInteger:Pr,typed:j}),filter:tm({typed:j}),forEach:rm({typed:j}),map:nm({typed:j}),or:xm({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),and:bm({add:ht,concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),concat:hm({isInteger:Pr,matrix:we,typed:j}),index:im({Index:mr,getMatrixDataType:Am}),print:ym({add:ht,matrix:we,typed:j,zeros:lr}),sum:pm({add:ht,config:pe,numeric:ii,typed:j}),bitAnd:Sm({add:ht,concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),min:om({config:pe,isNaN:Gi,numeric:ii,smaller:Dr,typed:j}),nullish:wm({deepEqual:ya,flatten:zn,matrix:we,size:Qt,typed:j}),subset:cm({add:ht,matrix:we,typed:j,zeros:lr}),bitOr:Nm({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),cumsum:gm({add:ht,typed:j,unaryPlus:Rm}),diff:fm({bignumber:zr,matrix:we,number:ji,subtract:Wt,typed:j}),max:sm({config:pe,isNaN:Gi,larger:Ar,numeric:ii,typed:j}),range:um({bignumber:zr,matrix:we,add:ht,config:pe,equal:Rr,isPositive:Rn,isZero:ti,larger:Ar,largerEq:Fo,smaller:Dr,smallerEq:ps,typed:j}),row:lm({Index:mr,matrix:we,range:ms,typed:j}),column:em({Index:mr,matrix:we,range:ms,typed:j}),mean:am({add:ht,divide:cr,typed:j}),quantileSeq:mm({add:ht,bignumber:zr,compare:$n,divide:cr,isInteger:Pr,larger:Ar,mapSlices:fs,multiply:xt,partitionSelect:_o,smaller:Dr,smallerEq:ps,subtract:Wt,typed:j}),variance:vm({add:ht,divide:cr,isNaN:Gi,mapSlices:fs,multiply:xt,subtract:Wt,typed:j}),std:dm({map:Ln,sqrt:vi,typed:j,variance:qm})}),wt(r2,{BigNumber:Ce,Complex:Ct,Fraction:kn,Matrix:Do,Node:gr,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,Range:UN,RelationalNode:f0,ResultSet:Mv,ArrayNode:vs,BlockNode:d0,ConditionalNode:p0,ConstantNode:ln,DenseMatrix:tt,RangeNode:m0,Chain:Um,FunctionAssignmentNode:g0,SparseMatrix:Zt,ImmutableDenseMatrix:Hv,Index:mr,AccessorNode:ys,AssignmentNode:v0,FibonacciHeap:Wv,IndexNode:bs,Spa:e0,Unit:qe,SymbolNode:cn,FunctionNode:hn,Help:b0,Parser:x0}),Um.createProxy(wa);var De={createBigNumberClass:wu},Et={createComplexClass:Su},Gm={createMatrixClass:Du},it={MatrixDependencies:Gm,createDenseMatrixClass:Ou},xs={createFractionClass:Nu},G={BigNumberDependencies:De,ComplexDependencies:Et,DenseMatrixDependencies:it,FractionDependencies:xs,createTyped:uu},Lr={typedDependencies:G,createAbs:cl},Er={createNode:tf},ot={typedDependencies:G,createEqualScalar:Xu},tr={MatrixDependencies:Gm,equalScalarDependencies:ot,typedDependencies:G,createSparseMatrixClass:Yu},rr={typedDependencies:G,createAddScalar:fl},Xr={typedDependencies:G,createIsInteger:zu},Ne={DenseMatrixDependencies:it,MatrixDependencies:Gm,SparseMatrixDependencies:tr,typedDependencies:G,createMatrix:il},mt={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createConcat:eo},ft={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,addScalarDependencies:rr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createAdd:Yh},vr={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createZeros:oc},ni={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createSubset:uo},Sa={NodeDependencies:Er,subsetDependencies:ni,createAccessorNode:nf},oI={ComplexDependencies:Et,typedDependencies:G,createAcos:ph},uI={ComplexDependencies:Et,typedDependencies:G,createAcosh:mh},lI={BigNumberDependencies:De,typedDependencies:G,createAcot:gh},cI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAcoth:vh},hI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAcsc:yh},fI={BigNumberDependencies:De,typedDependencies:G,createAcsch:bh},Xm={typedDependencies:G,createNot:Ul},dI={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createAnd:fo},pI={addDependencies:ft,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createAndTransform:bm},mI={typedDependencies:G,createArg:Il},Na={NodeDependencies:Er,createArrayNode:af},gI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAsec:xh},vI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAsech:wh},yI={ComplexDependencies:Et,typedDependencies:G,createAsin:Sh},bI={typedDependencies:G,createAsinh:Nh},f2={matrixDependencies:Ne,NodeDependencies:Er,subsetDependencies:ni,createAssignmentNode:lf},d2={typedDependencies:G,createAtan:Ch},xI={BigNumberDependencies:De,DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createAtan2:Dh},wI={ComplexDependencies:Et,typedDependencies:G,createAtanh:Ah},Yr={BigNumberDependencies:De,typedDependencies:G,createBignumber:el},Po={FractionDependencies:xs,typedDependencies:G,createFraction:rl},fn={typedDependencies:G,createNumber:Ju},xi={bignumberDependencies:Yr,fractionDependencies:Po,numberDependencies:fn,createNumeric:Sc},$t={numericDependencies:xi,typedDependencies:G,createDivideScalar:Nc},Jr={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createEqual:Vc},Ca={BigNumberDependencies:De,DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRound:Dc},w0={DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createCeil:ml},p2={DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createFloor:Ga},m2={ComplexDependencies:Et,DenseMatrixDependencies:it,ceilDependencies:w0,equalScalarDependencies:ot,floorDependencies:p2,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createFix:bl},zo={typedDependencies:G,createFormat:mc},ws={typedDependencies:G,createIsNumeric:qu},jt={typedDependencies:G,createMultiplyScalar:Al},Un={BigNumberDependencies:De,DenseMatrixDependencies:it,SparseMatrixDependencies:tr,matrixDependencies:Ne,typedDependencies:G,createIdentity:Jl},wi={equalScalarDependencies:ot,typedDependencies:G,createIsZero:Vu},Ss={typedDependencies:G,createConj:$l},ir={matrixDependencies:Ne,typedDependencies:G,createSize:ic},Ym={addScalarDependencies:rr,conjDependencies:Ss,multiplyScalarDependencies:jt,sizeDependencies:ir,typedDependencies:G,createDot:Qh},Nt={addScalarDependencies:rr,dotDependencies:Ym,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createMultiply:El},Si={typedDependencies:G,createSubtractScalar:dl},Yi={typedDependencies:G,createUnaryMinus:ul},g2={divideScalarDependencies:$t,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createDet:Gf},Ns={absDependencies:Lr,addScalarDependencies:rr,detDependencies:g2,divideScalarDependencies:$t,identityDependencies:Un,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,unaryMinusDependencies:Yi,createInv:Xf},ki={ComplexDependencies:Et,fractionDependencies:Po,identityDependencies:Un,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,numberDependencies:fn,typedDependencies:G,createPow:Cc},v2={typedDependencies:G,createToBest:xc},Ve={BigNumberDependencies:De,ComplexDependencies:Et,FractionDependencies:xs,absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,equalDependencies:Jr,fixDependencies:m2,formatDependencies:zo,isNumericDependencies:ws,multiplyScalarDependencies:jt,numberDependencies:fn,powDependencies:ki,roundDependencies:Ca,subtractScalarDependencies:Si,toBestDependencies:v2,createUnitClass:ch},SI={BigNumberDependencies:De,UnitDependencies:Ve,createAtomicMass:_p},NI={BigNumberDependencies:De,UnitDependencies:Ve,createAvogadro:Op},Vn={typedDependencies:G,createIsNegative:$u},Jm={typedDependencies:G,createCombinations:ld},S0={BigNumberDependencies:De,ComplexDependencies:Et,multiplyScalarDependencies:jt,powDependencies:ki,typedDependencies:G,createGamma:hd},Ro={gammaDependencies:S0,typedDependencies:G,createFactorial:dd},Ir={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,bignumberDependencies:Yr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createLarger:Zc},y2={bignumberDependencies:Yr,addScalarDependencies:rr,combinationsDependencies:Jm,divideScalarDependencies:$t,factorialDependencies:Ro,isIntegerDependencies:Xr,isNegativeDependencies:Vn,largerDependencies:Ir,multiplyScalarDependencies:jt,numberDependencies:fn,powDependencies:ki,subtractScalarDependencies:Si,typedDependencies:G,createStirlingS2:wd},CI={addScalarDependencies:rr,isIntegerDependencies:Xr,isNegativeDependencies:Vn,stirlingS2Dependencies:y2,typedDependencies:G,createBellNumbers:Sd},DI={typedDependencies:G,createBigint:Zu},AI={formatDependencies:zo,typedDependencies:G,createBin:gc},EI={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitAnd:Ja},MI={addDependencies:ft,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createBitAndTransform:Sm},TI={typedDependencies:G,createBitNot:Rl},FI={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitOr:Za},_I={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitOrTransform:Nm},OI={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createBitXor:Ll},b2={createResultSet:fu},x2={NodeDependencies:Er,ResultSetDependencies:b2,createBlockNode:hf},BI={BigNumberDependencies:De,UnitDependencies:Ve,createBohrMagneton:hp},kI={BigNumberDependencies:De,UnitDependencies:Ve,createBohrRadius:vp},PI={BigNumberDependencies:De,UnitDependencies:Ve,createBoltzmann:Bp},zI={typedDependencies:G,createBoolean:Ku},RI={addScalarDependencies:rr,combinationsDependencies:Jm,divideScalarDependencies:$t,isIntegerDependencies:Xr,isNegativeDependencies:Vn,multiplyScalarDependencies:jt,typedDependencies:G,createCatalan:Nd},w2={BigNumberDependencies:De,ComplexDependencies:Et,FractionDependencies:xs,isNegativeDependencies:Vn,matrixDependencies:Ne,typedDependencies:G,unaryMinusDependencies:Yi,createCbrt:pl},S2={typedDependencies:G,createChainClass:Vf},LI={ChainDependencies:S2,typedDependencies:G,createChain:jf},II={BigNumberDependencies:De,UnitDependencies:Ve,createClassicalElectronRadius:yp},$I={typedDependencies:G,createClone:Bu},$r={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,bignumberDependencies:Yr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createSmaller:Gc},N2={DenseMatrixDependencies:it,smallerDependencies:$r,createImmutableDenseMatrixClass:sh},N0={typedDependencies:G,createGetMatrixDataType:Yl},Mr={ImmutableDenseMatrixDependencies:N2,getMatrixDataTypeDependencies:N0,createIndexClass:ah},Cs={typedDependencies:G,createIsPositive:Uu},Zm={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createLargerEq:Kc},Da={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createSmallerEq:Yc},Aa={bignumberDependencies:Yr,matrixDependencies:Ne,addDependencies:ft,equalDependencies:Jr,isPositiveDependencies:Cs,isZeroDependencies:wi,largerDependencies:Ir,largerEqDependencies:Zm,smallerDependencies:$r,smallerEqDependencies:Da,typedDependencies:G,createRange:ao},C2={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createColumn:to},qI={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createColumnTransform:em},HI={typedDependencies:G,createCombinationsWithRep:cd},Ds={BigNumberDependencies:De,DenseMatrixDependencies:it,FractionDependencies:xs,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createCompare:Ic},Ji={compareDependencies:Ds,typedDependencies:G,createCompareNatural:qc},D2={concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createCompareText:Hc},A2={NodeDependencies:Er,createConditionalNode:df},Wn={NodeDependencies:Er,createConstantNode:mf},E2={NodeDependencies:Er,typedDependencies:G,createFunctionAssignmentNode:vf},jn={UnitDependencies:Ve,NodeDependencies:Er,createSymbolNode:Ff},Gn={NodeDependencies:Er,SymbolNodeDependencies:jn,createFunctionNode:Of},Ea={NodeDependencies:Er,sizeDependencies:ir,createIndexNode:bf},Ma={NodeDependencies:Er,createObjectNode:wf},dn={NodeDependencies:Er,createOperatorNode:Nf},As={NodeDependencies:Er,createParenthesisNode:Df},M2={NodeDependencies:Er,createRangeNode:Ef},T2={NodeDependencies:Er,createRelationalNode:Tf},Pi={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,AssignmentNodeDependencies:f2,BlockNodeDependencies:x2,ConditionalNodeDependencies:A2,ConstantNodeDependencies:Wn,FunctionAssignmentNodeDependencies:E2,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,RangeNodeDependencies:M2,RelationalNodeDependencies:T2,SymbolNodeDependencies:jn,numericDependencies:xi,typedDependencies:G,createParse:Bf},UI={parseDependencies:Pi,typedDependencies:G,createCompile:kf},Qm={ComplexDependencies:Et,typedDependencies:G,createComplex:tl},VI={addScalarDependencies:rr,combinationsDependencies:Jm,isIntegerDependencies:Xr,isNegativeDependencies:Vn,isPositiveDependencies:Cs,largerDependencies:Ir,typedDependencies:G,createComposition:Cd},WI={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createConcatTransform:hm},jI={BigNumberDependencies:De,UnitDependencies:Ve,createConductanceQuantum:fp},yr={divideScalarDependencies:$t,equalScalarDependencies:ot,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createDivide:rd},F2={addDependencies:ft,divideDependencies:yr,typedDependencies:G,createMean:wo},zi={ComplexDependencies:Et,typedDependencies:G,createSqrt:Fl},Gt={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createSubtract:Ol},C0={addDependencies:ft,numericDependencies:xi,typedDependencies:G,createSum:bo},GI={addDependencies:ft,divideDependencies:yr,matrixDependencies:Ne,meanDependencies:F2,multiplyDependencies:Nt,powDependencies:ki,sqrtDependencies:zi,subtractDependencies:Gt,sumDependencies:C0,typedDependencies:G,createCorr:ud},D0={typedDependencies:G,createCos:Eh},XI={typedDependencies:G,createCosh:Mh},YI={BigNumberDependencies:De,typedDependencies:G,createCot:Th},JI={BigNumberDependencies:De,typedDependencies:G,createCoth:Fh},ZI={BigNumberDependencies:De,UnitDependencies:Ve,createCoulomb:up},QI={BigNumberDependencies:De,UnitDependencies:Ve,createCoulombConstant:lp},_2={multiplyScalarDependencies:jt,numericDependencies:xi,typedDependencies:G,createProd:pc},KI={prodDependencies:_2,sizeDependencies:ir,typedDependencies:G,createCount:Wl},e$={UnitDependencies:Ve,typedDependencies:G,createCreateUnit:dh},t$={matrixDependencies:Ne,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createCross:jl},r$={BigNumberDependencies:De,typedDependencies:G,createCsc:_h},i$={BigNumberDependencies:De,typedDependencies:G,createCsch:Oh},Lo={matrixDependencies:Ne,typedDependencies:G,createTranspose:sc},A0={conjDependencies:Ss,transposeDependencies:Lo,typedDependencies:G,createCtranspose:ac},n$={typedDependencies:G,createCube:gl},E0={numericDependencies:xi,typedDependencies:G,createUnaryPlus:ll},s$={addDependencies:ft,typedDependencies:G,unaryPlusDependencies:E0,createCumSum:xo},a$={addDependencies:ft,typedDependencies:G,unaryPlusDependencies:E0,createCumSumTransform:gm},Io={equalDependencies:Jr,typedDependencies:G,createDeepEqual:eh},O2={createReplacer:Rd},B2={ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,parseDependencies:Pi,typedDependencies:G,createResolve:Fd},M0={bignumberDependencies:Yr,fractionDependencies:Po,AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,SymbolNodeDependencies:jn,matrixDependencies:Ne,typedDependencies:G,createSimplifyConstant:Md},T0={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,isZeroDependencies:wi,multiplyDependencies:Nt,parseDependencies:Pi,powDependencies:ki,subtractDependencies:Gt,typedDependencies:G,createSimplifyCore:Td},Km={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,equalDependencies:Jr,parseDependencies:Pi,replacerDependencies:O2,resolveDependencies:B2,simplifyConstantDependencies:M0,simplifyCoreDependencies:T0,typedDependencies:G,createSimplify:Ed},o$={ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,equalDependencies:Jr,isZeroDependencies:wi,numericDependencies:xi,parseDependencies:Pi,simplifyDependencies:Km,typedDependencies:G,createDerivative:Od},u$={BigNumberDependencies:De,UnitDependencies:Ve,createDeuteronMass:Cp},k2={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,matrixDependencies:Ne,typedDependencies:G,createDiag:Gl},l$={matrixDependencies:Ne,numberDependencies:fn,subtractDependencies:Gt,typedDependencies:G,createDiff:so},c$={bignumberDependencies:Yr,matrixDependencies:Ne,numberDependencies:fn,subtractDependencies:Gt,typedDependencies:G,createDiffTransform:fm},h$={absDependencies:Lr,addScalarDependencies:rr,deepEqualDependencies:Io,divideScalarDependencies:$t,multiplyScalarDependencies:jt,sqrtDependencies:zi,subtractScalarDependencies:Si,typedDependencies:G,createDistance:id},$o={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createDotDivide:Fc},f$={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createDotMultiply:Pl},d$={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,powDependencies:ki,typedDependencies:G,createDotPow:Tc},P2={BigNumberDependencies:De,createE:Wd},p$={BigNumberDependencies:De,createEfimovFactor:Fp},Es={typedDependencies:G,createFlatten:Xl},F0={typedDependencies:G,createIm:ql},_0={flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createMatrixFromColumns:al},z2={BigNumberDependencies:De,FractionDependencies:xs,complexDependencies:Qm,typedDependencies:G,createSign:Tl},O0={addScalarDependencies:rr,complexDependencies:Qm,conjDependencies:Ss,divideScalarDependencies:$t,equalDependencies:Jr,identityDependencies:Un,isZeroDependencies:wi,matrixDependencies:Ne,multiplyScalarDependencies:jt,signDependencies:z2,sqrtDependencies:zi,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,zerosDependencies:vr,createQr:If},B0={typedDependencies:G,createRe:Hl},R2={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createReshape:Kl},eg={typedDependencies:G,createSin:Ph},k0={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createUsolve:Oc},L2={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createUsolveAll:kc},I2={absDependencies:Lr,addDependencies:ft,addScalarDependencies:rr,atanDependencies:d2,bignumberDependencies:Yr,columnDependencies:C2,complexDependencies:Qm,cosDependencies:D0,diagDependencies:k2,divideScalarDependencies:$t,dotDependencies:Ym,equalDependencies:Jr,flattenDependencies:Es,imDependencies:F0,invDependencies:Ns,largerDependencies:Ir,matrixDependencies:Ne,matrixFromColumnsDependencies:_0,multiplyDependencies:Nt,multiplyScalarDependencies:jt,numberDependencies:fn,qrDependencies:O0,reDependencies:B0,reshapeDependencies:R2,sinDependencies:eg,sizeDependencies:ir,smallerDependencies:$r,sqrtDependencies:zi,subtractDependencies:Gt,typedDependencies:G,usolveDependencies:k0,usolveAllDependencies:L2,createEigs:Jf},m$={BigNumberDependencies:De,UnitDependencies:Ve,createElectricConstant:ap},g$={BigNumberDependencies:De,UnitDependencies:Ve,createElectronMass:bp},v$={BigNumberDependencies:De,UnitDependencies:Ve,createElementaryCharge:cp},y$={compareTextDependencies:D2,isZeroDependencies:wi,typedDependencies:G,createEqualText:Wc},b$={typedDependencies:G,createErf:hc},P0={parseDependencies:Pi,typedDependencies:G,createEvaluate:Pf},$2={typedDependencies:G,createExp:vl},x$={absDependencies:Lr,addDependencies:ft,identityDependencies:Un,invDependencies:Ns,multiplyDependencies:Nt,typedDependencies:G,createExpm:Zf},w$={ComplexDependencies:Et,typedDependencies:G,createExpm1:yl},S$={createFalse:Id},N$={BigNumberDependencies:De,UnitDependencies:Ve,createFaraday:kp},C$={BigNumberDependencies:De,UnitDependencies:Ve,createFermiCoupling:xp},q2={ComplexDependencies:Et,createI:Kd},z0={ComplexDependencies:Et,typedDependencies:G,createLog2:Dl},H2={BigNumberDependencies:De,createTau:Vd},U2={addScalarDependencies:rr,ceilDependencies:w0,conjDependencies:Ss,divideScalarDependencies:$t,dotDivideDependencies:$o,expDependencies:$2,iDependencies:q2,log2Dependencies:z0,matrixDependencies:Ne,multiplyScalarDependencies:jt,powDependencies:ki,tauDependencies:H2,typedDependencies:G,createFft:uc},V2={largerDependencies:Ir,smallerDependencies:$r,createFibonacciHeapClass:oh},D$={typedDependencies:G,createFilter:ro},A$={typedDependencies:G,createFilterTransform:tm},E$={BigNumberDependencies:De,createFineStructure:wp},M$={BigNumberDependencies:De,UnitDependencies:Ve,createFirstRadiation:Pp},T$={typedDependencies:G,createForEach:io},F$={typedDependencies:G,createForEachTransform:rm},_$={ComplexDependencies:Et,addDependencies:ft,divideDependencies:yr,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createFreqz:Pd},O$={BigNumberDependencies:De,UnitDependencies:Ve,createGasConstant:Rp},B$={BigNumberDependencies:De,DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createGcd:wl},k$={BigNumberDependencies:De,UnitDependencies:Ve,createGravitationConstant:rp},P$={BigNumberDependencies:De,UnitDependencies:Ve,createGravity:jp},z$={BigNumberDependencies:De,UnitDependencies:Ve,createHartreeEnergy:Sp},R$={isNumericDependencies:ws,typedDependencies:G,createHasNumericValue:Hu},W2={evaluateDependencies:P0,createHelpClass:Uf},L$={HelpDependencies:W2,typedDependencies:G,createHelp:Wf},I$={formatDependencies:zo,typedDependencies:G,createHex:yc},$$={absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,isPositiveDependencies:Cs,multiplyScalarDependencies:jt,smallerDependencies:$r,sqrtDependencies:zi,typedDependencies:G,createHypot:Jh},q$={conjDependencies:Ss,dotDivideDependencies:$o,fftDependencies:U2,typedDependencies:G,createIfft:lc},j2={IndexDependencies:Mr,typedDependencies:G,createIndex:ef},H$={IndexDependencies:Mr,getMatrixDataTypeDependencies:N0,createIndexTransform:im},U$={BigNumberDependencies:De,createInfinity:qd},V$={absDependencies:Lr,addDependencies:ft,addScalarDependencies:rr,divideScalarDependencies:$t,equalScalarDependencies:ot,flattenDependencies:Es,isNumericDependencies:ws,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,multiplyScalarDependencies:jt,smallerDependencies:$r,subtractDependencies:Gt,typedDependencies:G,createIntersect:nd},W$={BigNumberDependencies:De,UnitDependencies:Ve,createInverseConductanceQuantum:dp},G2={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createMod:Xa},X2={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createXgcd:Bl},j$={BigNumberDependencies:De,addDependencies:ft,equalDependencies:Jr,isIntegerDependencies:Xr,modDependencies:G2,smallerDependencies:$r,typedDependencies:G,xgcdDependencies:X2,createInvmod:kl},pn={typedDependencies:G,createIsNaN:Wu},G$={typedDependencies:G,createIsPrime:wc},R0={typedDependencies:G,createTypeOf:ju},L0={ComplexDependencies:Et,divideScalarDependencies:$t,typeOfDependencies:R0,typedDependencies:G,createLog:Ac},Ms={typedDependencies:G,createMap:no},X$={divideDependencies:yr,dotDivideDependencies:$o,isNumericDependencies:ws,logDependencies:L0,mapDependencies:Ms,matrixDependencies:Ne,multiplyDependencies:Nt,sumDependencies:C0,typedDependencies:G,createKldivergence:pd},Y$={BigNumberDependencies:De,UnitDependencies:Ve,createKlitzing:gp},J$={matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createKron:Zl},Z$={BigNumberDependencies:De,createLN10:Xd},Q$={BigNumberDependencies:De,createLN2:Gd},K$={BigNumberDependencies:De,createLOG10E:Jd},e6={BigNumberDependencies:De,createLOG2E:Yd},t6={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createLcm:Nl},r6={parseDependencies:Pi,typedDependencies:G,createLeafCount:Dd},i6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createLeftShift:Pc},n6={ComplexDependencies:Et,typedDependencies:G,createLgamma:fd},s6={ComplexDependencies:Et,typedDependencies:G,createLog10:Cl},a6={ComplexDependencies:Et,divideScalarDependencies:$t,logDependencies:L0,typedDependencies:G,createLog1p:Ec},o6={BigNumberDependencies:De,UnitDependencies:Ve,createLoschmidt:zp},Y2={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createLsolve:_c},u6={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createLsolveAll:Bc},J2={FibonacciHeapDependencies:V2,addScalarDependencies:rr,equalScalarDependencies:ot,createSpaClass:uh},Z2={DenseMatrixDependencies:it,SpaDependencies:J2,SparseMatrixDependencies:tr,absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,equalScalarDependencies:ot,largerDependencies:Ir,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createLup:Lf},Q2={SparseMatrixDependencies:tr,absDependencies:Lr,addDependencies:ft,divideScalarDependencies:$t,largerDependencies:Ir,largerEqDependencies:Zm,multiplyDependencies:Nt,subtractDependencies:Gt,transposeDependencies:Lo,typedDependencies:G,createSlu:$f},K2={DenseMatrixDependencies:it,lsolveDependencies:Y2,lupDependencies:Z2,matrixDependencies:Ne,sluDependencies:Q2,typedDependencies:G,usolveDependencies:k0,createLusolve:qf},I0={absDependencies:Lr,addDependencies:ft,conjDependencies:Ss,ctransposeDependencies:A0,eigsDependencies:I2,equalScalarDependencies:ot,largerDependencies:Ir,matrixDependencies:Ne,multiplyDependencies:Nt,powDependencies:ki,smallerDependencies:$r,sqrtDependencies:zi,typedDependencies:G,createNorm:Zh},eE={identityDependencies:Un,matrixDependencies:Ne,multiplyDependencies:Nt,normDependencies:I0,qrDependencies:O0,subtractDependencies:Gt,typedDependencies:G,createSchur:ed},tE={absDependencies:Lr,addDependencies:ft,concatDependencies:mt,identityDependencies:Un,indexDependencies:j2,lusolveDependencies:K2,matrixDependencies:Ne,matrixFromColumnsDependencies:_0,multiplyDependencies:Nt,rangeDependencies:Aa,schurDependencies:eE,subsetDependencies:ni,subtractDependencies:Gt,transposeDependencies:Lo,typedDependencies:G,createSylvester:Kf},l6={matrixDependencies:Ne,multiplyDependencies:Nt,sylvesterDependencies:tE,transposeDependencies:Lo,typedDependencies:G,createLyap:td},tg={compareDependencies:Ds,isNaNDependencies:pn,isNumericDependencies:ws,typedDependencies:G,createPartitionSelect:ih},rE={addDependencies:ft,compareDependencies:Ds,divideDependencies:yr,partitionSelectDependencies:tg,typedDependencies:G,createMedian:ad},c6={absDependencies:Lr,mapDependencies:Ms,medianDependencies:rE,subtractDependencies:Gt,typedDependencies:G,createMad:od},h6={BigNumberDependencies:De,UnitDependencies:Ve,createMagneticConstant:sp},f6={BigNumberDependencies:De,UnitDependencies:Ve,createMagneticFluxQuantum:pp},qo={isIntegerDependencies:Xr,typedDependencies:G,createMapSlices:la},d6={isIntegerDependencies:Xr,typedDependencies:G,createMapSlicesTransform:Kp},p6={typedDependencies:G,createMapTransform:nm},m6={isZeroDependencies:wi,matrixDependencies:Ne,typedDependencies:G,createMatrixFromFunction:nl},g6={flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createMatrixFromRows:sl},$0={isNaNDependencies:pn,largerDependencies:Ir,numericDependencies:xi,typedDependencies:G,createMax:po},v6={isNaNDependencies:pn,largerDependencies:Ir,numericDependencies:xi,typedDependencies:G,createMaxTransform:sm},y6={addDependencies:ft,divideDependencies:yr,typedDependencies:G,createMeanTransform:am},b6={isNaNDependencies:pn,numericDependencies:xi,smallerDependencies:$r,typedDependencies:G,createMin:mo},x6={isNaNDependencies:pn,numericDependencies:xi,smallerDependencies:$r,typedDependencies:G,createMinTransform:om},w6={isNaNDependencies:pn,isNumericDependencies:ws,typedDependencies:G,createMode:dc},S6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarMass:Vp},N6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarMassC12:Wp},C6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarPlanckConstant:Lp},D6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarVolume:Ip},A6={addDependencies:ft,divideDependencies:yr,factorialDependencies:Ro,isIntegerDependencies:Xr,isPositiveDependencies:Cs,multiplyDependencies:Nt,typedDependencies:G,createMultinomial:md},E6={BigNumberDependencies:De,createNaN:Hd},M6={BigNumberDependencies:De,UnitDependencies:Ve,createNeutronMass:Dp},T6={BigNumberDependencies:De,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createNthRoot:Ml},F6={ComplexDependencies:Et,divideScalarDependencies:$t,typedDependencies:G,createNthRoots:Mc},_6={BigNumberDependencies:De,UnitDependencies:Ve,createNuclearMagneton:mp},O6={createNull:$d},B6={deepEqualDependencies:Io,flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createNullish:Qa},k6={deepEqualDependencies:Io,flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createNullishTransform:wm},P6={formatDependencies:zo,typedDependencies:G,createOct:vc},z6={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createOnes:Ql},R6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createOr:Ka},L6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createOrTransform:xm},iE={evaluateDependencies:P0,parseDependencies:Pi,createParserClass:zf},I6={ParserDependencies:iE,typedDependencies:G,createParser:Rf},$6={factorialDependencies:Ro,typedDependencies:G,createPermutations:gd},q6={BigNumberDependencies:De,createPhi:jd},q0={BigNumberDependencies:De,createPi:Ud},H6={typedDependencies:G,createPickRandom:yd},U6={ComplexDependencies:Et,addDependencies:ft,ctransposeDependencies:A0,deepEqualDependencies:Io,divideScalarDependencies:$t,dotDependencies:Ym,dotDivideDependencies:$o,equalDependencies:Jr,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createPinv:Yf},V6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckCharge:Jp},W6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckConstant:ip},j6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckLength:Gp},G6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckMass:Xp},X6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckTemperature:Zp},Y6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckTime:Yp},J6={addDependencies:ft,cbrtDependencies:w2,divideDependencies:yr,equalScalarDependencies:ot,imDependencies:F0,isZeroDependencies:wi,multiplyDependencies:Nt,reDependencies:B0,sqrtDependencies:zi,subtractDependencies:Gt,typeOfDependencies:R0,typedDependencies:G,unaryMinusDependencies:Yi,createPolynomialRoot:Hf},Z6={typedDependencies:G,createPrint:co},Q6={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createPrintTransform:ym},K6={BigNumberDependencies:De,UnitDependencies:Ve,createProtonMass:Np},e7={bignumberDependencies:Yr,addDependencies:ft,compareDependencies:Ds,divideDependencies:yr,isIntegerDependencies:Xr,largerDependencies:Ir,mapSlicesDependencies:qo,multiplyDependencies:Nt,partitionSelectDependencies:tg,smallerDependencies:$r,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createQuantileSeq:No},t7={addDependencies:ft,bignumberDependencies:Yr,compareDependencies:Ds,divideDependencies:yr,isIntegerDependencies:Xr,largerDependencies:Ir,mapSlicesDependencies:qo,multiplyDependencies:Nt,partitionSelectDependencies:tg,smallerDependencies:$r,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createQuantileSeqTransform:mm},r7={BigNumberDependencies:De,UnitDependencies:Ve,createQuantumOfCirculation:Ap},i7={typedDependencies:G,createRandom:bd},n7={log2Dependencies:z0,typedDependencies:G,createRandomInt:xd},s7={createRangeClass:Cu},a7={bignumberDependencies:Yr,matrixDependencies:Ne,addDependencies:ft,equalDependencies:Jr,isPositiveDependencies:Cs,isZeroDependencies:wi,largerDependencies:Ir,largerEqDependencies:Zm,smallerDependencies:$r,smallerEqDependencies:Da,typedDependencies:G,createRangeTransform:um},o7={bignumberDependencies:Yr,fractionDependencies:Po,AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,parseDependencies:Pi,powDependencies:ki,simplifyDependencies:Km,simplifyConstantDependencies:M0,simplifyCoreDependencies:T0,subtractDependencies:Gt,typedDependencies:G,createRationalize:Bd},u7={BigNumberDependencies:De,UnitDependencies:Ve,createReducedPlanckConstant:np},l7={matrixDependencies:Ne,createResize:ec},c7={createReviver:zd},h7={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRightArithShift:zc},f7={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRightLogShift:Rc},nE={BigNumberDependencies:De,DenseMatrixDependencies:it,SparseMatrixDependencies:tr,addScalarDependencies:rr,cosDependencies:D0,matrixDependencies:Ne,multiplyScalarDependencies:jt,normDependencies:I0,sinDependencies:eg,typedDependencies:G,unaryMinusDependencies:Yi,createRotationMatrix:rc},d7={multiplyDependencies:Nt,rotationMatrixDependencies:nE,typedDependencies:G,createRotate:tc},p7={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createRow:oo},m7={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createRowTransform:lm},g7={BigNumberDependencies:De,UnitDependencies:Ve,createRydberg:Ep},v7={BigNumberDependencies:De,createSQRT1_2:Zd},y7={BigNumberDependencies:De,createSQRT2:Qd},b7={BigNumberDependencies:De,createSackurTetrode:$p},x7={BigNumberDependencies:De,typedDependencies:G,createSec:Bh},w7={BigNumberDependencies:De,typedDependencies:G,createSech:kh},S7={BigNumberDependencies:De,UnitDependencies:Ve,createSecondRadiation:qp},N7={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetCartesian:Ih},sE={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetDifference:$h},C7={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetDistinct:qh},aE={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetIntersect:Hh},D7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetIsSubset:Uh},A7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetMultiplicity:Vh},E7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetPowerset:Wh},M7={compareNaturalDependencies:Ji,typedDependencies:G,createSetSize:jh},oE={IndexDependencies:Mr,concatDependencies:mt,setDifferenceDependencies:sE,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetSymDifference:Gh},T7={IndexDependencies:Mr,concatDependencies:mt,setIntersectDependencies:aE,setSymDifferenceDependencies:oE,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetUnion:Xh},F7={typedDependencies:G,createSinh:zh},_7={absDependencies:Lr,addDependencies:ft,bignumberDependencies:Yr,divideDependencies:yr,isNegativeDependencies:Vn,isPositiveDependencies:Cs,largerDependencies:Ir,mapDependencies:Ms,matrixDependencies:Ne,maxDependencies:$0,multiplyDependencies:Nt,smallerDependencies:$r,subtractDependencies:Gt,typedDependencies:G,unaryMinusDependencies:Yi,createSolveODE:cc},O7={compareDependencies:Ds,compareNaturalDependencies:Ji,matrixDependencies:Ne,typedDependencies:G,createSort:nh},B7={SparseMatrixDependencies:tr,typedDependencies:G,createSparse:fh},k7={BigNumberDependencies:De,UnitDependencies:Ve,createSpeedOfLight:tp},P7={typedDependencies:G,createSplitUnit:ol},z7={absDependencies:Lr,addDependencies:ft,identityDependencies:Un,invDependencies:Ns,mapDependencies:Ms,maxDependencies:$0,multiplyDependencies:Nt,sizeDependencies:ir,sqrtDependencies:zi,subtractDependencies:Gt,typedDependencies:G,createSqrtm:Qf},R7={typedDependencies:G,createSquare:_l},L7={typedDependencies:G,createSqueeze:nc},H0={addDependencies:ft,divideDependencies:yr,isNaNDependencies:pn,mapSlicesDependencies:qo,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createVariance:So},I7={mapDependencies:Ms,sqrtDependencies:zi,typedDependencies:G,varianceDependencies:H0,createStd:Co},$7={mapDependencies:Ms,sqrtDependencies:zi,typedDependencies:G,varianceDependencies:H0,createStdTransform:dm},q7={BigNumberDependencies:De,UnitDependencies:Ve,createStefanBoltzmann:Hp},H7={typedDependencies:G,createString:Qu},U7={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createSubsetTransform:cm},V7={addDependencies:ft,numericDependencies:xi,typedDependencies:G,createSumTransform:pm},W7={OperatorNodeDependencies:dn,parseDependencies:Pi,simplifyDependencies:Km,typedDependencies:G,createSymbolicEqual:_d},j7={typedDependencies:G,createTan:Rh},G7={typedDependencies:G,createTanh:Lh},X7={BigNumberDependencies:De,UnitDependencies:Ve,createThomsonCrossSection:Mp},Y7={concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createTo:bc},J7={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,createTrace:Kh},Z7={createTrue:Ld},Q7={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createUnequal:rh},K7={UnitDependencies:Ve,typedDependencies:G,createUnitFunction:hh},eq={eDependencies:P2,createUppercaseE:Nv},tq={piDependencies:q0,createUppercasePi:Sv},rq={BigNumberDependencies:De,UnitDependencies:Ve,createVacuumImpedance:op},iq={addDependencies:ft,divideDependencies:yr,isNaNDependencies:pn,mapSlicesDependencies:qo,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createVarianceTransform:vm},nq={createVersion:ep},sq={BigNumberDependencies:De,createWeakMixingAngle:Tp},aq={BigNumberDependencies:De,UnitDependencies:Ve,createWienDisplacement:Up},oq={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createXor:Vl},uq={BigNumberDependencies:De,ComplexDependencies:Et,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,factorialDependencies:Ro,gammaDependencies:S0,isNegativeDependencies:Vn,multiplyDependencies:Nt,piDependencies:q0,powDependencies:ki,sinDependencies:eg,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createZeta:fc},lq={ComplexDependencies:Et,addDependencies:ft,multiplyDependencies:Nt,numberDependencies:fn,typedDependencies:G,createZpk2tf:kd},cq=sI,U0={exports:{}};function V0(){}V0.prototype={on:function(n,e,t){var r=this.e||(this.e={});return(r[n]||(r[n]=[])).push({fn:e,ctx:t}),this},once:function(n,e,t){var r=this;function i(){r.off(n,i),e.apply(t,arguments)}return i._=e,this.on(n,i,t)},emit:function(n){var e=[].slice.call(arguments,1),t=((this.e||(this.e={}))[n]||[]).slice(),r=0,i=t.length;for(r;r<i;r++)t[r].fn.apply(t[r].ctx,e);return this},off:function(n,e){var t=this.e||(this.e={}),r=t[n],i=[];if(r&&e)for(var s=0,a=r.length;s<a;s++)r[s].fn!==e&&r[s].fn._!==e&&i.push(r[s]);return i.length?t[n]=i:delete t[n],this}},U0.exports=V0,U0.exports.TinyEmitter=V0;var hq=U0.exports;const fq=$c(hq);function dq(n){var e=new fq;return n.on=e.on.bind(e),n.off=e.off.bind(e),n.once=e.once.bind(e),n.emit=e.emit.bind(e),n}function pq(n,e,t,r){function i(v,S){var g=arguments.length;if(g!==1&&g!==2)throw new Vi("import",g,1,2);S||(S={});function b(D,C,A){if(Array.isArray(C))C.forEach(O=>b(D,O));else if(yn(C)||h(C))for(var E in C)Te(C,E)&&b(D,C[E],E);else if(qa(C)||A!==void 0){var F=qa(C)?m(C)?C.fn+".transform":C.fn:A;if(Te(D,F)&&D[F]!==C&&!S.silent)throw new Error('Cannot import "'+F+'" twice');D[F]=C}else if(!S.silent)throw new TypeError("Factory, Object, or Array expected")}var w={};b(w,v);for(var x in w)if(Te(w,x)){var N=w[x];if(qa(N))u(N,S);else if(c(N))s(x,N,S);else if(!S.silent)throw new TypeError("Factory, Object, or Array expected")}}function s(v,S,g){var b;if(g.wrap&&typeof S=="function"&&(S=l(S)),f(S)&&(S=n(v,{[S.signature]:S})),n.isTypedFunction(t[v])&&n.isTypedFunction(S)){g.override?S=n(v,S.signatures):S=n(t[v],S),t[v]=S,delete r[v],a(v,S),t.emit("import",v,function(){return S});return}var w=t[v]!==void 0,x=(b=t.Unit)===null||b===void 0?void 0:b.isValuelessUnit(v);if(!w&&!x||g.override){t[v]=S,delete r[v],a(v,S),t.emit("import",v,function(){return S});return}if(!g.silent)throw new Error('Cannot import "'+v+'": already exists')}function a(v,S){S&&typeof S.transform=="function"?(t.expression.transform[v]=S.transform,d(v)&&(t.expression.mathWithTransform[v]=S.transform)):(delete t.expression.transform[v],d(v)&&(t.expression.mathWithTransform[v]=S))}function o(v){delete t.expression.transform[v],d(v)?t.expression.mathWithTransform[v]=t[v]:delete t.expression.mathWithTransform[v]}function l(v){var S=function(){for(var b=[],w=0,x=arguments.length;w<x;w++){var N=arguments[w];b[w]=N&&N.valueOf()}return v.apply(t,b)};return v.transform&&(S.transform=v.transform),S}function u(v,S){var g,b,w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v.fn;if(w.includes("."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(w));var x=m(v)?t.expression.transform:t,N=w in t.expression.transform,D=Te(x,w)?x[w]:void 0,C=function(){var k={};v.dependencies.map(Oy).forEach(T=>{if(T.includes("."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(T));T==="math"?k.math=t:T==="mathWithTransform"?k.mathWithTransform=t.expression.mathWithTransform:T==="classes"?k.classes=t:k[T]=t[T]});var B=v(k);if(B&&typeof B.transform=="function")throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with export const path = "expression.transform"');if(D===void 0||S.override)return B;if(n.isTypedFunction(D)&&n.isTypedFunction(B))return n(D,B);if(S.silent)return D;throw new Error('Cannot import "'+w+'": already exists')},A=(g=(b=v.meta)===null||b===void 0?void 0:b.formerly)!==null&&g!==void 0?g:"",E=m(v)||p(v),F=t.expression.mathWithTransform;!v.meta||v.meta.lazy!==!1?(is(x,w,C),A&&is(x,A,C),D&&N?(o(w),A&&o(A)):E&&(is(F,w,()=>x[w]),A&&is(F,A,()=>x[w]))):(x[w]=C(),A&&(x[A]=x[w]),D&&N?(o(w),A&&o(A)):E&&(is(F,w,()=>x[w]),A&&is(F,A,()=>x[w]))),r[w]=v,t.emit("import",w,C)}function c(v){return typeof v=="function"||typeof v=="number"||typeof v=="string"||typeof v=="boolean"||v===null||br(v)||ci(v)||Xe(v)||vn(v)||Re(v)||Array.isArray(v)}function h(v){return typeof v=="object"&&v[Symbol.toStringTag]==="Module"}function f(v){return typeof v=="function"&&typeof v.signature=="string"}function d(v){return!Te(y,v)}function p(v){return!v.fn.includes(".")&&!Te(y,v.fn)&&(!v.meta||!v.meta.isClass)}function m(v){return v!==void 0&&v.meta!==void 0&&v.meta.isTransformFunction===!0||!1}var y={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return i}function uE(n,e){var t=wt({},tu,e);if(typeof Object.create!="function")throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=dq({isNumber:Je,isComplex:ci,isBigNumber:Xe,isBigInt:ts,isFraction:vn,isUnit:br,isString:nr,isArray:St,isMatrix:Re,isCollection:Or,isDenseMatrix:Vs,isSparseMatrix:Ki,isRange:Ia,isIndex:Ws,isBoolean:hg,isResultSet:fg,isHelp:nu,isFunction:su,isDate:dg,isRegExp:pg,isObject:yn,isMap:bn,isPartitionedMap:Ny,isObjectWrappingMap:Cy,isNull:mg,isUndefined:gg,isAccessorNode:en,isArrayNode:Vr,isAssignmentNode:vg,isBlockNode:yg,isConditionalNode:bg,isConstantNode:ct,isFunctionAssignmentNode:rs,isFunctionNode:qi,isIndexNode:xn,isNode:bt,isObjectNode:js,isOperatorNode:qt,isParenthesisNode:Ai,isRangeNode:wg,isRelationalNode:Sg,isSymbolNode:Xt,isChain:au});r.config=IE(t,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var i=[],s=[];function a(c){if(qa(c))return c(r);var h=c[Object.keys(c)[0]];if(qa(h))return h(r);if(!RE(c))throw console.warn("Factory object with properties `type`, `name`, and `factory` expected",c),new Error("Factory object with properties `type`, `name`, and `factory` expected");var f=i.indexOf(c),d;return f===-1?(c.math===!0?d=c.factory(r.type,t,a,r.typed,r):d=c.factory(r.type,t,a,r.typed),i.push(c),s.push(d)):d=s[f],d}var o={};function l(){for(var c=arguments.length,h=new Array(c),f=0;f<c;f++)h[f]=arguments[f];return r.typed.apply(r.typed,h)}l.isTypedFunction=$a.isTypedFunction;var u=pq(l,a,r,o);return r.import=u,r.on("config",()=>{Object.values(o).forEach(c=>{c&&c.meta&&c.meta.recreateOnConfigChange&&u(c,{override:!0})})}),r.create=uE.bind(null,n),r.factory=R,r.import(Object.values(zE(n))),r.ArgumentsError=Vi,r.DimensionError=Ke,r.IndexError=Kr,r}const W0=Object.freeze(Object.defineProperty({__proto__:null,AccessorNode:ys,AccessorNodeDependencies:Sa,ArgumentsError:Vi,ArrayNode:vs,ArrayNodeDependencies:Na,AssignmentNode:v0,AssignmentNodeDependencies:f2,BigNumber:Ce,BigNumberDependencies:De,BlockNode:d0,BlockNodeDependencies:x2,Chain:Um,ChainDependencies:S2,Complex:Ct,ComplexDependencies:Et,ConditionalNode:p0,ConditionalNodeDependencies:A2,ConstantNode:ln,ConstantNodeDependencies:Wn,DenseMatrix:tt,DenseMatrixDependencies:it,DimensionError:Ke,EDependencies:eq,FibonacciHeap:Wv,FibonacciHeapDependencies:V2,Fraction:kn,FractionDependencies:xs,FunctionAssignmentNode:g0,FunctionAssignmentNodeDependencies:E2,FunctionNode:hn,FunctionNodeDependencies:Gn,Help:b0,HelpDependencies:W2,ImmutableDenseMatrix:Hv,ImmutableDenseMatrixDependencies:N2,Index:mr,IndexDependencies:Mr,IndexError:Kr,IndexNode:bs,IndexNodeDependencies:Ea,InfinityDependencies:U$,LN10:LN,LN10Dependencies:Z$,LN2:YN,LN2Dependencies:Q$,LOG10E:IN,LOG10EDependencies:K$,LOG2E:vC,LOG2EDependencies:e6,Matrix:Do,MatrixDependencies:Gm,NaNDependencies:E6,Node:gr,NodeDependencies:Er,ObjectNode:gs,ObjectNodeDependencies:Ma,OperatorNode:Xi,OperatorNodeDependencies:dn,PIDependencies:tq,ParenthesisNode:Hn,ParenthesisNodeDependencies:As,Parser:x0,ParserDependencies:iE,Range:UN,RangeDependencies:s7,RangeNode:m0,RangeNodeDependencies:M2,RelationalNode:f0,RelationalNodeDependencies:T2,ResultSet:Mv,ResultSetDependencies:b2,SQRT1_2:VN,SQRT1_2Dependencies:v7,SQRT2:JN,SQRT2Dependencies:y7,Spa:e0,SpaDependencies:J2,SparseMatrix:Zt,SparseMatrixDependencies:tr,SymbolNode:cn,SymbolNodeDependencies:jn,Unit:qe,UnitDependencies:Ve,_Infinity:RN,_NaN:$N,_false:PN,_null:qN,_true:jN,abs:Cr,absDependencies:Lr,acos:QN,acosDependencies:oI,acosh:TC,acoshDependencies:uI,acot:KN,acotDependencies:lI,acoth:VC,acothDependencies:cI,acsc:eC,acscDependencies:hI,acsch:FC,acschDependencies:fI,add:ht,addDependencies:ft,addScalar:Jt,addScalarDependencies:rr,all:cq,and:PD,andDependencies:dI,andTransformDependencies:pI,apply:aI,arg:tC,argDependencies:mI,asec:_C,asecDependencies:gI,asech:rC,asechDependencies:vI,asin:WC,asinDependencies:yI,asinh:iC,asinhDependencies:bI,atan:_v,atan2:nD,atan2Dependencies:xI,atanDependencies:d2,atanh:nC,atanhDependencies:wI,atomicMass:HD,atomicMassDependencies:SI,avogadro:NA,avogadroDependencies:NI,bellNumbers:LA,bellNumbersDependencies:CI,bigint:sC,bigintDependencies:DI,bignumber:zr,bignumberDependencies:Yr,bin:jC,binDependencies:AI,bitAnd:sD,bitAndDependencies:EI,bitAndTransformDependencies:MI,bitNot:aC,bitNotDependencies:TI,bitOr:aD,bitOrDependencies:FI,bitOrTransformDependencies:_I,bitXor:oD,bitXorDependencies:OI,bohrMagneton:UD,bohrMagnetonDependencies:BI,bohrRadius:CA,bohrRadiusDependencies:kI,boltzmann:VD,boltzmannDependencies:PI,boolean:oC,booleanDependencies:zI,catalan:bD,catalanDependencies:RI,cbrt:Iv,cbrtDependencies:w2,ceil:Lm,ceilDependencies:w0,chain:n2,chainDependencies:LI,classicalElectronRadius:GA,classicalElectronRadiusDependencies:II,clone:uC,cloneDependencies:$I,column:Yv,columnDependencies:C2,columnTransformDependencies:qI,combinations:Ao,combinationsDependencies:Jm,combinationsWithRep:OC,combinationsWithRepDependencies:HI,compare:$n,compareDependencies:Ds,compareNatural:Bi,compareNaturalDependencies:Ji,compareText:$v,compareTextDependencies:D2,compile:s2,compileDependencies:UI,complex:Eo,complexDependencies:Qm,composition:xD,compositionDependencies:VI,concat:dt,concatDependencies:mt,concatTransformDependencies:WI,conductanceQuantum:WD,conductanceQuantumDependencies:jI,config:pe,conj:Pn,conjDependencies:Ss,corr:XA,corrDependencies:GI,cos:Dm,cosDependencies:D0,cosh:BC,coshDependencies:XI,cot:lC,cotDependencies:YI,coth:GC,cothDependencies:JI,coulomb:jD,coulombConstant:DA,coulombConstantDependencies:QI,coulombDependencies:ZI,count:uD,countDependencies:KI,create:uE,createAbs:cl,createAccessorNode:nf,createAcos:ph,createAcosh:mh,createAcot:gh,createAcoth:vh,createAcsc:yh,createAcsch:bh,createAdd:Yh,createAddScalar:fl,createAnd:fo,createAndTransform:bm,createArg:Il,createArrayNode:af,createAsec:xh,createAsech:wh,createAsin:Sh,createAsinh:Nh,createAssignmentNode:lf,createAtan:Ch,createAtan2:Dh,createAtanh:Ah,createAtomicMass:_p,createAvogadro:Op,createBellNumbers:Sd,createBigNumberClass:wu,createBigint:Zu,createBignumber:el,createBin:gc,createBitAnd:Ja,createBitAndTransform:Sm,createBitNot:Rl,createBitOr:Za,createBitOrTransform:Nm,createBitXor:Ll,createBlockNode:hf,createBohrMagneton:hp,createBohrRadius:vp,createBoltzmann:Bp,createBoolean:Ku,createCatalan:Nd,createCbrt:pl,createCeil:ml,createChain:jf,createChainClass:Vf,createClassicalElectronRadius:yp,createClone:Bu,createColumn:to,createColumnTransform:em,createCombinations:ld,createCombinationsWithRep:cd,createCompare:Ic,createCompareNatural:qc,createCompareText:Hc,createCompile:kf,createComplex:tl,createComplexClass:Su,createComposition:Cd,createConcat:eo,createConcatTransform:hm,createConditionalNode:df,createConductanceQuantum:fp,createConj:$l,createConstantNode:mf,createCorr:ud,createCos:Eh,createCosh:Mh,createCot:Th,createCoth:Fh,createCoulomb:up,createCoulombConstant:lp,createCount:Wl,createCreateUnit:dh,createCross:jl,createCsc:_h,createCsch:Oh,createCtranspose:ac,createCube:gl,createCumSum:xo,createCumSumTransform:gm,createDeepEqual:eh,createDenseMatrixClass:Ou,createDerivative:Od,createDet:Gf,createDeuteronMass:Cp,createDiag:Gl,createDiff:so,createDiffTransform:fm,createDistance:id,createDivide:rd,createDivideScalar:Nc,createDot:Qh,createDotDivide:Fc,createDotMultiply:Pl,createDotPow:Tc,createE:Wd,createEfimovFactor:Fp,createEigs:Jf,createElectricConstant:ap,createElectronMass:bp,createElementaryCharge:cp,createEqual:Vc,createEqualScalar:Xu,createEqualText:Wc,createErf:hc,createEvaluate:Pf,createExp:vl,createExpm:Zf,createExpm1:yl,createFactorial:dd,createFalse:Id,createFaraday:kp,createFermiCoupling:xp,createFft:uc,createFibonacciHeapClass:oh,createFilter:ro,createFilterTransform:tm,createFineStructure:wp,createFirstRadiation:Pp,createFix:bl,createFlatten:Xl,createFloor:Ga,createForEach:io,createForEachTransform:rm,createFormat:mc,createFraction:rl,createFractionClass:Nu,createFreqz:Pd,createFunctionAssignmentNode:vf,createFunctionNode:Of,createGamma:hd,createGasConstant:Rp,createGcd:wl,createGetMatrixDataType:Yl,createGravitationConstant:rp,createGravity:jp,createHartreeEnergy:Sp,createHasNumericValue:Hu,createHelp:Wf,createHelpClass:Uf,createHex:yc,createHypot:Jh,createI:Kd,createIdentity:Jl,createIfft:lc,createIm:ql,createImmutableDenseMatrixClass:sh,createIndex:ef,createIndexClass:ah,createIndexNode:bf,createIndexTransform:im,createInfinity:qd,createIntersect:nd,createInv:Xf,createInverseConductanceQuantum:dp,createInvmod:kl,createIsInteger:zu,createIsNaN:Wu,createIsNegative:$u,createIsNumeric:qu,createIsPositive:Uu,createIsPrime:wc,createIsZero:Vu,createKldivergence:pd,createKlitzing:gp,createKron:Zl,createLN10:Xd,createLN2:Gd,createLOG10E:Jd,createLOG2E:Yd,createLarger:Zc,createLargerEq:Kc,createLcm:Nl,createLeafCount:Dd,createLeftShift:Pc,createLgamma:fd,createLog:Ac,createLog10:Cl,createLog1p:Ec,createLog2:Dl,createLoschmidt:zp,createLsolve:_c,createLsolveAll:Bc,createLup:Lf,createLusolve:qf,createLyap:td,createMad:od,createMagneticConstant:sp,createMagneticFluxQuantum:pp,createMap:no,createMapSlices:la,createMapSlicesTransform:Kp,createMapTransform:nm,createMatrix:il,createMatrixClass:Du,createMatrixFromColumns:al,createMatrixFromFunction:nl,createMatrixFromRows:sl,createMax:po,createMaxTransform:sm,createMean:wo,createMeanTransform:am,createMedian:ad,createMin:mo,createMinTransform:om,createMod:Xa,createMode:dc,createMolarMass:Vp,createMolarMassC12:Wp,createMolarPlanckConstant:Lp,createMolarVolume:Ip,createMultinomial:md,createMultiply:El,createMultiplyScalar:Al,createNaN:Hd,createNeutronMass:Dp,createNode:tf,createNorm:Zh,createNot:Ul,createNthRoot:Ml,createNthRoots:Mc,createNuclearMagneton:mp,createNull:$d,createNullish:Qa,createNullishTransform:wm,createNumber:Ju,createNumeric:Sc,createObjectNode:wf,createOct:vc,createOnes:Ql,createOperatorNode:Nf,createOr:Ka,createOrTransform:xm,createParenthesisNode:Df,createParse:Bf,createParser:Rf,createParserClass:zf,createPartitionSelect:ih,createPermutations:gd,createPhi:jd,createPi:Ud,createPickRandom:yd,createPinv:Yf,createPlanckCharge:Jp,createPlanckConstant:ip,createPlanckLength:Gp,createPlanckMass:Xp,createPlanckTemperature:Zp,createPlanckTime:Yp,createPolynomialRoot:Hf,createPow:Cc,createPrint:co,createPrintTransform:ym,createProd:pc,createProtonMass:Np,createQr:If,createQuantileSeq:No,createQuantileSeqTransform:mm,createQuantumOfCirculation:Ap,createRandom:bd,createRandomInt:xd,createRange:ao,createRangeClass:Cu,createRangeNode:Ef,createRangeTransform:um,createRationalize:Bd,createRe:Hl,createReducedPlanckConstant:np,createRelationalNode:Tf,createReplacer:Rd,createReshape:Kl,createResize:ec,createResolve:Fd,createResultSet:fu,createReviver:zd,createRightArithShift:zc,createRightLogShift:Rc,createRotate:tc,createRotationMatrix:rc,createRound:Dc,createRow:oo,createRowTransform:lm,createRydberg:Ep,createSQRT1_2:Zd,createSQRT2:Qd,createSackurTetrode:$p,createSchur:ed,createSec:Bh,createSech:kh,createSecondRadiation:qp,createSetCartesian:Ih,createSetDifference:$h,createSetDistinct:qh,createSetIntersect:Hh,createSetIsSubset:Uh,createSetMultiplicity:Vh,createSetPowerset:Wh,createSetSize:jh,createSetSymDifference:Gh,createSetUnion:Xh,createSign:Tl,createSimplify:Ed,createSimplifyConstant:Md,createSimplifyCore:Td,createSin:Ph,createSinh:zh,createSize:ic,createSlu:$f,createSmaller:Gc,createSmallerEq:Yc,createSolveODE:cc,createSort:nh,createSpaClass:uh,createSparse:fh,createSparseMatrixClass:Yu,createSpeedOfLight:tp,createSplitUnit:ol,createSqrt:Fl,createSqrtm:Qf,createSquare:_l,createSqueeze:nc,createStd:Co,createStdTransform:dm,createStefanBoltzmann:Hp,createStirlingS2:wd,createString:Qu,createSubset:uo,createSubsetTransform:cm,createSubtract:Ol,createSubtractScalar:dl,createSum:bo,createSumTransform:pm,createSylvester:Kf,createSymbolNode:Ff,createSymbolicEqual:_d,createTan:Rh,createTanh:Lh,createTau:Vd,createThomsonCrossSection:Mp,createTo:bc,createToBest:xc,createTrace:Kh,createTranspose:sc,createTrue:Ld,createTypeOf:ju,createTyped:uu,createUnaryMinus:ul,createUnaryPlus:ll,createUnequal:rh,createUnit:GD,createUnitClass:ch,createUnitDependencies:e$,createUnitFunction:hh,createUppercaseE:Nv,createUppercasePi:Sv,createUsolve:Oc,createUsolveAll:kc,createVacuumImpedance:op,createVariance:So,createVarianceTransform:vm,createVersion:ep,createWeakMixingAngle:Tp,createWienDisplacement:Up,createXgcd:Bl,createXor:Vl,createZeros:oc,createZeta:fc,createZpk2tf:kd,cross:zD,crossDependencies:t$,csc:cC,cscDependencies:r$,csch:kC,cschDependencies:i$,ctranspose:_m,ctransposeDependencies:A0,cube:hC,cubeDependencies:n$,cumsum:IA,cumsumDependencies:s$,cumsumTransformDependencies:a$,deepEqual:ya,deepEqualDependencies:Io,derivative:c2,derivativeDependencies:o$,det:Jv,detDependencies:g2,deuteronMass:XD,deuteronMassDependencies:u$,diag:Rv,diagDependencies:k2,diff:wD,diffDependencies:l$,diffTransformDependencies:c$,distance:SD,distanceDependencies:h$,divide:cr,divideDependencies:yr,divideScalar:Rt,divideScalarDependencies:$t,docs:OS,dot:Oo,dotDependencies:Ym,dotDivide:ba,dotDivideDependencies:$o,dotMultiply:XC,dotMultiplyDependencies:f$,dotPow:YD,dotPowDependencies:d$,e:Av,eDependencies:P2,efimovFactor:XN,efimovFactorDependencies:p$,eigs:s0,eigsDependencies:I2,electricConstant:JD,electricConstantDependencies:m$,electronMass:AA,electronMassDependencies:g$,elementaryCharge:ZD,elementaryChargeDependencies:v$,equal:Rr,equalDependencies:Jr,equalScalar:nt,equalScalarDependencies:ot,equalText:lD,equalTextDependencies:y$,erf:fC,erfDependencies:b$,evaluate:jm,evaluateDependencies:P0,exp:Ov,expDependencies:$2,expm:QD,expm1:dC,expm1Dependencies:w$,expmDependencies:x$,factorial:xa,factorialDependencies:Ro,factory:R,falseDependencies:S$,faraday:KD,faradayDependencies:N$,fermiCoupling:$A,fermiCouplingDependencies:C$,fft:t0,fftDependencies:U2,filter:pC,filterDependencies:D$,filterTransformDependencies:A$,fineStructure:zN,fineStructureDependencies:E$,firstRadiation:EA,firstRadiationDependencies:M$,fix:Zv,fixDependencies:m2,flatten:zn,flattenDependencies:Es,floor:qv,floorDependencies:p2,forEach:mC,forEachDependencies:T$,forEachTransformDependencies:F$,format:ma,formatDependencies:zo,fraction:va,fractionDependencies:Po,freqz:YA,freqzDependencies:_$,gamma:$m,gammaDependencies:S0,gasConstant:qA,gasConstantDependencies:O$,gcd:cD,gcdDependencies:B$,getMatrixDataType:Am,getMatrixDataTypeDependencies:N0,gravitationConstant:eA,gravitationConstantDependencies:k$,gravity:MA,gravityDependencies:P$,hartreeEnergy:tA,hartreeEnergyDependencies:z$,hasNumericValue:hD,hasNumericValueDependencies:R$,help:h2,helpDependencies:L$,hex:gC,hexDependencies:I$,hypot:fD,hypotDependencies:$$,i:Ev,iDependencies:q2,identity:un,identityDependencies:Un,ifft:rA,ifftDependencies:q$,im:Em,imDependencies:F0,index:jv,indexDependencies:j2,indexTransformDependencies:H$,intersect:TA,intersectDependencies:V$,inv:qn,invDependencies:Ns,inverseConductanceQuantum:iA,inverseConductanceQuantumDependencies:W$,invmod:ND,invmodDependencies:j$,isAccessorNode:en,isArray:St,isArrayNode:Vr,isAssignmentNode:vg,isBigInt:ts,isBigNumber:Xe,isBlockNode:yg,isBoolean:hg,isChain:au,isCollection:Or,isComplex:ci,isConditionalNode:bg,isConstantNode:ct,isDate:dg,isDenseMatrix:Vs,isFraction:vn,isFunction:su,isFunctionAssignmentNode:rs,isFunctionNode:qi,isHelp:nu,isIndex:Ws,isIndexNode:xn,isInteger:Pr,isIntegerDependencies:Xr,isMap:bn,isMatrix:Re,isNaN:Gi,isNaNDependencies:pn,isNegative:on,isNegativeDependencies:Vn,isNode:bt,isNull:mg,isNumber:Je,isNumeric:In,isNumericDependencies:ws,isObject:yn,isObjectNode:js,isObjectWrappingMap:Cy,isOperatorNode:qt,isParenthesisNode:Ai,isPartitionedMap:Ny,isPositive:Rn,isPositiveDependencies:Cs,isPrime:PC,isPrimeDependencies:G$,isRange:Ia,isRangeNode:wg,isRegExp:pg,isRelationalNode:Sg,isResultSet:fg,isSparseMatrix:Ki,isString:nr,isSymbolNode:Xt,isUndefined:gg,isUnit:br,isZero:ti,isZeroDependencies:wi,kldivergence:HA,kldivergenceDependencies:X$,klitzing:nA,klitzingDependencies:Y$,kron:YC,kronDependencies:J$,larger:Ar,largerDependencies:Ir,largerEq:Fo,largerEqDependencies:Zm,lcm:CD,lcmDependencies:t6,leafCount:o2,leafCountDependencies:r6,leftShift:JC,leftShiftDependencies:i6,lgamma:yC,lgammaDependencies:n6,log:Om,log10:bC,log10Dependencies:s6,log1p:DD,log1pDependencies:a6,log2:Mm,log2Dependencies:z0,logDependencies:L0,loschmidt:sA,loschmidtDependencies:o6,lsolve:Uv,lsolveAll:AD,lsolveAllDependencies:u6,lsolveDependencies:Y2,lup:r0,lupDependencies:Z2,lusolve:a0,lusolveDependencies:K2,lyap:t2,lyapDependencies:l6,mad:JA,madDependencies:c6,magneticConstant:aA,magneticConstantDependencies:h6,magneticFluxQuantum:FA,magneticFluxQuantumDependencies:f6,map:Ln,mapDependencies:Ms,mapSlices:fs,mapSlicesDependencies:qo,mapSlicesTransformDependencies:d6,mapTransformDependencies:p6,matrix:we,matrixDependencies:Ne,matrixFromColumns:Bm,matrixFromColumnsDependencies:_0,matrixFromFunction:zC,matrixFromFunctionDependencies:m6,matrixFromRows:ED,matrixFromRowsDependencies:g6,max:km,maxDependencies:$0,maxTransformDependencies:v6,mean:o0,meanDependencies:F2,meanTransformDependencies:y6,median:u0,medianDependencies:rE,min:dD,minDependencies:b6,minTransformDependencies:x6,mod:Vv,modDependencies:G2,mode:ZC,modeDependencies:w6,molarMass:oA,molarMassC12:_A,molarMassC12Dependencies:N6,molarMassDependencies:S6,molarPlanckConstant:uA,molarPlanckConstantDependencies:C6,molarVolume:UA,molarVolumeDependencies:D6,multinomial:OA,multinomialDependencies:A6,multiply:xt,multiplyDependencies:Nt,multiplyScalar:Ht,multiplyScalarDependencies:jt,neutronMass:lA,neutronMassDependencies:M6,norm:Hm,normDependencies:I0,not:Mo,notDependencies:Xm,nthRoot:QC,nthRootDependencies:T6,nthRoots:pD,nthRootsDependencies:F6,nuclearMagneton:cA,nuclearMagnetonDependencies:_6,nullDependencies:O6,nullish:mD,nullishDependencies:B6,nullishTransformDependencies:k6,number:ji,numberDependencies:fn,numeric:ii,numericDependencies:xi,oct:xC,octDependencies:P6,ones:RC,onesDependencies:z6,or:gD,orDependencies:R6,orTransformDependencies:L6,parse:bi,parseDependencies:Pi,parser:u2,parserDependencies:I6,partitionSelect:_o,partitionSelectDependencies:tg,permutations:BA,permutationsDependencies:$6,phi:HN,phiDependencies:q6,pi:Cm,piDependencies:q0,pickRandom:wC,pickRandomDependencies:H6,pinv:RD,pinvDependencies:U6,planckCharge:hA,planckChargeDependencies:V6,planckConstant:VA,planckConstantDependencies:W6,planckLength:fA,planckLengthDependencies:j6,planckMass:kA,planckMassDependencies:G6,planckTemperature:dA,planckTemperatureDependencies:X6,planckTime:KA,planckTimeDependencies:Y6,polynomialRoot:PA,polynomialRootDependencies:J6,pow:yi,powDependencies:ki,print:SC,printDependencies:Z6,printTransformDependencies:Q6,prod:Lv,prodDependencies:_2,protonMass:pA,protonMassDependencies:K6,qr:Pm,qrDependencies:O0,quantileSeq:WA,quantileSeqDependencies:e7,quantileSeqTransformDependencies:t7,quantumOfCirculation:mA,quantumOfCirculationDependencies:r7,random:NC,randomDependencies:i7,randomInt:LC,randomIntDependencies:n7,range:ms,rangeDependencies:Aa,rangeTransformDependencies:a7,rationalize:l2,rationalizeDependencies:o7,re:Tm,reDependencies:B0,reducedPlanckConstant:gA,reducedPlanckConstantDependencies:u7,replacer:Fv,replacerDependencies:O2,reshape:Pv,reshapeDependencies:R2,resize:KC,resizeDependencies:l7,resolve:y0,resolveDependencies:B2,reviver:i2,reviverDependencies:c7,rightArithShift:eD,rightArithShiftDependencies:h7,rightLogShift:vD,rightLogShiftDependencies:f7,rotate:e2,rotateDependencies:d7,rotationMatrix:l0,rotationMatrixDependencies:nE,round:ds,roundDependencies:Ca,row:MD,rowDependencies:p7,rowTransformDependencies:m7,rydberg:vA,rydbergDependencies:g7,sackurTetrode:WN,sackurTetrodeDependencies:b7,schur:c0,schurDependencies:eE,sec:CC,secDependencies:x7,sech:IC,sechDependencies:w7,secondRadiation:yA,secondRadiationDependencies:S7,setCartesian:TD,setCartesianDependencies:N7,setDifference:Qv,setDifferenceDependencies:sE,setDistinct:FD,setDistinctDependencies:C7,setIntersect:i0,setIntersectDependencies:aE,setIsSubset:_D,setIsSubsetDependencies:D7,setMultiplicity:LD,setMultiplicityDependencies:A7,setPowerset:OD,setPowersetDependencies:E7,setSize:bA,setSizeDependencies:M7,setSymDifference:Kv,setSymDifferenceDependencies:oE,setUnion:jA,setUnionDependencies:T7,sign:Bv,signDependencies:z2,simplify:ko,simplifyConstant:Vm,simplifyConstantDependencies:M0,simplifyCore:Wm,simplifyCoreDependencies:T0,simplifyDependencies:Km,sin:To,sinDependencies:eg,sinh:$C,sinhDependencies:F7,size:Qt,sizeDependencies:ir,slu:Gv,sluDependencies:Q2,smaller:Dr,smallerDependencies:$r,smallerEq:ps,smallerEqDependencies:Da,solveODE:zA,solveODEDependencies:_7,sort:BD,sortDependencies:O7,sparse:qC,sparseDependencies:B7,speedOfLight:xA,speedOfLightDependencies:k7,splitUnit:DC,splitUnitDependencies:P7,sqrt:vi,sqrtDependencies:zi,sqrtm:ID,sqrtmDependencies:z7,square:AC,squareDependencies:R7,squeeze:HC,squeezeDependencies:L7,std:ZA,stdDependencies:I7,stdTransformDependencies:$7,stefanBoltzmann:wA,stefanBoltzmannDependencies:q7,stirlingS2:n0,stirlingS2Dependencies:y2,string:EC,stringDependencies:H7,subset:Gr,subsetDependencies:ni,subsetTransformDependencies:U7,subtract:Wt,subtractDependencies:Gt,subtractScalar:ri,subtractScalarDependencies:Si,sum:Im,sumDependencies:C0,sumTransformDependencies:V7,sylvester:h0,sylvesterDependencies:tE,symbolicEqual:a2,symbolicEqualDependencies:W7,tan:MC,tanDependencies:j7,tanh:UC,tanhDependencies:G7,tau:Tv,tauDependencies:H2,thomsonCrossSection:SA,thomsonCrossSectionDependencies:X7,to:tD,toBest:kv,toBestDependencies:v2,toDependencies:Y7,trace:yD,traceDependencies:J7,transpose:ga,transposeDependencies:Lo,trueDependencies:Z7,typeOf:Fm,typeOfDependencies:R0,typed:j,typedDependencies:G,unaryMinus:Oi,unaryMinusDependencies:Yi,unaryPlus:Rm,unaryPlusDependencies:E0,unequal:rD,unequalDependencies:Q7,unit:RA,unitDependencies:K7,usolve:zm,usolveAll:Xv,usolveAllDependencies:L2,usolveDependencies:k0,vacuumImpedance:$D,vacuumImpedanceDependencies:rq,variance:qm,varianceDependencies:H0,varianceTransformDependencies:iq,version:GN,versionDependencies:nq,weakMixingAngle:ZN,weakMixingAngleDependencies:sq,wienDisplacement:qD,wienDisplacementDependencies:aq,xgcd:zv,xgcdDependencies:X2,xor:iD,xorDependencies:oq,zeros:lr,zerosDependencies:vr,zeta:QA,zetaDependencies:uq,zpk2tf:kD,zpk2tfDependencies:lq},Symbol.toStringTag,{value:"Module"}));var Fe={lightGray:"#EEEEEE",mediumGray:"#DDDDDD",darkGray:"#AAAAAA",hiliteColor:"#FF69B4",stepColor:"#9FDAFF",explainColor:"#FFD9B3",red:"#DB2323",green:"#6FDE29",blue:"#2386DB",white:"#FFFFFF"};class Ri{constructor(){this.name="",this.xpos=0,this.scale=1,this.rotation=0,this.ypos=0,this.width=0,this.height=0,this.opacity=1,this.visible=!0,this.svgObject=null,this.childList=[],this.parent=null}setName(e){this.name=e}setPosition(e,t){this.xpos=e,this.ypos=t,this.updateTransform()}setScale(e){this.scale=e,this.updateTransform()}setRotation(e){this.rotation=e,this.updateTransform()}updateTransform(){const e=isNaN(this.xpos)?0:this.xpos,t=isNaN(this.ypos)?0:this.ypos;var r=" translate("+e.toString()+","+t.toString()+") ";this.scale!=1&&(r+=" scale("+this.scale.toString()+")"),this.rotation!=0&&(r+=" rotate("+this.rotation+")"),this.svgObject.setAttribute("transform",r)}setWidth(e){this.width=e,this.svgObject.setAttribute("width",this.width.toString())}setHeight(e){this.height=e,this.svgObject.setAttribute("height",this.height.toString())}setWidthAndHeight(e,t){this.setWidth(e),this.setHeight(t)}setFillColor(e){this.svgObject.setAttribute("fill",e)}setStrokeColor(e){this.svgObject.setAttribute("stroke",e)}setStrokeWidth(e){this.svgObject.setAttribute("stroke-width",e.toString())}setOpacity(e){this.opacity=e,this.svgObject.style.opacity=e}setDropShadow(){this.svgObject.style.filter="drop-shadow(0px 3px 6px rgba(0, 0, 0, 0.4))"}show(){this.visible=!0,this.svgObject.style.display=""}hide(){this.visible=!1,this.svgObject.style.display="none"}update(){if(this.visible)for(var e of this.childList)e.update()}addChild(e){this.svgObject&&e.svgObject&&(this.childList.push(e),this.svgObject.appendChild(e.svgObject),e.parent=this)}getChild(e){return this.childList[e]}replaceChild(e,t){this.svgObject.replaceChild(e.svgObject,t.svgObject);for(var r=0;r<this.childList.length;r++)if(this.childList[r]==t){this.childList[r]=e;break}t.parent=null,e.parent=this}getNumberOfChildren(){return this.childList.length}removeChild(e){const t=this.childList.indexOf(e);this.removeChildByIndex(t),e.parent=null}removeChildByIndex(e){if(e>=0){var t=this.childList[e];this.childList.splice(e,1),this.svgObject.removeChild(t.svgObject),t.parent=null}}removeAllChildren(){for(;this.svgObject.firstChild;)this.svgObject.removeChild(this.svgObject.lastChild);this.childList=[]}sortChildren(e){this.childList.sort(e),this.childList.forEach(t=>this.svgObject.appendChild(t.svgObject))}setClickCallback(e){if(this.svgObject){var t=this;this.svgObject.onclick=function(){e(t)},this.svgObject.style.cursor="pointer"}}enableDragging(){this.svgObject.style.cursor="pointer";var e=this;this.svgObject.onmousedown=function(t){e.lastX=t.clientX,e.lastY=t.clientY,window.onmousemove=function(r){var i=r.clientX-e.lastX,s=r.clientY-e.lastY;e.lastX=r.clientX,e.lastY=r.clientY,e.setPosition(e.xpos+i,e.ypos+s)},window.onmouseup=function(){window.onmousemove=null}}}}class j0 extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"svg"),this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("width","500"),this.svgObject.setAttribute("height","500"),this.svgObject.setAttribute("backgroundColor","blue")}setViewbox(e,t){this.setWidth(e),this.setHeight(t);var r="0 0 "+e.toString()+" "+t.toString();this.svgObject.setAttribute("viewBox",r)}}let Oe=class extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"g"),this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("width","500"),this.svgObject.setAttribute("height","500"),this.svgObject.setAttribute("viewBox","0 0 500 500")}},Ut=class extends Ri{constructor(){super(),this.x1=0,this.y1=0,this.x2=100,this.y2=100;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"line"),this.svgObject.setAttribute("x1","0"),this.svgObject.setAttribute("y1","0"),this.svgObject.setAttribute("x2","100"),this.svgObject.setAttribute("y2","100"),this.setStrokeColor("black"),this.setStrokeWidth(1),this.setEndpointA(this.x1,this.y1),this.setEndpointB(this.x2,this.y2)}setEndpointA(e,t){this.x1=e,this.y1=t,this.svgObject.setAttribute("x1",e.toString()),this.svgObject.setAttribute("y1",t.toString())}setEndpointB(e,t){this.x2=e,this.y2=t,this.svgObject.setAttribute("x2",e.toString()),this.svgObject.setAttribute("y2",t.toString())}setEndpoints(e,t,r,i){this.setEndpointA(e,t),this.setEndpointB(r,i)}};class yt extends Ri{constructor(){super(),this.cornerRadius=0;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"rect"),this.setWidthAndHeight(100,100),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}setCornerRadius(e){this.cornerRadius=e,this.svgObject.setAttribute("rx",e.toString()),this.svgObject.setAttribute("ry",e.toString())}}let Tr=class extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"ellipse"),this.setPosition(0,0),this.setWidthAndHeight(100,100),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}setWidth(e){this.width=e,this.svgObject.setAttribute("rx",(this.width/2).toString())}setHeight(e){this.height=e,this.svgObject.setAttribute("ry",(this.height/2).toString())}setPosition(e,t){this.xpos=e,this.ypos=t,this.svgObject.setAttribute("cx",e.toString()),this.svgObject.setAttribute("cy",t.toString()),this.svgObject.setAttribute("transform","")}updateTransform(){var e="";this.scale!=1&&(e+=" scale("+this.scale.toString()+")"),this.rotation!=0&&(e+=" rotate("+this.rotation+")"),this.svgObject.setAttribute("transform",e.trim())}};class lE extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"path"),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}createPieSlice(e,t,r){function i(u,c){const h=(c-90)*Math.PI/180;return{x:u*Math.cos(h),y:u*Math.sin(h)}}const s=i(e,r),a=i(e,t),o=r-t<=180?"0":"1",l=["M 0 0",`L ${s.x} ${s.y}`,`A ${e} ${e} 0 ${o} 0 ${a.x} ${a.y}`,"Z"].join(" ");this.svgObject.setAttribute("d",l)}}class Ni extends Ri{constructor(){super(),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.setAttribute("fill","none"),this.path.setAttribute("stroke","black"),this.path.setAttribute("stroke-width","2"),this.svgObject=this.path,this.points=[],this.updatePath()}addPoint(e,t){if(typeof e!="number"||typeof t!="number")throw new Error("Coordinates must be numbers.");this.points.push({x:e,y:t})}updatePath(){if(this.points.length===0){this.path.setAttribute("d","");return}const t=this.points.map((r,i)=>i===0?`M ${r.x},${r.y}`:`L ${r.x},${r.y}`).join(" ");this.path.setAttribute("d",t)}clearPoints(){this.points=[],this.updatePath()}}class Ho extends Ri{constructor(e=300,t=300,r=10){super();const i="http://www.w3.org/2000/svg",s=document.createElementNS(i,"g");this.svgObject=s,this.width=e,this.height=t,this.cornerRadius=r,this.maskID="clipMaskID"+Math.random(),s.setAttribute("width",this.width),s.setAttribute("height",this.height),s.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);const a=document.createElementNS(i,"clipPath");a.setAttribute("id",this.maskID),this.clipRect=document.createElementNS(i,"rect"),this.clipRect.setAttribute("x",0),this.clipRect.setAttribute("y",0),this.clipRect.setAttribute("width",this.width),this.clipRect.setAttribute("height",this.height),this.clipRect.setAttribute("rx",this.cornerRadius),this.clipRect.setAttribute("ry",this.cornerRadius),a.appendChild(this.clipRect),s.appendChild(a),this.clipGroup=new Oe,this.clipGroup.svgObject.setAttribute("clip-path",`url(#${this.maskID})`),super.addChild(this.clipGroup)}setWidth(e){this.width=e,this.svgObject.setAttribute("width",this.width),this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.clipRect.setAttribute("width",this.width)}setHeight(e){this.height=e,this.svgObject.setAttribute("height",this.height),this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.clipRect.setAttribute("height",this.height)}setCornerRadius(e){this.cornerRadius=e,this.clipRect.setAttribute("rx",this.cornerRadius),this.clipRect.setAttribute("ry",this.cornerRadius)}addChild(e){this.clipGroup.addChild(e)}}class cE extends Ri{constructor(){super(),this.preserveAspectRatio=!0;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"image"),this.setWidthAndHeight(100,100)}setImageURL(e){this.svgObject.setAttribute("href",e),this.imageURL=e}setAspectRatio(e){this.svgObject.setAttribute("preserveAspectRatio",e)}applyRoundedCorners(e,t=0){this.svgObject&&this.svgObject.remove();const r="http://www.w3.org/2000/svg",i=document.createElementNS(r,"g");this.svgObject=i,i.setAttribute("width",this.width),i.setAttribute("height",this.height),i.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);const s=document.createElementNS(r,"clipPath");s.setAttribute("id","rounded-corners");const a=document.createElementNS(r,"rect");a.setAttribute("x",0),a.setAttribute("y",0),a.setAttribute("width",this.width),a.setAttribute("height",this.height),a.setAttribute("rx",e),a.setAttribute("ry",e),s.appendChild(a),i.appendChild(s);const o=document.createElementNS(r,"image");o.setAttribute("href",this.imageURL),o.setAttribute("width",this.width),o.setAttribute("height",this.height),o.setAttribute("clip-path","url(#rounded-corners)"),t&&o.setAttribute("preserveAspectRatio",t),i.appendChild(o)}}let si=class extends Ri{constructor(){super(),this.text="";const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"text"),this.svgObject.textContent="hello world",this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("fill","black"),this.svgObject.style.fontFamily="Arial, Helvetica, sans-serif;"}setText(e){this.text=e,this.svgObject.textContent=e}getText(){return this.text}setFontSize(e){this.svgObject.style.fontSize=e.toString()+"px"}setFontFamily(e){this.svgObject.style.fontFamily=e}setFontColor(e){this.svgObject.style.fill=e}setTextAnchor(e){this.svgObject.setAttribute("text-anchor",e)}setAlignment(e){this.alignment=e,e=="left"&&this.setTextAnchor("start"),e=="center"&&this.setTextAnchor("middle"),e=="right"&&this.setTextAnchor("end")}setFontWeight(e){this.svgObject.style.fontWeight=e.toString()}},Bt=class extends Oe{constructor(e={}){super(),this.text="",this._useForeignObject=e.useForeignObject===!0,this._textAlign="left",this._verticalCenter=!1,this._lineHeight=null,this._fontSize=16,this._fontFamily="Arial, Helvetica, sans-serif",this._fontWeight="normal",this._fontColor="black";const t="http://www.w3.org/2000/svg";this._useForeignObject?(this.foreignObject=document.createElementNS(t,"foreignObject"),this.foreignObject.style.backgroundColor="none",this.svgObject.appendChild(this.foreignObject),this.div=document.createElement("div"),this.foreignObject.appendChild(this.div)):(this.textElement=document.createElementNS(t,"text"),this.textElement.setAttribute("x","0"),this.textElement.setAttribute("y","0"),this.textElement.setAttribute("fill",this._fontColor),this.textElement.setAttribute("xml:space","preserve"),this.textElement.style.fontFamily=this._fontFamily,this.textElement.style.fontSize=this._fontSize.toString()+"px",this.svgObject.appendChild(this.textElement)),this.setWidthAndHeight(200,100)}_getLineHeight(){return this._lineHeight||this._fontSize}_getTextX(){return this._textAlign==="center"?this.width/2:this._textAlign==="right"||this._textAlign==="end"?this.width:0}_applyTextAnchor(){this.textElement&&(this._textAlign==="center"?this.textElement.setAttribute("text-anchor","middle"):this._textAlign==="right"||this._textAlign==="end"?this.textElement.setAttribute("text-anchor","end"):this.textElement.setAttribute("text-anchor","start"))}_parseHtmlToLines(e){if(!/<\s*(sup|sub|br)\b/i.test(e||""))return[[{text:e||"",mode:null}]];const r=document.createElement("div");r.innerHTML=e||"";const i=[[]],s=(a,o)=>{if(a.nodeType===3){const c=a.nodeValue||"";c.length>0&&i[i.length-1].push({text:c,mode:o});return}if(a.nodeType!==1)return;const l=a.tagName.toLowerCase();if(l==="br"){i.push([]);return}let u=o;l==="sup"&&(u="sup"),l==="sub"&&(u="sub");for(let c=0;c<a.childNodes.length;c++)s(a.childNodes[c],u)};for(let a=0;a<r.childNodes.length;a++)s(r.childNodes[a],null);return i.length>1&&i[i.length-1].length===0&&i.pop(),i}_renderSvgText(e){if(!this.textElement)return;const t="http://www.w3.org/2000/svg",r=this._parseHtmlToLines(e),i=this._getLineHeight(),s=i*r.length,a=this._verticalCenter?Math.max(0,(this.height-s)/2):0,o=this._getTextX();for(;this.textElement.firstChild;)this.textElement.removeChild(this.textElement.firstChild);this._applyTextAnchor(),this.textElement.setAttribute("dominant-baseline","hanging");for(let l=0;l<r.length;l++){const u=r[l];u.length===0&&u.push({text:"",mode:null});for(let c=0;c<u.length;c++){const h=u[c],f=document.createElementNS(t,"tspan");f.textContent=h.text,h.mode==="sup"?(f.setAttribute("baseline-shift","super"),f.setAttribute("font-size","0.7em")):h.mode==="sub"&&(f.setAttribute("baseline-shift","sub"),f.setAttribute("font-size","0.7em")),c===0&&(f.setAttribute("x",o),l===0?f.setAttribute("y",a):f.setAttribute("dy",i)),this.textElement.appendChild(f)}}}_updateSvgLayout(){this.textElement&&this._renderSvgText(this.text)}setText(e){this.text=e||"",this._useForeignObject?this.div.innerHTML=this.text:this._renderSvgText(this.text)}getText(){return this.text}setStyle(e){this._useForeignObject?(this.div.className=e,this.div.style.position="fixed"):this.textElement&&this.textElement.setAttribute("class",e)}setFontFamily(e){this._fontFamily=e,this._useForeignObject?this.div.style.fontFamily=e:this.textElement&&(this.textElement.style.fontFamily=e)}setFontSize(e){this._fontSize=e,this._useForeignObject?this.div.style.fontSize=e.toString()+"px":this.textElement&&(this.textElement.style.fontSize=e.toString()+"px",this._updateSvgLayout())}setLineHeight(e){this._lineHeight=e,this._useForeignObject?this.div.style.lineHeight=e+"px":this._updateSvgLayout()}setFontWeight(e){this._fontWeight=e,this._useForeignObject?this.div.style.fontWeight=e:this.textElement&&(this.textElement.style.fontWeight=e)}setFontColor(e){this._fontColor=e,this._useForeignObject?this.div.style.color=e:this.textElement&&this.textElement.setAttribute("fill",e)}setAlignment(e){this._textAlign=e,this._useForeignObject?this.div.style.textAlign=e:this._updateSvgLayout()}setVerticalCentering(){this._useForeignObject?(this.div.style.display="flex",this.div.style.flexFlow="column",this.div.style.justifyContent="center",this.div.style.alignItems="center"):(this._verticalCenter=!0,this._updateSvgLayout())}makeEditable(){this._useForeignObject&&(this.div.style.contentEditable="true",this.div.onclick=function(){console.log("here"),this.focus()})}setBorderWidthAndColor(e,t){this._useForeignObject&&(this.div.style.border=e+"px solid "+t)}setWidth(e){this.width=e,this._useForeignObject?(this.div&&(this.div.style.width=e+"px"),this.foreignObject&&this.foreignObject.setAttribute("width",e)):this._updateSvgLayout()}setHeight(e){this.height=e,this._useForeignObject?(this.div&&(this.div.style.height=e+"px"),this.foreignObject&&this.foreignObject.setAttribute("height",e)):this._updateSvgLayout()}};class hE extends Bt{constructor(){super({useForeignObject:!0}),this.callback=null,this.foreignObject.removeChild(this.div),this.div=document.createElement("input"),this.div.contentEditable=!0,this.div.onkeyup=this.handleInput.bind(this),this.foreignObject.appendChild(this.div),this.setWidthAndHeight(200,30),this.setPlaceholderText("placeholder")}setStyle(e){this.div.className=e}setPlaceholderText(e){this.div.placeholder=e}setText(e){this.div.value=e}getText(){return this.div.value}setInputCallback(e){this.callback=e}handleInput(e){(e.key=="Enter"||e.keyCode==13)&&this.callback&&this.callback(this.div.value)}}let fE=class extends Bt{constructor(){super({useForeignObject:!0}),this.callback=null,this.foreignObject.removeChild(this.div),this.div=document.createElement("textarea"),this.div.onkeyup=this.handleInput.bind(this),this.foreignObject.appendChild(this.div),this.setWidthAndHeight(200,30),this.setPlaceholderText("placeholder")}setText(e){this.div.value=e}getText(){return this.div.value}setStyle(e){this.div.className=e}handleInput(e){this.callback&&this.callback(this)}setPlaceholderText(e){this.div.placeholder=e}setInputCallback(e){this.callback=e}},Xn=class extends Oe{constructor(){super(),this.callback=null,this.fontSize=12,this.text="button",this.backRect=new yt,this.backRect.setWidthAndHeight(100,30),this.backRect.setFillColor("white"),this.backRect.setStrokeWidth(0),this.backRect.setCornerRadius(15),this.backRect.svgObject.style.cursor="pointer",this.addChild(this.backRect),this.buttonText=new si,this.buttonText.setPosition(50,20),this.buttonText.setFontFamily("Arial"),this.buttonText.setFontSize(12),this.buttonText.setText("button"),this.buttonText.setTextAnchor("middle"),this.buttonText.svgObject.style.cursor="pointer",this.addChild(this.buttonText)}setText(e){this.text=e,this.buttonText.setText(e)}setFontFamily(e){this.buttonText.setFontFamily(e)}setFontSize(e){this.fontSize=e,this.buttonText.setFontSize(e)}setFontColor(e){this.buttonText.setFontColor(e)}setFillColor(e){this.backRect.setFillColor(e)}setStrokeColor(e){this.backRect.setStrokeColor(e)}setStrokeWidth(e){this.backRect.setStrokeWidth(e)}setCornerRadius(e){this.backRect.setCornerRadius(e)}addImage(e,t=30,r=30){this.image=new cE,this.image.setImageURL(e),this.image.setWidthAndHeight(t,r),this.image.setPosition(this.backRect.width/2-t/2,this.backRect.height/2-r/2),this.image.svgObject.style.cursor="pointer",this.addChild(this.image)}setWidthAndHeight(e,t){this.width=e,this.height=t,this.backRect.setWidthAndHeight(e,t),this.buttonText.setPosition(e/2,t*.5+2+this.fontSize*.25),this.image&&this.image.setPosition(this.backRect.width/2-this.image.width/2,this.backRect.height/2-this.image.height/2)}};class qr extends Oe{constructor(){super(),this.spacer=10}setSpacer(e){this.spacer=e}updateLayout(){}showAll(){for(var e=this.getNumberOfChildren(),t=0;t<e;t++){var r=this.getChild(t);r.show()}}showOnly(e){for(var t=this.getNumberOfChildren(),r=0;r<t;r++){var i=this.getChild(r);r==e?i.show():i.hide()}}doVerticalLayout(){for(var e=this.getNumberOfChildren(),t=0,r=0,i=0,s=0;s<e;s++){var a=this.getChild(s);a.visible&&(a.setPosition(t,r),r+=a.height,r+=this.spacer,a.width>i&&(i=a.width))}this.height=r-this.spacer,this.width=i;for(var s=0;s<e;s++){var a=this.getChild(s),t=this.width/2-a.width/2;a.setPosition(t,a.ypos)}}doHorizontalLayout(){for(var e=this.getNumberOfChildren(),t=0,r=0,i=0,s=0;s<e;s++){var a=this.getChild(s);a.visible&&(a.setPosition(t,r),t+=a.width,t+=this.spacer,a.height>i&&(i=a.height))}this.width=t-this.spacer,this.height=i;for(var s=0;s<e;s++){var a=this.getChild(s),r=this.height/2-a.height/2;a.setPosition(a.xpos,r)}}}class mq extends Oe{constructor(){super(),this.scrollPercent=0,this.scrollOffset=0,this.contentHeight=0,this.oldMouseX=0,this.oldMouseY=0,this.clipMask=new Ho(200,400,10),super.addChild(this.clipMask),this.backRect=new yt,this.backRect.setFillColor("white"),this.clipMask.addChild(this.backRect),this.scrollGroup=new Oe,this.clipMask.addChild(this.scrollGroup),this.scrollBar=new yt,this.scrollBar.setWidthAndHeight(10,50),this.scrollBar.setCornerRadius(5),this.scrollBar.setFillColor("darkgray"),this.scrollBar.setPosition(180,10),this.scrollBar.svgObject.onmousedown=this.handleMouseDown.bind(this),this.scrollBar.svgObject.style.cursor="pointer",this.clipMask.addChild(this.scrollBar),this.setWidthAndHeight(200,500),this.updateLayout()}setWidth(e){super.setWidth(e),this.clipMask.setWidth(e),this.backRect.setWidth(e)}setHeight(e){super.setWidth(e),this.clipMask.setHeight(e),this.backRect.setHeight(e)}setCornerRadius(e){this.clipMask.setCornerRadius(e)}addChild(e){this.scrollGroup.addChild(e)}handleMouseDown(e){if(!this.visible)return;function t(i){i.preventDefault();var s,a;if(i.touches&&i.touches.length>=1?(s=i.touches[0].clientX,a=i.touches[0].clientY):(s=i.clientX,a=i.clientY),this.oldMouseX&&this.oldMouseY){s-this.oldMouseX;var o=a-this.oldMouseY,l=this.scrollBar.ypos+o,u=10,c=this.backRect.height-this.scrollBar.height-10;l<u&&(l=u),l>c&&(l=c),this.scrollBar.setPosition(this.scrollBar.xpos,l),this.scrollPercent=(l-u)/(c-u),this.updateLayout()}this.oldMouseX=s,this.oldMouseY=a}function r(i){this.activeBubble=null,window.onmousemove=null,window.ontouchmove=null,window.onmouseup=null,window.ontouchend=null,this.oldMouseX=0,this.oldMouseY=0}window.onmousemove=t.bind(this),window.ontouchmove=t.bind(this),window.onmouseup=r.bind(this),window.ontouchend=r.bind(this)}computeContentBounds(){for(var e=0,t=this.scrollGroup.getNumberOfChildren(),r=0;r<t;r++){var i=this.scrollGroup.getChild(r),s=i.ypos+i.height;s>e&&(e=s)}this.contentHeight=e}updateLayout(){if(this.backRect.width,this.backRect.height,this.computeContentBounds(),this.contentHeight>this.backRect.height){var e=this.contentHeight-this.backRect.height,t=-1*this.scrollPercent*e;this.scrollGroup.setPosition(0,t)}}}class kt extends Oe{constructor(e=1){super(),this.type="",this.value=e,this.defaultOpaqueBack=!0,this.backRect=new yt,this.backRect.setWidthAndHeight(30,30),this.backRect.setCornerRadius(5),this.backRect.setFillColor(this.getBackgroundColor()),this.addChild(this.backRect),this.svgObject.onmouseenter=this.highlightProvenance.bind(this),this.svgObject.onmouseleave=this.clearProvenance.bind(this),this.svgObject.style.cursor="pointer"}setWidthAndHeight(e,t){super.setWidthAndHeight(e,t),this.backRect.setWidthAndHeight(e,t)}setFontSize(e){this.fontSize=e,this.childList&&this.childList.forEach(t=>{t&&typeof t.setFontSize=="function"&&t.setFontSize(e)})}getFontSize(){return this.fontSize?this.fontSize:this.parent&&typeof this.parent.getFontSize=="function"?this.parent.getFontSize():16}getRootFontSize(){return this.parent&&this.parent instanceof kt?this.parent.getRootFontSize():this.fontSize||16}getBackgroundColor(){var e;return((e=this._backgroundStyle)==null?void 0:e.backgroundColor)??Fe.lightGray}highlightProvenance(e,t=Fe.hiliteColor,r=-1/0){e.stopPropagation();const i=this.getRootNode();if(!i||!i.nodeMap)return;i.clearProvenanceHighlights(),this.highlight(t);let s=[...this.provenance];const a=new Set(s);for(;s.length>0;){const o=s.shift(),l=i.nodeMap.get(o);l&&(l.highlight(t),l.provenance&&l.provenance.forEach(u=>{a.has(u)||(a.add(u),s.push(u))}))}}clearProvenance(e){e.stopPropagation();const t=this.getRootNode();t&&t.clearProvenanceHighlights()}highlight(e){this.backRect.setFillColor(e),this.backRect.setOpacity(1),this.childList.forEach(t=>{t instanceof kt&&t.highlight(e)})}clearProvenanceHighlights(){var e;this.isExplainHighlighted?(this.backRect.setFillColor(Fe.explainColor),this.backRect.setOpacity(1)):this.isProvenanceHighlighted?(this.backRect.setFillColor(Fe.explainColor),this.backRect.setOpacity(1)):(this.backRect.setFillColor(((e=this._backgroundStyle)==null?void 0:e.backgroundColor)??Fe.lightGray),this.defaultOpaqueBack||this.backRect.setOpacity(.01)),this.childList.forEach(t=>{t instanceof kt&&typeof t.clearProvenanceHighlights=="function"&&t.clearProvenanceHighlights()})}setExplainHighlight(e=!0,t=Fe.explainColor){this.isExplainHighlighted=e,e?(this.backRect.setFillColor(t),this.backRect.setOpacity(1)):(this.backRect.setFillColor(this.getBackgroundColor()),this.defaultOpaqueBack||this.backRect.setOpacity(.01)),this.argumentNodeList&&Object.values(this.argumentNodeList).forEach(r=>{r&&typeof r.setExplainHighlight=="function"&&r.setExplainHighlight(e,t)})}getRootNode(){let e=this;for(;e.parent&&e.parent instanceof kt;)e=e.parent;return e}findAllNodes(e=[]){return e.push(this),this.childList&&this.childList.forEach(t=>{t.findAllNodes&&t.findAllNodes(e)}),e}select(e){e!==this&&(e instanceof kt||(e=this),this.backRect.setFillColor(Fe.hiliteColor),this.backRect.setOpacity(1),this.childList.forEach(t=>{t instanceof kt&&t.select(e)}),this===e&&this.parent instanceof kt&&e.parent.deselect(e))}deselect(e){e instanceof kt||(e=this),this===e&&this.parent instanceof kt&&e.parent.select(e),!(e===this&&this.parent instanceof kt)&&(this.backRect.setFillColor(this.getBackgroundColor()),this.defaultOpaqueBack==!1&&this.backRect.setOpacity(.01),this.childList.forEach(t=>{t!==e&&t instanceof kt&&t.deselect(e)}))}hideBackgroundByDefault(){this.defaultOpaqueBack=!1,this.backRect.setOpacity(.01)}makeBackgroundLight(){this.backRect.setFillColor(this.getBackgroundColor())}makeBackgroundDark(){this.backRect.setFillColor(Fe.mediumGray)}}let G0=null;function gq(n){G0=n}const ug=class ug extends kt{constructor(e){super(),this.astNodeData=e,this.type="omdNode",this.id=ug.nextId++,this.argumentNodeList={},this.provenance=e&&e.provenance?[...e.provenance]:[],this.isExplainHighlighted=!1,this.parent=null,this.svgElement=null,this.x=0,this.y=0,this.width=0,this.height=0,this.fontSize=32}clone(){const e=JSON.parse(JSON.stringify(this.astNodeData)),t=new this.constructor(e);return t.provenance.push(this.id),t}_syncProvenanceFrom(e){var t;if(e&&(this.provenance.includes(e.id)||this.provenance.push(e.id),e.argumentNodeList&&this.argumentNodeList))for(const r of Object.keys(e.argumentNodeList)){const i=e.argumentNodeList[r],s=this.argumentNodeList[r];if(i&&s)if(Array.isArray(i)&&Array.isArray(s))for(let a=0;a<i.length;a++)(t=s[a])==null||t._syncProvenanceFrom(i[a]);else s._syncProvenanceFrom(i)}}parseValue(){}parseType(){}initialize(){this.computeDimensions(),this.updateLayout()}computeDimensions(){}updateLayout(){}getAlignmentBaseline(){return this.height/2}replaceWith(e,t={updateLayout:!0}){if(!this.parent)return console.error("Cannot replace a node with no parent."),!1;const r=this.parent,i=r.childList.indexOf(this),s=()=>{r.childList[i]=this,e.parent=null,this.parent=r};return i===-1?(console.error("Node not found in parent's childList.",this),!1):(r.childList[i]=e,e.parent=r,this.parent=null,this.replaceNodeInParent(e)?(t.updateLayout&&(this.updateSvg(e),e.updateLayoutUpwards()),!0):(s(),console.error("Failed to replace specific references. Reverting changes."),!1))}replaceNodeInParent(e){const t=e.parent;if(!t||!t.argumentNodeList)return!1;for(const r in t.argumentNodeList){const i=t.argumentNodeList[r];if(i===this)return t.argumentNodeList[r]=e,Object.prototype.hasOwnProperty.call(t,r)&&(t[r]=e),!0;if(Array.isArray(i)&&i.includes(this)){const s=i.indexOf(this);return i[s]=e,t[r]===i&&(t[r][s]=e),!0}}return!1}updateSvg(e){const t=e.parent;if(t&&t.svgObject&&this.svgObject&&e.svgObject)try{t.svgObject.replaceChild(e.svgObject,this.svgObject)}catch(r){console.error("SVG replacement failed, attempting fallback.",r);try{t.svgObject.removeChild(this.svgObject),t.svgObject.appendChild(e.svgObject)}catch(i){console.error("SVG fallback replacement also failed:",i)}}}updateLayoutUpwards(){const e=[];let t=this.parent;for(;t;)e.push(t),t=t.parent;for(const r of e)typeof r.computeDimensions=="function"&&r.computeDimensions();for(let r=e.length-1;r>=0;r--)typeof e[r].updateLayout=="function"&&e[r].updateLayout()}isConstant(){return!1}getValue(){throw new Error("Node is not a constant expression")}getRationalValue(){throw new Error("Node is not a constant rational expression")}simplify(){if(!G0)throw new Error("simplifyStep not set");try{const{foldedCount:e,newRoot:t}=G0(this);return e>0?{success:!0,foldedCount:e,newRoot:t,message:`Simplified! Applied ${e} simplification step(s)`}:{success:!1,foldedCount:0,newRoot:null,message:"No simplifications available"}}catch(e){return{success:!1,foldedCount:0,newRoot:null,message:`Simplification error: ${e.message}`}}}toMathJSNode(){throw new Error(`toMathJSNode() must be implemented by ${this.type}`)}toString(){try{return this.toMathJSNode().toString()}catch{return`[${this.type}]`}}render(){return this.svgElement||(this.svgElement=this.renderSelf()),this.svgElement}renderSelf(){throw new Error(`renderSelf() must be implemented by ${this.type}`)}setFontSize(e){this.fontSize=e,this.childList&&this.childList.forEach(t=>{t&&typeof t.setFontSize=="function"&&t.setFontSize(e)})}moveTo(e,t){const r=e-this.x,i=t-this.y;this.x=e,this.y=t,this.svgElement&&this.svgElement.setAttribute("transform",`translate(${this.x}, ${this.y})`),this.childList&&this.childList.forEach(s=>{s&&typeof s.moveTo=="function"&&s.moveTo(s.x+r,s.y+i)})}show(){this.visible=!0,this.svgElement&&(this.svgElement.style.display="block"),this.svgObject&&(this.svgObject.style.display="block")}hide(){this.visible=!1,this.svgElement&&(this.svgElement.style.display="none"),this.svgObject&&(this.svgObject.style.display="none")}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}findParentOfType(e){let t=this.parent;for(;t;){if(t.type===e||t.type===e)return t;t=t.parent}return null}static fromAST(e){throw new Error("Use omdHelpers.createNodeFromAST() instead")}validateProvenance(e=null){const t=[],r=this.findAllNodes(),i=e?new Set(e.keys()):new Set(r.map(s=>s.id));return r.forEach(s=>{s.provenance&&s.provenance.length>0&&(new Set(s.provenance).size!==s.provenance.length&&t.push({type:"duplicate_provenance",nodeId:s.id,nodeType:s.type,provenance:s.provenance}),s.provenance.forEach(o=>{i.has(o)||t.push({type:"invalid_provenance_reference",nodeId:s.id,nodeType:s.type,invalidId:o})}),s.provenance.includes(s.id)&&t.push({type:"self_reference_provenance",nodeId:s.id,nodeType:s.type}))}),t}setHighlight(e=!0,t=omdColor.highlightColor){this.backRect&&this.backRect.fillColor===omdColor.explainColor||this.isExplainHighlighted||this.backRect&&(this.backRect.setFillColor(e?t:omdColor.lightGray),this.backRect.setOpacity(1))}lowlight(){this.backRect&&this.backRect.fillColor===omdColor.explainColor||this.isExplainHighlighted||super.lowlight()}setFillColor(e){this.isExplainHighlighted}};eu(ug,"nextId",1);let Pt=ug;class Uo extends Pt{constructor(e){super(e),this.type="omdLeafNode"}createTextElement(e){let t=new si;return t.setText(e),t.setTextAnchor("middle"),t.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(t),t}clone(){const e=new this.constructor(this.astNodeData);return e.provenance.push(this.id),e}updateTextElement(e){this.textElement.setText(e)}computeDimensions(){let e=this.getFontSize();this.textElement.setFontSize(e);let t=Jn(this.textElement.getText(),e);this.setWidthAndHeight(t.width,t.height)}updateLayout(){this.updateTextPosition()}updateTextPosition(){this.textElement.setPosition(this.width/2,this.height/2)}}let hr=null,rg=null;const Li={multiplication:{symbol:"·",forceImplicit:!1,implicitCombinations:{constantVariable:!0,variableConstant:!1,parenthesisAfterVariable:!0,parenthesisAfterConstant:!0,variableParenthesis:!0,parenthesisParenthesis:!0,parenthesisVariable:!0,parenthesisConstant:!0,variableVariable:!0}},stepVisualizer:{dotSizes:{level0:8,level1:8,level2:8},fontWeights:{level0:400,level1:400,level2:400}}};async function vq(n=null){return rg&&!n?rg:n&&typeof n=="object"?(hr={...Li,...n},hr):(rg=(async()=>{try{if(typeof window<"u"){const e=n||"./omd/config/omdConfig.json",t=await fetch(e);if(!t.ok)return console.warn(`Config file not found at ${e}, using default configuration`),hr=Li,hr;const r=await t.text(),i=JSON.parse(r);return hr={...Li,...i},hr}else{if(!(typeof process<"u"&&!!(process.versions&&process.versions.node)))return console.warn("Config loading skipped: filesystem APIs unavailable in this environment. Using default configuration."),hr=Li,hr;try{const t=await Promise.resolve().then(()=>vd),r=await Promise.resolve().then(()=>vd),{fileURLToPath:i}=await Promise.resolve().then(()=>vd),s=r.dirname(i(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Lt&&Lt.tagName.toUpperCase()==="SCRIPT"&&Lt.src||new URL("omd.global.js",document.baseURI).href)),a=n||r.join(s,"omdConfig.json");try{const o=await t.readFile(a,"utf-8"),l=JSON.parse(o);hr={...Li,...l}}catch{console.warn(`Config file not found at ${a}, using default configuration`),hr=Li}}catch(t){console.warn("Config loading skipped: unable to access Node filesystem APIs. Using default configuration.",t),hr=Li}return hr}}catch(e){return console.warn("Error loading config, using default configuration:",e),hr=Li,hr}})(),rg)}function ig(){return hr||(hr=Li),hr}async function yq(n=null){await vq(n)}function bq(n){hr={...Li,...n}}function xq(){return{...Li}}function dE(n=null){const e=ig();return n?e.multiplication.implicitCombinations[n]??!1:e.multiplication.forceImplicit}function ai(){return ig().multiplication.symbol}function Ta(n=0){var r,i;const e=ig(),t=`level${n}`;return((i=(r=e.stepVisualizer)==null?void 0:r.dotSizes)==null?void 0:i[t])??6}function wq(n=0){var r,i;const e=ig(),t=`level${n}`;return((i=(r=e.stepVisualizer)==null?void 0:r.fontWeights)==null?void 0:i[t])??400}class ng extends Uo{constructor(e){super(e),this.type="omdOperatorNode",this.opName=this.parseOpName(e);const t=this.opName==="*"?ai():this.opName;this.textElement=super.createTextElement(t)}parseOpName(e){if(typeof e=="string")return e;const t={multiply:ai(),divide:"÷",add:"+",subtract:"−",pow:"^",unaryMinus:"-",unaryPlus:"+"},r=e.op||e.fn;return t[r]||r}parseType(){return"operator"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"OperatorNode",op:this.opName,fn:this.opName,args:[]};return e.clone=function(){const t={...this};return t.argumentNodeList.argument=t.argument,t},e}toString(){return this.opName}highlight(e){super.highlight(e),this.opLabel&&this.opLabel.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.opLabel&&this.opLabel.setFillColor(Fe.text)}}class Zr extends Uo{constructor(e){super(e),this.type="omdConstantNode",this.number=this.parseNumber(e),this.textElement=super.createTextElement(this.number)}parseNumber(e){return typeof e=="number"?e:e.value}parseType(){return"constant"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}isConstant(){return typeof this.number=="number"}getValue(){return this.number}toString(){return this.number.toString()}evaluate(){return this.number}getRationalValue(){return{num:this.getValue(),den:1}}toMathJSNode(){const e={type:"ConstantNode",value:this.number,id:this.id,provenance:this.provenance};return e.clone=function(){return{...this}},e}highlight(e){super.highlight(e),this.textElement&&this.textElement.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.textElement&&this.textElement.setFillColor(Fe.text)}static fromValue(e){const t={type:"ConstantNode",value:e};return new Zr(t)}}class Zi extends Uo{constructor(e){super(e),this.type="omdVariableNode",this.name=this.parseName(e),this.textElement=super.createTextElement(this.name)}parseName(e){return typeof e=="string"?e:e.name}parseType(){return"variable"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"SymbolNode",name:this.name,id:this.id,provenance:this.provenance};return e.clone=function(){return{...this}},e}highlight(e){super.highlight(e),this.textElement&&this.textElement.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.textElement&&this.textElement.setFillColor(Fe.text)}toString(){return this.name}evaluate(e={}){if(Object.prototype.hasOwnProperty.call(e,this.name))return e[this.name];throw new Error(`Variable '${this.name}' is not defined.`)}static fromName(e){const t={type:"SymbolNode",name:e};return new Zi(t)}}function pE(n,e){return e===0?n:pE(e,n%e)}class Hr extends Pt{constructor(e){if(super(e),this.type="omdRationalNode",!e.args||e.args.length<2){console.error("omdRationalNode requires numerator and denominator");return}this.value=this.parseValue(),this.numerator=this.createOperand(e.args[0]),this.denominator=this.createOperand(e.args[1]),this.argumentNodeList.numerator=this.numerator,this.argumentNodeList.denominator=this.denominator,this.fractionLine=new Ut,this.fractionLine.setStrokeColor("black"),this.fractionLine.setStrokeWidth(2),this.addChild(this.fractionLine)}parseValue(){return"/"}createOperand(e){let t=_t(e),r=new t(e);this.addChild(r);try{e.id&&e.provenance&&e.provenance.length>0&&(!r.provenance||r.provenance.length===0)&&(r.provenance=[...e.provenance])}catch(i){console.debug("Failed to preserve lineage in createOperand:",i.message)}return r}computeDimensions(){this.numerator.setFontSize(this.getFontSize()*5/6),this.denominator.setFontSize(this.getFontSize()*5/6),this.numerator.computeDimensions(),this.denominator.computeDimensions();const e=this.getFontSize()/this.getRootFontSize(),t=8*e,r=8*e;let i=Math.max(this.numerator.width,this.denominator.width)+t,s=this.numerator.height+this.denominator.height+r;this.setWidthAndHeight(i,s)}updateLayout(){const t=(this.width-this.numerator.width)/2;this.numerator.updateLayout(),this.numerator.setPosition(t,2);const r=this.numerator.height+2*2;this.fractionLine.setEndpoints(0,r,this.width,r);const i=(this.width-this.denominator.width)/2,s=r+2;this.denominator.updateLayout(),this.denominator.setPosition(i,s)}getAlignmentBaseline(){return this.numerator.height+2*2}isConstant(){return this.numerator.isConstant()&&this.denominator.isConstant()}getRationalValue(){if(this.isConstant())return{num:this.numerator.getValue(),den:this.denominator.getValue()};throw new Error("Rational node is not constant")}getValue(){if(this.isConstant()){const{num:e,den:t}=this.getRationalValue();return t===0?NaN:e/t}throw new Error("Node is not a constant expression")}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Hr(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.numerator=this.numerator.clone(),t.denominator=this.denominator.clone(),t.fractionLine=new Ut,t.fractionLine.setStrokeColor("black"),t.fractionLine.setStrokeWidth(2),t.addChild(t.numerator),t.addChild(t.fractionLine),t.addChild(t.denominator),t.argumentNodeList.numerator=t.numerator,t.argumentNodeList.denominator=t.denominator,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"OperatorNode",op:"/",fn:"divide",args:[this.numerator.toMathJSNode(),this.denominator.toMathJSNode()],id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.numerator.toString(),t=this.denominator.toString(),r=this.numerator.type==="omdBinaryExpressionNode",i=this.denominator.type==="omdBinaryExpressionNode",s=r?`(${e})`:e,a=i?`(${t})`:t;return`${s} / ${a}`}evaluate(e={}){const t=this.numerator.evaluate(e),r=this.denominator.evaluate(e);if(r===0)throw new Error("Division by zero in rational expression.");return t/r}reduce(){if(this.isConstant()){let{num:e,den:t}=this.getRationalValue();t<0&&(e=-e,t=-t);const r=pE(Math.abs(e),Math.abs(t)),i=e/r,s=t/r;if(i===this.numerator.getValue()&&s===this.denominator.getValue())return this;if(s===1)return Zr.fromNumber(i);const a={type:"OperatorNode",op:"/",fn:"divide",args:[Zr.fromNumber(i).toMathJSNode(),Zr.fromNumber(s).toMathJSNode()]};return new Hr(a)}return this.clone()}isProper(){if(this.isConstant()){const{num:e,den:t}=this.getRationalValue();return Math.abs(e)<Math.abs(t)}return null}static fromString(e){try{const t=window.math.parse(e);if(t.type!=="OperatorNode"||t.op!=="/")throw new Error("Expression is not a division operation");return new Hr(t)}catch(t){throw console.error("Failed to create rational node from string:",t),t}}}class Qi extends Pt{constructor(e){if(super(e),this.type="omdUnaryExpressionNode",!e.args||e.args.length!==1){console.error("omdUnaryExpressionNode requires an AST node with exactly 1 argument",e);return}this.op=this.createOperatorNode(e),this.operand=this.createExpressionNode(e.args[0]),this.operation=e.fn||e.op,this.operand=this.operand,this.argument=this.operand,this.argumentNodeList.operand=this.operand,this.argumentNodeList.argument=this.argument,this.addChild(this.op),this.addChild(this.operand)}createOperatorNode(e){const t=new ng({op:e.op,fn:e.fn});return t.parent=this,t}createExpressionNode(e){const t=_t(e),r=new t(e);return r.parent=this,r}computeDimensions(){this.op.computeDimensions(),this.operand.computeDimensions();const e=this.op.width,t=this.operand.width,r=e+t,i=Math.max(this.op.height,this.operand.height);this.setWidthAndHeight(r,i)}updateLayout(){this.op.updateLayout(),this.operand.updateLayout();const e=(this.height-this.op.height)/2,t=(this.height-this.operand.height)/2;this.op.setPosition(0,e),this.operand.setPosition(this.op.width,t)}clone(){const e={type:"OperatorNode",op:"-",args:[{type:"ConstantNode",value:1}]},t=new Qi(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.op=this.op.clone(),t.addChild(t.op),t.operand=this.operand.clone(),t.addChild(t.operand),t.argument=t.operand,t.argumentNodeList={operand:t.operand,argument:t.argument},t.astNodeData=JSON.parse(JSON.stringify(this.astNodeData)),t.provenance.push(this.id),t}isConstant(){return!!(this.operand&&typeof this.operand.isConstant=="function"&&this.operand.isConstant())}getValue(){if(!this.isConstant())throw new Error("Node is not a constant expression");const e=this.operand.getValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?-e:e}getRationalValue(){if(!this.isConstant())throw new Error("Node is not a constant expression");if(typeof this.operand.getRationalValue=="function"){const{num:t,den:r}=this.operand.getRationalValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?{num:-t,den:r}:{num:t,den:r}}const e=this.operand.getValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?{num:-e,den:1}:{num:e,den:1}}toMathJSNode(){const e={type:"OperatorNode",op:this.op.opName,fn:this.operation,args:[this.operand.toMathJSNode()],id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.operand.toString();return this.needsParentheses()?`${this.op.opName}(${e})`:`${this.op.opName}${e}`}needsParentheses(){return this.operand.type==="omdBinaryExpressionNode"}evaluate(e={}){if(!this.operand.evaluate)return NaN;const t=this.operand.evaluate(e);return this.op.opName==="-"?-t:t}static fromString(e){try{const t=window.math.parse(e);if(t.type==="OperatorNode"&&t.fn==="unaryMinus")return new Qi(t);throw new Error("Expression is not a unary minus operation.")}catch(t){throw console.error("Failed to create unary expression node from string:",t),t}}}function Ur(n,...e){if(!n)return n;n.provenance=n.provenance||[];for(const t of e)t&&(t.id&&!n.provenance.includes(t.id)&&n.provenance.push(t.id),t.provenance&&Array.isArray(t.provenance)&&t.provenance.forEach(r=>{r&&!n.provenance.includes(r)&&n.provenance.push(r)}),X0(t,n.provenance));return n}function X0(n,e){if(!n||!e)return;const t=["left","right","base","exponent","argument","expression","numerator","denominator","content"];for(const r of t){const i=n[r];i&&i.id&&!e.includes(i.id)&&(e.push(i.id),X0(i,e))}n.args&&Array.isArray(n.args)&&n.args.forEach(r=>{r&&r.id&&!e.includes(r.id)&&(e.push(r.id),X0(r,e))})}function Yn(n,e){for(n=Math.abs(n),e=Math.abs(e);e;)[n,e]=[e,n%e];return n}function Y0(n,e){const t={type:"ConstantNode",value:n,clone:function(){return{...this}}},r=new Zr(t);return r.setFontSize(e),r.initialize(),r}function Sq(n,e,t){if(n===t)return{success:!0,newRoot:e};const r=n.replaceWith(e,{updateLayout:!0});if(r){e.astNodeData=e.toMathJSNode();let i=e.parent;for(;i&&i instanceof Pt;){i.astNodeData=i.toMathJSNode();i=i.parent}}return{success:r,newRoot:t}}function Nq(n){const e=[];function t(r){if(r){if(r.type==="omdConstantNode"||r.type==="omdVariableNode"){e.push(r);return}r.left&&t(r.left),r.right&&t(r.right),r.base&&t(r.base),r.exponent&&t(r.exponent),r.argument&&t(r.argument),r.expression&&t(r.expression),r.numerator&&t(r.numerator),r.denominator&&t(r.denominator)}}return t(n),e}function oi(n,e){const t=n.operation;if(n.type==="omdBinaryExpressionNode"&&(t==="add"||t==="+"))oi(n.left,e),oi(n.right,e);else if(n.type==="omdBinaryExpressionNode"&&(t==="subtract"||t==="-")){oi(n.left,e);const r=[];oi(n.right,r),r.forEach(i=>{i.sign*=-1}),e.push(...r)}else{const r=Nq(n);e.push({node:n,sign:1,leafNodes:r})}}function Ts(n,e){if(n.length===0)return Y0(0,e);if(n.sort((i,s)=>s.sign-i.sign),n.length>1&&n[0].sign===-1)if(n[0].node.type==="omdConstantNode"){const i=n.shift();i.sign=1,n.push(i)}else n.unshift({node:Y0(0,e),sign:1});let r=n.shift().node;if(!r||typeof r.updateLayoutUpwards!="function"){const i=r.id;r=r.clone(),r.provenance=r.provenance||[],i&&!r.provenance.includes(i)&&r.provenance.push(i),r.setFontSize(e),r.initialize()}if(n.length===0)return r;for(;n.length>0;){const i=n.shift(),s=i.sign===1?"+":"-",a=i.sign===1?"add":"subtract";let o=i.node;if(!o||typeof o.updateLayoutUpwards!="function"){const f=o.id;o=o.clone(),o.provenance=o.provenance||[],f&&!o.provenance.includes(f)&&o.provenance.push(f),o.setFontSize(e),o.initialize()}i.expansionProvenance&&(o.expansionProvenance=o.expansionProvenance||[],o.expansionProvenance.push(i.expansionProvenance),[i.expansionProvenance.leftSource,i.expansionProvenance.rightSource,i.expansionProvenance.originalMultiplication].forEach(f=>{f&&!o.provenance.includes(f)&&o.provenance.push(f)}));const l={type:"OperatorNode",op:s,fn:a,args:[r.toMathJSNode(),o.toMathJSNode()],clone:function(){return{...this,args:this.args.map(f=>f.clone())}}},u=new Ci(l);u.setFontSize(e),u.initialize();const c=r.provenance||[],h=o.provenance||[];[...c,...h,r.id,o.id].forEach(f=>{f&&!u.provenance.includes(f)&&u.provenance.push(f)}),(o.expansionProvenance||r.expansionProvenance)&&(u.expansionProvenance=u.expansionProvenance||[],o.expansionProvenance&&u.expansionProvenance.push(...o.expansionProvenance),r.expansionProvenance&&u.expansionProvenance.push(...r.expansionProvenance)),r=u}return r}function pt(n){if(!n)return"";const e={add:"+",subtract:"-",multiply:ai(),divide:"÷",unaryMinus:"-",unaryPlus:"+",pow:"^"};if(typeof n.getValue=="function"&&n.isConstant&&n.isConstant())return n.getValue().toString();if(n.name)return n.name;if(n.type==="omdBinaryExpressionNode"){const t=pt(n.left),r=pt(n.right);let i;return n.op&&n.op.opName?i=e[n.op.opName]||n.op.opName:n.operation?i=e[n.operation]||n.operation:i="",i?`${t} ${i} ${r}`:`${t}${r}`}if(n.type==="omdUnaryExpressionNode"){const t=pt(n.argument);let r;return n.op&&n.op.opName?r=e[n.op.opName]||n.op.opName:n.operation?r=e[n.operation]||n.operation:r="-",t.includes(" ")||t.includes("+")||t.includes("-")||t.includes(ai())||t.includes("÷")?`${r}(${t})`:`${r}${t}`}if(n.type==="omdRationalNode"){const t=pt(n.numerator),r=pt(n.denominator);return`(${t}/${r})`}if(n.type==="omdParenthesisNode"){const t=pt(n.content||n.expression);return t.startsWith("(")&&t.endsWith(")")?t:`(${t})`}if(n.type==="omdPowerNode"){const t=pt(n.base),r=pt(n.exponent);return`${t}^${r}`}if(n.type==="omdSqrtNode")return`√(${pt(n.argument)})`;if(n.type==="omdFunctionNode"){const t=n.functionName||n.name||"f";if(n.argNodes&&n.argNodes.length>0){const r=n.argNodes.map(i=>pt(i)).join(", ");return`${t}(${r})`}else if(n.args&&n.args.length>0){const r=n.args.map(i=>pt(i)).join(", ");return`${t}(${r})`}return`${t}()`}if(n.type==="omdEquationNode"){const t=pt(n.left),r=pt(n.right);return`${t} = ${r}`}if(typeof n.toString=="function")try{return n.toString()}catch{}if(n.toMathJSNode)try{return math.parse(n.toMathJSNode()).toString()}catch{}return n.name||n.type||"[unknown]"}function Cq(n,e,t){if(e===1)return n;if(e===2)return mE(n,t);if(e===3)return gE(n,t);if(e===4)return Dq(n,t);let r=n;for(let i=1;i<e;i++)r=J0(r,n,t);return r}function mE(n,e){const t=[];for(const r of n){const i=ie.createBinaryOp(r.node.clone(),"multiply",r.node.clone(),e);(r.leafNodes||[]).forEach(a=>{[i.left,i.right,i].forEach(o=>{o&&!o.provenance.includes(a.id)&&o.provenance.push(a.id)})}),t.push({node:i,sign:r.sign*r.sign})}for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){const s=n[r],a=n[i],o=ie.createConstant(2,e),l=ie.createBinaryOp(o,"multiply",s.node.clone(),e),u=ie.createBinaryOp(l,"multiply",a.node.clone(),e);[...s.leafNodes||[],...a.leafNodes||[]].forEach(h=>{[l.right,u.right,u].forEach(f=>{f&&!f.provenance.includes(h.id)&&f.provenance.push(h.id)})}),t.push({node:u,sign:s.sign*a.sign})}return t}function gE(n,e){if(n.length===2){const[t,r]=n,i=[];return i.push({node:Fa(t.node,3,e,t.leafNodes),sign:Math.pow(t.sign,3)}),i.push({node:Vo(3,t.node,2,r.node,1,e,t.leafNodes,r.leafNodes),sign:Math.pow(t.sign,2)*r.sign}),i.push({node:Vo(3,t.node,1,r.node,2,e,t.leafNodes,r.leafNodes),sign:t.sign*Math.pow(r.sign,2)}),i.push({node:Fa(r.node,3,e,r.leafNodes),sign:Math.pow(r.sign,3)}),i}return J0(mE(n,e),n,e)}function Dq(n,e){if(n.length===2){const[r,i]=n,s=[];return s.push({node:Fa(r.node,4,e,r.leafNodes),sign:Math.pow(r.sign,4)}),s.push({node:Vo(4,r.node,3,i.node,1,e,r.leafNodes,i.leafNodes),sign:Math.pow(r.sign,3)*i.sign}),s.push({node:Vo(6,r.node,2,i.node,2,e,r.leafNodes,i.leafNodes),sign:Math.pow(r.sign,2)*Math.pow(i.sign,2)}),s.push({node:Vo(4,r.node,1,i.node,3,e,r.leafNodes,i.leafNodes),sign:r.sign*Math.pow(i.sign,3)}),s.push({node:Fa(i.node,4,e,i.leafNodes),sign:Math.pow(i.sign,4)}),s}const t=gE(n,e);return J0(t,n,e)}function Fa(n,e,t,r){if(e===1){const o=n.clone();return r&&r.length>0&&r.forEach(l=>{o.provenance.includes(l.id)||o.provenance.push(l.id)}),o}const i=ie.createConstant(e,t),s={type:"OperatorNode",op:"^",fn:"pow",args:[n.toMathJSNode(),i.toMathJSNode()],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}},a=new Ii(s);return a.setFontSize(t),a.initialize(),r&&r.length>0?r.forEach(o=>{a.base.provenance.includes(o.id)||a.base.provenance.push(o.id),a.provenance.includes(o.id)||a.provenance.push(o.id)}):(a.base.provenance.push(n.id),a.provenance.push(n.id)),a}function Vo(n,e,t,r,i,s,a,o){let l=ie.createConstant(n,s);if(t>0){const u=Fa(e,t,s,a);l=ie.createBinaryOp(l,"multiply",u,s),a&&a.length>0&&a.forEach(c=>{l.provenance.includes(c.id)||l.provenance.push(c.id)})}if(i>0){const u=Fa(r,i,s,o);l=ie.createBinaryOp(l,"multiply",u,s),o&&o.length>0&&o.forEach(c=>{l.provenance.includes(c.id)||l.provenance.push(c.id)})}return l}function vE(n,e,t){if(e===1)return n.clone();const r=ie.createConstant(e,t),i={type:"OperatorNode",op:"^",fn:"pow",args:[n.toMathJSNode(),r.toMathJSNode()],clone:function(){return{...this,args:this.args.map(a=>a.clone())}}},s=new Ii(i);return s.setFontSize(t),s.initialize(),s}function J0(n,e,t){const r=[];for(const i of n)for(const s of e){const a=ie.createBinaryOp(i.node.clone(),"multiply",s.node.clone(),t),o=[...i.leafNodes||[],...s.leafNodes||[]];o.forEach(l=>{[a.left,a.right,a].forEach(u=>{u&&!u.provenance.includes(l.id)&&u.provenance.push(l.id)})}),r.push({node:a,sign:i.sign*s.sign,leafNodes:o})}return r}function yE(n,e,t,r,i=[],s=[]){const a={type:"SymbolNode",name:e,clone:function(){return{...this}}},o=new(ie.getNodeClass("omdVariableNode"))(a);o.setFontSize(r),o.initialize(),s&&s.length>0&&(o.provenance=[...s]);let l=o;if(t!==1){const c={type:"OperatorNode",op:"^",fn:"pow",args:[a,{type:"ConstantNode",value:t,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};l=new(ie.getNodeClass("omdPowerNode"))(c),l.setFontSize(r),l.initialize(),l.base&&s&&s.length>0&&(l.base.provenance=[...s])}let u;if(n===1)u=l;else if(n===-1){const c={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[l.toMathJSNode()],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};u=new(ie.getNodeClass("omdUnaryExpressionNode"))(c),u.setFontSize(r),u.initialize(),u.argument&&s&&s.length>0&&(u.argument.provenance=[...s])}else{const c=ie.createConstant(Math.abs(n),r);i&&i.length>0&&(c.provenance=[...i]);const h=ie.createBinaryOp(c,"multiply",l,r);if(h.left&&i&&i.length>0&&(h.left.provenance=[...i]),h.right&&s&&s.length>0&&(h.right.provenance=[...s]),n<0){const f={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(d=>d.clone())}}};u=new(ie.getNodeClass("omdUnaryExpressionNode"))(f),u.setFontSize(r),u.initialize(),u.argument&&(u.argument.left&&i&&i.length>0&&(u.argument.left.provenance=[...i]),u.argument.right&&s&&s.length>0&&(u.argument.right.provenance=[...s]))}else u=h}return u}function Z0(n){const e=[],t=[];function r(i,s=!1){if(i){if(i.type==="omdVariableNode"){t.push(i);return}if(i.type==="omdConstantNode"){if(i.parent&&i.parent.type==="omdPowerNode"&&i.parent.exponent===i)return;e.push(i);return}if(i.type==="omdPowerNode"){i.base&&r(i.base,!1);return}if(i.type==="omdBinaryExpressionNode"){i.operation==="multiply"?(i.left&&r(i.left,!0),i.right&&r(i.right,!1)):(i.left&&r(i.left,s),i.right&&r(i.right,s));return}if(i.type==="omdUnaryExpressionNode"){i.argument&&r(i.argument,s);return}["left","right","base","exponent","argument","expression","numerator","denominator"].forEach(a=>{i[a]&&r(i[a],s)})}}return r(n),{coefficientNodes:e,variableNodes:t}}const rt=class rt{static createConstant(e,t=16,...r){const i=Y0(e,t);return r.length>0&&Ur(i,...r),i}static createBinaryOp(e,t,r,i=16,s=null,a=null,...o){const u={add:{op:"+",fn:"add"},subtract:{op:"−",fn:"subtract"},multiply:{op:ai(),fn:"multiply"},divide:{op:"÷",fn:"divide"}}[t];if(!u)throw new Error(`Unknown operator: ${t}`);let c=e,h=r;if(t==="multiply"){const p=e instanceof Zr&&e.isConstant(),m=r instanceof Zr&&r.isConstant();!p&&m&&(c=r,h=e)}const f={type:"OperatorNode",op:u.op,fn:u.fn,args:[c.toMathJSNode(),h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(p=>p.clone())}}};a&&(f.operatorProvenance=[a.id]);const d=new Ci(f);if(d.setFontSize(i),s)d.provenance=s;else{const p=[c,h];a&&p.push(a),p.push(...o),Ur(d,...p)}return d.initialize(),d}static createMultiplication(e,t,r=16,i=null){var l;const s=e.clone();s.provenance=[e.id];const a=t.clone(),o=((l=e.parent)==null?void 0:l.op)||null;return rt.createBinaryOp(s,"multiply",a,r,i,o)}static createRational(e,t,r=16,...i){if(t===1)return rt.createConstant(e,r,...i);const s={type:"OperatorNode",op:"/",fn:"divide",args:[{type:"ConstantNode",value:Math.abs(e)},{type:"ConstantNode",value:t}],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}};let a=new Hr(s);if(e<0){const o={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[a.toMathJSNode()],clone:function(){return{...this,args:this.args.map(l=>l.clone())}}};a=new Qi(o)}return a.setFontSize(r),i.length>0&&Ur(a,...i),a.initialize(),a}static isType(e,t){return e?e.type===t:!1}static isBinaryOp(e,t=null){if(!rt.isType(e,"omdBinaryExpressionNode"))return!1;if(!t)return!0;let r=e.operation;return typeof r=="object"&&r.name&&(r=r.name),r===t}static isConstantValue(e,t=null){return e.isConstant()?t!==null?e.getValue()===t:!0:!1}static hasConstantOperand(e){return rt.isBinaryOp(e)?e.left.isConstant()?{constant:e.left,other:e.right}:e.right.isConstant()?{constant:e.right,other:e.left}:null:null}static unwrapParentheses(e){return rt.isType(e,"omdParenthesisNode")?e.expression:e}static isMonomial(e){let t=1;for(e=rt.unwrapParentheses(e);rt.isType(e,"omdUnaryExpressionNode")&&e.operation==="unaryMinus";)e=e.argument,t*=-1,e=rt.unwrapParentheses(e);if(rt.isType(e,"omdVariableNode"))return{coefficient:1*t,variable:e.name,power:1,variableNode:e};if(rt.isBinaryOp(e,"multiply")){const r=rt.hasConstantOperand(e);if(r&&rt.isType(r.other,"omdVariableNode"))return{coefficient:r.constant.getValue()*t,variable:r.other.name,power:1,variableNode:r.other,coefficientNode:r.constant};if(r&&rt.isType(r.constant,"omdVariableNode")&&r.other.isConstant())return{coefficient:r.other.getValue()*t,variable:r.constant.name,power:1,variableNode:r.constant,coefficientNode:r.other};const i=rt.hasConstantOperand(e);if(i&&rt.isType(i.other,"omdPowerNode")){const s=i.other;if(rt.isType(s.base,"omdVariableNode")&&s.exponent.isConstant())return{coefficient:i.constant.getValue()*t,variable:s.base.name,power:s.exponent.getValue(),variableNode:s.base,coefficientNode:i.constant,powerNode:s}}}return rt.isType(e,"omdPowerNode")&&rt.isType(e.base,"omdVariableNode")&&e.exponent.isConstant()?{coefficient:1*t,variable:e.base.name,power:e.exponent.getValue(),variableNode:e.base,powerNode:e}:null}static areLikeTerms(e,t){return e.variable===t.variable&&e.power===t.power}static createMonomial(e,t,r,i,s=[]){const a={type:"SymbolNode",name:t,clone:function(){return{...this}}},o=new(rt.getNodeClass("omdVariableNode"))(a);o.setFontSize(i),o.initialize(),s&&s.length>0&&(o.provenance=[...s]);let l=o;if(r!==1){const c={type:"OperatorNode",op:"^",fn:"pow",args:[a,{type:"ConstantNode",value:r,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};l=new(rt.getNodeClass("omdPowerNode"))(c),l.setFontSize(i),l.initialize(),s&&s.length>0&&(l.provenance=[...s],l.base&&(l.base.provenance=[...s]),l.exponent&&(l.exponent.provenance=[...s]))}let u;if(e===1)u=l;else if(e===-1){const c={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[l.toMathJSNode()],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};u=new Qi(c),u.setFontSize(i),u.initialize(),s&&s.length>0&&(u.provenance=[...s],u.argument&&(u.argument.provenance=[...s]))}else{const c=rt.createConstant(Math.abs(e),i);s&&s.length>0&&(c.provenance=[...s]);const h=rt.createBinaryOp(c,"multiply",l,i);if(s&&s.length>0&&(h.provenance=[...s],h.left&&(h.left.provenance=[...s]),h.right&&(h.right.provenance=[...s])),e<0){const f={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(d=>d.clone())}}};u=new Qi(f),u.setFontSize(i),u.initialize(),s&&s.length>0&&(u.provenance=[...s],u.argument&&(u.argument.provenance=[...s],u.argument.left&&(u.argument.left.provenance=[...s]),u.argument.right&&(u.argument.right.provenance=[...s])))}else u=h}return s&&s.length>0&&s.forEach(c=>{u.provenance.includes(c)||u.provenance.push(c)}),u}static getNodeClass(e){return{omdVariableNode:Zi,omdPowerNode:Ii,omdUnaryExpressionNode:Qi}[e]}static rational(e,t,r){var o,l;const i=Yn(Math.abs(e),Math.abs(t)),s=e/i,a=t/i;return a<0?by(o=rt,Jo,xy).call(o,-s,-a,r):by(l=rt,Jo,xy).call(l,s,a,r)}static combineConstants(e,t,r,i){const s=e.getValue(),a=t.getValue();let o=null;switch(r){case"add":o=rt.createConstant(s+a,i,e,t);break;case"subtract":o=rt.createConstant(s-a,i,e,t);break;case"multiply":o=rt.createConstant(s*a,i,e,t);break;case"divide":if(a===0)return null;o=rt.rational(s,a,i,e,t);break;default:return null}return o}static createRule(e,t,r,i=null,s=null){return new rt.SimplificationRule(e,t,r,i,s)}static createConstantFoldRule(e,t){return rt.createRule(e,r=>rt.isBinaryOp(r,t)?r.left.isConstant()&&r.right.isConstant():!1,r=>rt.combineConstants(r.left,r.right,t,r.getFontSize()),(r,i,s)=>{const a=r.left.getValue(),o=r.right.getValue(),l=s.getValue?s.getValue():s.toString(),c={add:"+",subtract:"-",multiply:ai(),divide:"÷"}[t]||t;return`Combined constants: ${a} ${c} ${o} = ${l}`})}static createIdentityRule(e,t,r,i="both"){return rt.createRule(e,s=>{if(!rt.isBinaryOp(s,t))return!1;const a=rt.hasConstantOperand(s);return!a||!a.constant.isConstant()||a.constant.getValue()!==r||i==="left"&&s.right.isConstant()||i==="right"&&s.left.isConstant()?!1:{other:a.other}},(s,a)=>{const o=a.other.clone();return Ur(o,s),o.__isSimpleIdentity=!0,o},(s,a,o)=>{const{other:l}=a,u=l.toString?l.toString():"expression",c={add:"addition",subtract:"subtraction",multiply:"multiplication",divide:"division"};ai();const h=c[t]||t,d=s.left.isConstant()&&s.left.getValue()===r?"left":"right";return t==="add"&&r===0?`Applied additive identity: "${u} + 0" simplified to "${u}" (adding 0 doesn't change the value)`:t==="subtract"&&r===0?`Applied subtraction identity: "${u} - 0" simplified to "${u}" (subtracting 0 doesn't change the value)`:t==="multiply"&&r===1?`Applied multiplicative identity: "${u} ${ai()} 1" simplified to "${u}" (multiplying by 1 doesn't change the value)`:t==="divide"&&r===1?`Applied division identity: "${u} ÷ 1" simplified to "${u}" (dividing by 1 doesn't change the value)`:`Applied ${h} identity: removed ${r} from ${d} side, leaving "${u}"`})}static createZeroMultiplicationRule(){return rt.createRule("Zero Multiplication",e=>{if(!rt.isBinaryOp(e,"multiply"))return!1;const t=rt.hasConstantOperand(e);return t&&t.constant.getValue()===0},e=>rt.createConstant(0,e.getFontSize(),e),(e,t,r)=>{const s=rt.hasConstantOperand(e).other;return`Applied zero multiplication: ${pt(s)} ${ai()} 0 = 0`})}};Jo=new WeakSet,xy=function(e,t,r){if(t===1)return rt.createConstant(e,r);const i={type:"OperatorNode",op:"/",fn:"divide",args:[{type:"ConstantNode",value:Math.abs(e),clone:function(){return{...this}}},{type:"ConstantNode",value:t,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(a=>a.clone())}}};let s=new Hr(i);if(e<0){const a={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[s.toMathJSNode()],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}};s=new Qi(a)}return s.setFontSize(r),s.initialize(),s},TE(rt,Jo),eu(rt,"SimplificationRule",class{constructor(t,r,i,s=null,a=null){this.name=t,this.type=a,this.match=r,this.transform=i,this.message=s}canApply(t){const r=this.match(t);return r===!1||r===null||r===void 0?null:r===!0?{}:r}apply(t,r,i){try{if(typeof this.transform!="function")throw new Error(`Invalid transform function for rule: ${this.name}`);const s=this.transform(t,r,i);if(!s)throw new Error(`Transform function for rule '${this.name}' did not return a new node.`);const a=this._collectAffectedNodeIds(t),{success:o,newRoot:l}=Sq(t,s,i);if(o){const u=s.__affectedNodeIds||a,c=s.__resultNodeId||s.id,h={name:this.name,affectedNodes:u,resultNodeId:c,resultProvSources:s.provenance,message:this.message(t,r,s)};return{success:!0,newRoot:l,historyEntry:h}}else return{success:!1,newRoot:i}}catch(s){return console.error(`Error applying rule '${this.name}':`,s),{success:!1,newRoot:i}}}_collectAffectedNodeIds(t){return t&&t.provenance&&t.provenance.length>0?t.provenance.filter(r=>r!==t.id):t&&t.id?[t.id]:[]}_generateMessage(t,r,i){if(this.message)try{return this.message(t,r,i)}catch(o){console.warn(`Error generating message for rule ${this.name}:`,o)}const s=t.toString?t.toString():"expression",a=i.toString?i.toString():"expression";return`Applied ${this.name}: "${s}" → "${a}"`}});let ie=rt;const Aq=[ie.createRule("Simplify Double Negation",n=>n.operation==="unaryMinus"&&ie.isType(n.argument,"omdUnaryExpressionNode")&&n.argument.operation==="unaryMinus",n=>{const e=n.argument.argument.clone();return e.provenance.push(n.id,n.argument.id),e},(n,e,t)=>{const r=pt(n.argument.argument);return`Simplified double negation: -(-${r}) = ${r}`}),ie.createRule("Remove Unary Plus",n=>n.operation==="unaryPlus",n=>{const e=n.argument.clone();return e.provenance.push(n.id),e},(n,e,t)=>`Removed unary plus from "${pt(n.argument)}"`)],Eq=[ie.createRule("Remove Redundant Parentheses",n=>ie.isType(n.expression,"omdParenthesisNode"),n=>{const e=n.expression.clone();return e.provenance.push(n.id),e},(n,e,t)=>`Removed redundant parentheses around "${pt(n.content)}"`)],Mq=[ie.createRule("Simplify Square Root of Constant",n=>{if(!n.argument.isConstant())return!1;const e=n.argument.getValue();if(e<0)return!1;const t=Math.sqrt(e);return Number.isInteger(t)?{value:t}:!1},(n,e)=>{const t=ie.createConstant(e.value,n.getFontSize());return t.provenance.push(n.id,n.argument.id),t},(n,e,t)=>{const r=n.argument.getValue(),i=e.value;return`Calculated square root: √${r} = ${i}`}),ie.createRule("Square Root of Square",n=>{if(!n.argument||n.argument.type!=="omdPowerNode")return!1;const e=n.argument;return!e.exponent.isConstant()||e.exponent.getValue()!==2?!1:{base:e.base}},(n,e)=>{const t=e.base.clone();return t.provenance.push(n.id,n.argument.id),t},(n,e,t)=>{const r=pt(e.base);return`Simplified square root of square: √(${r}²) = ${r}`})];class Fs extends Pt{constructor(e){super(e),this.type="omdSqrtNode",this.args=e.args||[],this.value=this.parseValue(),this.argument=this.createArgumentNode(),this.argument&&(this.argumentNodeList.argument=this.argument),[this.radicalPath,this.radicalLine]=this.createRadicalElements()}parseValue(){return"sqrt"}createArgumentNode(){if(this.args.length===0)return null;const e=this.args[0],t=_t(e);let r=new t(e);return this.addChild(r),r}createRadicalElements(){let e=new Ni;e.setStrokeColor("black"),e.setStrokeWidth(2),e.setFillColor("none"),this.addChild(e);let t=new Ut;return t.setStrokeColor("black"),t.setStrokeWidth(2),this.addChild(t),[e,t]}computeDimensions(){if(!this.argument)return;const e=this.getFontSize(),t=e*5/6;this.argument.setFontSize(t),this.argument.computeDimensions();const r=e/this.getRootFontSize(),i=4*r,s=this.argument.width,a=this.argument.height,l=Math.max(12*r,a*.3)+i+s+i,u=a+8*r;this.setWidthAndHeight(l,u)}updateLayout(){if(!this.argument)return;const t=this.getFontSize()/this.getRootFontSize(),r=4*t;let i=0;const s=this.argument.height,a=Math.max(12*t,s*.3),o=i+a+r,l=(this.height-s)/2;this.argument.setPosition(o,l),this.argument.updateLayout();const u=l+s-2*t,c=l-4*t,h=l+s*.7;this.radicalPath.clearPoints(),this.radicalPath.addPoint(i+a*.3,h),this.radicalPath.addPoint(i+a*.6,u),this.radicalPath.addPoint(i+a,c),this.radicalPath.updatePath();const f=l-2*t,d=i+a,p=o+this.argument.width+r/2;this.radicalLine.setEndpoints(d,f,p,f)}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Fs(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.radicalPath=new Ni,t.radicalPath.setStrokeColor("black"),t.radicalPath.setStrokeWidth(2),t.radicalPath.setFillColor("none"),t.addChild(t.radicalPath),t.radicalLine=new Ut,t.radicalLine.setStrokeColor("black"),t.radicalLine.setStrokeWidth(2),t.addChild(t.radicalLine),this.argument&&(t.argument=this.argument.clone(),t.addChild(t.argument),t.argumentNodeList.argument=t.argument,t.provenance.push(this.id)),t}highlightAll(){this.select(),this.argument&&this.argument.highlightAll&&this.argument.highlightAll()}unhighlightAll(){this.deselect(),this.argument&&this.argument.unhighlightAll&&this.argument.unhighlightAll()}toMathJSNode(){const e={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt",clone:function(){return{...this}}},args:this.argument?[this.argument.toMathJSNode()]:[]};return e.clone=function(){const t={...this};return this.args&&(t.args=this.args.map(r=>r.clone())),this.fn&&typeof this.fn.clone=="function"&&(t.fn=this.fn.clone()),t},e}toString(){return`sqrt(${this.argument?this.argument.toString():""})`}evaluate(e={}){if(!this.argument||!this.argument.evaluate)return NaN;const t=this.argument.evaluate(e);return t<0?NaN:Math.sqrt(t)}isSquareRoot(){return!0}isCubeRoot(){return!1}toPowerForm(){if(!this.argument)return null;const e={type:"OperatorNode",op:"^",fn:"pow",args:[this.argument.toMathJSNode(),Zr.fromNumber(.5).toMathJSNode()]};return new Ii(e)}static fromString(e){try{const t=window.math.parse(e);if(t.type==="FunctionNode"&&t.fn.name==="sqrt")return new Fs(t);throw new Error("Expression is not a 'sqrt' function.")}catch(t){throw console.error("Failed to create sqrt node from string:",t),t}}}const Tq=[ie.createRule("Calculate Powers",n=>{if(!n.base.isConstant()||!n.exponent.isConstant())return!1;const e=n.base.getValue(),t=n.exponent.getValue();return{value:Math.pow(e,t)}},(n,e)=>{const t=ie.createConstant(e.value,n.getFontSize());return t.provenance.push(n.id),t},(n,e,t)=>{const{base:r,exponent:i}=n,s=e.value;return`Calculated power: ${pt(r)}^${pt(i)} = ${s}`}),ie.createRule("Power of Zero",n=>n.exponent.isConstant()&&n.exponent.getValue()===0,n=>{const e=ie.createConstant(1,n.getFontSize());return e.provenance.push(n.id),e},(n,e,t)=>{const{base:r}=n;return`Simplified power of zero: ${pt(r)}^0 = 1`}),ie.createRule("Power of One",n=>n.exponent.isConstant()&&n.exponent.getValue()===1,n=>{const e=n.base.clone();return e.provenance.push(n.id),e},(n,e,t)=>{const{base:r}=n;return`Simplified power of one: ${pt(r)}^1 = ${pt(r)}`}),ie.createRule("Expand Polynomial Power",n=>{if(!n.exponent.isConstant())return!1;const e=n.exponent.getValue();if(!Number.isInteger(e)||e<2||e>4)return!1;let t=ie.unwrapParentheses(n.base);if(!ie.isBinaryOp(t,"add")&&!ie.isBinaryOp(t,"subtract"))return!1;const r=[];return oi(t,r),r.length>5?!1:{baseExpression:t,terms:r,exponent:e}},(n,e)=>{const{terms:t,exponent:r}=e,i=Cq(t,r,n.getFontSize()),s=Ts(i,n.getFontSize());return s&&s.provenance.push(n.id),s},(n,e,t)=>{const{baseExpression:r,exponent:i}=e;return`Expanded polynomial power: (${pt(r)})^${i}`}),ie.createRule("Square of Square Root",n=>!n.exponent.isConstant()||n.exponent.getValue()!==2||n.base.type!=="omdSqrtNode"?!1:{innerArg:n.base.argument},(n,e)=>{const t=e.innerArg.clone();return t.provenance.push(n.id,n.base.id),t},(n,e,t)=>{const r=pt(e.innerArg);return`Simplified square of square root: (√${r})² = ${r}`}),ie.createRule("Fractional Exponent to Square Root",n=>{if(!n.exponent.isConstant())return!1;const e=n.exponent.getValue();return Math.abs(e-.5)>1e-4?!1:{base:n.base}},(n,e)=>{const t={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt"},args:[e.base.toMathJSNode()]},r=new Fs(t);return r.setFontSize(n.getFontSize()),r.initialize(),r.provenance.push(n.id),r},(n,e,t)=>{const r=pt(e.base);return`Converted fractional exponent to square root: ${r}^(1/2) = √${r}`})],Fq=[["sin","arcsin"],["cos","arccos"],["tan","arctan"],["ln","exp"],["log","pow10"],["sqrt","square"],["sinh","asinh"],["cosh","acosh"],["tanh","atanh"]];function _q(n){for(const[e,t]of Fq){if(e===n)return t;if(t===n)return e}return null}const Oq=[ie.createRule("Function Inverse Simplification",n=>{if(n.type!=="omdFunctionNode"||!n.functionName||!n.argNodes||n.argNodes.length!==1)return!1;const e=n.functionName,t=n.argNodes[0];if(t.type!=="omdFunctionNode"||!t.functionName||!t.argNodes||t.argNodes.length!==1)return!1;const r=t.functionName;return _q(e)===r?{outerFunction:e,innerFunction:r,innerArg:t.argNodes[0]}:!1},(n,e)=>{const t=e.innerArg.clone();return t.provenance.push(n.id,n.argNodes[0].id),t},(n,e,t)=>{const{outerFunction:r,innerFunction:i}=e,s=pt(e.innerArg);return`Simplified inverse functions: ${r}(${i}(${s})) = ${s}`}),ie.createRule("Function to Sqrt Node",n=>n.type!=="omdFunctionNode"||n.functionName!=="sqrt"||!n.argNodes||n.argNodes.length!==1?!1:{argument:n.argNodes[0]},(n,e)=>{const t={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt"},args:[e.argument.toMathJSNode()]},r=new Fs(t);return r.setFontSize(n.getFontSize()),r.initialize(),r.provenance.push(n.id),r},(n,e,t)=>{const r=pt(e.argument);return`Converted function to sqrt node: sqrt(${r}) = √${r}`})],Bq=[ie.createRule("Unary Minus Cancellation",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdUnaryExpressionNode")&&ie.isType(t,"omdUnaryExpressionNode")?{numeratorArg:e.argument||e.operand,denominatorArg:t.argument||t.operand,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=n.getFontSize(),r=e.numeratorArg,i=e.denominatorArg;if(i&&typeof i.isConstant=="function"&&i.isConstant()&&i.getValue()===1){const u=r.clone();try{Ur(u,n.numerator,n.denominator,n)}catch{u.provenance=u.provenance||[],e.numeratorNode&&u.provenance.push(e.numeratorNode.id),e.denominatorNode&&u.provenance.push(e.denominatorNode.id),u.provenance.push(n.id)}return u}const s=r.clone(),a=i.clone(),o={type:"OperatorNode",op:"/",fn:"divide",args:[s.toMathJSNode(),a.toMathJSNode()],clone:function(){return{...this,args:this.args.map(u=>u.clone())}}},l=new Hr(o);l.setFontSize(t),l.initialize();try{l.numerator&&Ur(l.numerator,n.numerator),l.denominator&&Ur(l.denominator,n.denominator),Ur(l,n.numerator,n.denominator,n)}catch{Q0(l,e.numeratorNode.argument||e.numeratorNode.operand,e.denominatorNode.argument||e.denominatorNode.operand),l.provenance.includes(n.id)||l.provenance.push(n.id)}return l},(n,e,t)=>"Canceled unary negatives in fraction","rational"),ie.createRule("Unary Numerator Divide By -1",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdUnaryExpressionNode")&&t.isConstant&&t.isConstant()&&t.getValue()===-1?{numeratorArg:e.argument||e.operand,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=e.numeratorArg.clone();try{Ur(t,n.numerator,n.denominator,n)}catch{t.provenance=t.provenance||[],e.numeratorNode&&t.provenance.push(e.numeratorNode.id),e.denominatorNode&&t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id)}return t},(n,e,t)=>"Divided by -1 cancels unary minus in numerator","rational"),ie.createRule("Variable Self Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdVariableNode")&&ie.isType(t,"omdVariableNode")&&e.name===t.name?{variable:e.name,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=ie.createConstant(1,n.getFontSize());return t.provenance.push(e.numeratorNode.id),t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id),t},(n,e,t)=>{const{variable:r}=e;return`Simplified variable self-division: ${r}/${r} = 1`}),ie.createRule("Power Base Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(ie.isType(e,"omdPowerNode")&&ie.isType(t,"omdVariableNode")&&ie.isType(e.base,"omdVariableNode")&&e.base.name===t.name&&e.exponent.isConstant()){const r=e.exponent.getValue(),i=r-1;return{variable:e.base.name,originalExponent:r,newExponent:i,baseNode:e.base,powerNode:e,denominatorNode:t}}return!1},(n,e)=>{const{variable:t,newExponent:r,baseNode:i,powerNode:s,denominatorNode:a}=e,o=n.getFontSize();let l;return r===0?l=ie.createConstant(1,o):r===1?l=i.clone():l=vE(i.clone(),r,o),l.provenance.push(s.id),l.provenance.push(a.id),l.provenance.push(n.id),l},(n,e,t)=>{const{variable:r,originalExponent:i,newExponent:s}=e;return s===0?`Simplified power division: ${r}^${i}/${r} = 1`:s===1?`Simplified power division: ${r}^${i}/${r} = ${r}`:`Simplified power division: ${r}^${i}/${r} = ${r}^${s}`}),ie.createRule("Monomial Variable Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator),r=ie.isMonomial(e);return r&&ie.isType(t,"omdVariableNode")&&r.variable===t.name&&r.power===1?{coefficient:r.coefficient,variable:r.variable,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const{coefficient:t}=e,r=n.getFontSize(),i=ie.createConstant(t,r);return i.provenance.push(e.numeratorNode.id),i.provenance.push(e.denominatorNode.id),i.provenance.push(n.id),i},(n,e,t)=>{const{coefficient:r,variable:i}=e;return`Simplified monomial division: ${r}${i}/${i} = ${r}`}),ie.createRule("Simplify Fraction",n=>{if(n.type!=="omdRationalNode")return!1;const e=n.numerator,t=n.denominator;if(!e.isConstant()||!t.isConstant())return!1;const r=e.getValue(),i=t.getValue();if(i===0)return!1;const s=Yn(Math.abs(r),Math.abs(i));return s>1||i<0?{originalNum:r,originalDen:i,gcd:s,simplifiedNum:i<0?-r/s:r/s,simplifiedDen:Math.abs(i)/s}:!1},(n,e)=>{const{simplifiedNum:t,simplifiedDen:r}=e;if(r===1){const i=ie.createConstant(t,n.getFontSize(),n.numerator,n.denominator);return i.provenance.push(n.id),i}else{const i=ie.rational(t,r,n.getFontSize());return Q0(i,n.numerator,n.denominator),i.provenance.push(n.id),i}},(n,e,t)=>{const{originalNum:r,originalDen:i,simplifiedNum:s,simplifiedDen:a,gcd:o}=e;return i<0&&o>1?`Simplified fraction: ${r}/${i} = ${s}/${a} (corrected sign and reduced by GCD ${o})`:a===1?`Simplified fraction to whole number: ${r}/${i} = ${s}`:o>1?`Simplified fraction: ${r}/${i} = ${s}/${a} (reduced by GCD ${o})`:`Corrected fraction sign: ${r}/${i} = ${s}/${a}`}),ie.createRule("Simplify Multiplication in Rational",n=>{let e=n.numerator;if(!n.denominator.isConstant())return!1;const t=n.denominator.getValue();if(t===0||(e=ie.unwrapParentheses(e),!ie.isBinaryOp(e,"multiply")))return!1;const r=ie.hasConstantOperand(e);return r?{numeratorCoeff:r.constant.getValue(),denominator:t,expression:r.other}:!1},(n,e)=>{const{numeratorCoeff:t,denominator:r,expression:i}=e,s=ie.rational(t,r,n.getFontSize());kq(s,n);const a=ie.createBinaryOp(s,"multiply",i.clone(),n.getFontSize());return a.right&&a.right.provenance.push(i.id),a.provenance.push(n.id),a},(n,e,t)=>{const{numeratorCoeff:r,denominator:i}=e,s=Yn(Math.abs(r),Math.abs(i));if(s===1)return"Separated the coefficient from the variable, changing the fraction into a multiplication.";const a=r/s,o=i/s;let l=`The numerator and denominator share a common factor of ${s}. `;return l+=`Dividing both by ${s} (${r} ÷ ${s} = ${a}, and ${i} ÷ ${s} = ${o}) simplifies the fraction.`,l},"rational"),ie.createRule("Cancel Negative Coefficient",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(!ie.isType(e,"omdUnaryExpressionNode"))return!1;const r=e.argument||e.operand;if(!ie.isBinaryOp(r,"multiply"))return!1;const i=ie.hasConstantOperand(r);if(!i||!i.constant.isConstant()||!t.isConstant())return!1;const s=t.getValue();if(s>=0)return!1;const a=i.constant.getValue();return Math.abs(a)===Math.abs(s)?{innerMultiplication:r,otherFactor:i.other,numeratorUnary:e,denominatorNode:t}:!1},(n,e)=>{const t=e.otherFactor.clone();try{Ur(t,e.innerMultiplication||n.numerator,n.denominator,n)}catch{t.provenance=t.provenance||[],t.provenance.push(e.numeratorUnary.id),t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id)}return t},(n,e,t)=>"Canceled matching numeric factors between numerator and denominator","rational"),ie.createRule("Negative Constant Over Negative Product",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(!e.isConstant||!e.isConstant()||e.getValue()>=0||!ie.isBinaryOp(t,"multiply"))return!1;const i=ie.hasConstantOperand(t);return!i||!i.constant.isConstant()||i.constant.getValue()>=0?!1:{numeratorNode:e,denominatorNode:t,denominatorConst:i.constant,denominatorOther:i.other}},(n,e)=>{const t=n.getFontSize(),r=ie.createConstant(Math.abs(e.numeratorNode.getValue()),t),i=ie.createConstant(Math.abs(e.denominatorConst.getValue()),t),s=ie.createBinaryOp(i,"multiply",e.denominatorOther.clone(),t),a={type:"OperatorNode",op:"/",fn:"divide",args:[r.toMathJSNode(),s.toMathJSNode()],clone:function(){return{...this,args:this.args.map(l=>l.clone())}}},o=new Hr(a);o.setFontSize(t),o.initialize();try{const l=e&&e.numeratorNode&&(e.numeratorNode.argument||e.numeratorNode.operand)||n.numerator;o.numerator&&l&&Ur(o.numerator,l);const u=e&&e.denominatorNode||n.denominator;if(o.denominator&&ie.isBinaryOp(u,"multiply")&&ie.isBinaryOp(o.denominator,"multiply")){const c=e&&e.denominatorConst||u.left||u.right,h=e&&e.denominatorOther||(u.left===c?u.right:u.left);o.denominator.left&&c&&Ur(o.denominator.left,c),o.denominator.right&&h&&Ur(o.denominator.right,h)}else o.denominator&&Ur(o.denominator,n.denominator);Ur(o,n.numerator,n.denominator,n)}catch{Q0(o,n.numerator,n.denominator),o.provenance.includes(n.id)||o.provenance.push(n.id)}return o},(n,e,t)=>"Canceled matching negative factors: simplified sign and magnitude","rational"),ie.createRule("Simplify Rational Division",n=>{if(n.type!=="omdRationalNode")return!1;let e=n.numerator;const t=n.denominator;if(!t.isConstant()||(e=ie.unwrapParentheses(e),!ie.isBinaryOp(e,"add")&&!ie.isBinaryOp(e,"subtract")))return!1;const r=[];return oi(e,r),{terms:r,denominator:t.getValue()}},(n,e)=>{const{terms:t,denominator:r}=e,i=n.getFontSize(),s=t.map(a=>{const l=(a.node.isConstant()?a.node.getValue():1)*a.sign;if(a.node.isConstant()){const u=Yn(Math.abs(l),Math.abs(r)),c=l/u,h=r/u;if(h===1){const f=ie.createConstant(c,i);return K0(f,a.node,n.denominator),{node:f,sign:1}}else{const f=ie.rational(Math.abs(c),h,i);return K0(f,a.node,n.denominator),{node:f,sign:c>=0?1:-1}}}else if(l===r){const u=a.node.clone();return u.provenance.push(a.node.id),{node:u,sign:1}}else{const u=ie.rational(Math.abs(l),r,i),c=ie.createBinaryOp(u,"multiply",a.node.clone(),i);return K0(u,a.node,n.denominator),c.provenance.push(n.id),{node:c,sign:l>=0?1:-1}}});return Ts(s,i)},(n,e,t)=>{const{terms:r,denominator:i}=e,s=pt(n.numerator),a=r.map(l=>{const u=(l.node.isConstant()?l.node.getValue():1)*l.sign,c=Yn(Math.abs(u),Math.abs(i)),h=u/c,f=i/c,d=l.node.isConstant()?"":pt(l.node);return f===1?`${h}${d}`:`(${h}/${f})${d}`}).join(" + ");return`Distributed division: ${s.startsWith("(")&&s.endsWith(")")?s:`(${s})`}/${i} = ${a}`},"rational")];function Q0(n,e,t){e!=null&&e.provenance?e.provenance.forEach(r=>{n.provenance.includes(r)||n.provenance.push(r)}):e&&n.provenance.push(e.id),t!=null&&t.provenance?t.provenance.forEach(r=>{n.provenance.includes(r)||n.provenance.push(r)}):t&&n.provenance.push(t.id)}function kq(n,e){var r,i,s,a;const t=(i=(r=e.numerator)==null?void 0:r.left)!=null&&i.isConstant()?e.numerator.left:(s=e.numerator)==null?void 0:s.right;t!=null&&t.provenance?t.provenance.forEach(o=>{n.provenance.includes(o)||n.provenance.push(o)}):t&&n.provenance.push(t.id),(a=e.denominator)!=null&&a.provenance?e.denominator.provenance.forEach(o=>{n.provenance.includes(o)||n.provenance.push(o)}):e.denominator&&n.provenance.push(e.denominator.id)}function K0(n,e,t){var r,i,s;n.numerator&&e&&(n.numerator.provenance=[],((r=e.provenance)==null?void 0:r.length)>0?e.provenance.forEach(a=>{n.numerator.provenance.push(a)}):n.numerator.provenance.push(e.id)),n.denominator&&t&&(n.denominator.provenance=[],((i=t.provenance)==null?void 0:i.length)>0?t.provenance.forEach(a=>{n.denominator.provenance.push(a)}):n.denominator.provenance.push(t.id)),((s=e.provenance)==null?void 0:s.length)>0&&e.provenance.forEach(a=>{n.provenance.includes(a)||n.provenance.push(a)})}const _s={binary:[ie.createRule("Opposite Term Cancellation",n=>{if(!ie.isBinaryOp(n,"add"))return!1;if(n.left.isConstant()){const i=n.left.getValue();if(ie.isType(n.right,"omdUnaryExpressionNode")&&n.right.operation==="unaryMinus"&&n.right.argument.isConstant()){const s=n.right.argument.getValue();if(i===s)return{leftTerm:n.left,rightTerm:n.right,termType:"constant",leftValue:i,rightValue:-s,isNegatedRight:!0}}if(n.right.isConstant()){const s=n.right.getValue();if(i===-s)return{leftTerm:n.left,rightTerm:n.right,termType:"constant",leftValue:i,rightValue:s,isNegatedRight:!1}}}const e=ie.isMonomial(n.left);let t=null,r=!1;if(ie.isType(n.right,"omdUnaryExpressionNode")&&n.right.operation==="unaryMinus"?(t=ie.isMonomial(n.right.argument),r=!0):t=ie.isMonomial(n.right),e&&t){let i=e.coefficient,s=t.coefficient;if(r&&(s=-s),e.variable===t.variable&&e.power===t.power&&i===-s)return{leftTerm:n.left,rightTerm:n.right,termType:"monomial",variable:e.variable,power:e.power,leftCoeff:i,rightCoeff:s,isNegatedRight:r}}return!1},(n,e)=>{const{leftTerm:t,rightTerm:r}=e,i=ie.createConstant(0,n.getFontSize());return i.provenance.push(t.id),i.provenance.push(r.id),i.provenance.push(n.id),i},(n,e,t)=>{const{termType:r}=e;if(r==="constant"){const{leftValue:i,rightValue:s,isNegatedRight:a}=e;return a?`Cancelled opposite terms: ${i} + (-${i}) = 0`:`Cancelled opposite terms: ${i} + ${s} = 0`}else{const{variable:i,power:s,leftCoeff:a,rightCoeff:o,isNegatedRight:l}=e,u=s!==1?`^${s}`:"",h=`${a===1?"":a===-1?"-":`${a}`}${i}${u}`;let f;if(l){const d=Math.abs(o);f=`(-${d===1?"":`${d}`}${i}${u})`}else f=`${o===1?"":o===-1?"-":`${o}`}${i}${u}`;return`Cancelled opposite terms: ${h} + ${f} = 0`}}),ie.createRule("Cancel Constants in Sums",n=>{if(!ie.isBinaryOp(n)||n.operation!=="add"&&n.operation!=="subtract")return!1;const e=[];if(oi(n,e),e.length<3)return!1;const t=e.filter(a=>a.node.isConstant()),r=e.filter(a=>!a.node.isConstant());if(r.length===0||t.length<2)return!1;const i=[],s=new Set;for(let a=0;a<t.length;a++){if(s.has(a))continue;const o=t[a],l=o.node.getValue()*o.sign;for(let u=a+1;u<t.length;u++){if(s.has(u))continue;const c=t[u],h=c.node.getValue()*c.sign;if(l+h===0){i.push([o,c]),s.add(a),s.add(u);break}}}return i.length>0?{terms:e,cancellingPairs:i,constantTerms:t,nonConstantTerms:r}:!1},(n,e)=>{const{terms:t,cancellingPairs:r,constantTerms:i,nonConstantTerms:s}=e,a=[...s],o=new Set;r.forEach(c=>{c.forEach(h=>o.add(h))}),i.forEach(c=>{o.has(c)||a.push(c)});let l=[];if(r.length>0){const c=ie.createConstant(0,n.getFontSize());r.forEach(h=>{const[f,d]=h,p=t.find(m=>m.node.type==="omdBinaryExpressionNode"&&(m.node.left===f.node&&m.node.right===d.node||m.node.left===d.node&&m.node.right===f.node));h.forEach(m=>{c.provenance.push(m.node.id),l.push(m.node.id),m.node.operation&&(c.provenance.push(m.node.operation.id),l.push(m.node.operation.id))}),p&&p.node.operation&&(c.provenance.push(p.node.operation.id),l.push(p.node.operation.id))}),a.push({node:c,sign:1})}const u=Ts(a,n.getFontSize());return u&&l.forEach(c=>{u.provenance.includes(c)||u.provenance.push(c)}),u},(n,e,t)=>{const{cancellingPairs:r}=e;return`Cancelled constants in sum: ${r.map(s=>{const[a,o]=s,l=a.node.getValue(),u=o.node.getValue(),c=a.sign===1?"+":"-",h=o.sign===1?"+":"-";return`${c} ${l} ${h} ${u} = 0`}).join(", ")}`}),ie.createConstantFoldRule("Add Constants","add"),ie.createConstantFoldRule("Subtract Constants","subtract"),ie.createConstantFoldRule("Multiply Constants","multiply"),ie.createConstantFoldRule("Divide Constants","divide"),ie.createIdentityRule("Add Zero","add",0),ie.createIdentityRule("Subtract Zero","subtract",0,"right"),ie.createIdentityRule("Multiply One","multiply",1),ie.createIdentityRule("Divide One","divide",1,"right"),ie.createZeroMultiplicationRule(),ie.createRule("Combine Coefficients",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;if(!ie.isBinaryOp(t,"multiply"))return!1;const r=ie.hasConstantOperand(t);if(!r)return!1;const i=e.constant.getValue(),s=r.constant.getValue(),a=r.other;return{coefficient:i*s,expression:a}},(n,e)=>{const{coefficient:t,expression:r}=e,i=ie.createMultiplication(ie.createConstant(t,n.getFontSize()),r.clone(),n.getFontSize());return i.provenance.push(n.id),i.left&&i.left.provenance.push(n.left.id,n.right.id),i.right&&i.right.provenance.push(r.id),i},(n,e,t)=>{const{coefficient:r,expression:i}=e,s=ie.hasConstantOperand(n),a=ie.hasConstantOperand(s.other),o=s.constant.getValue(),l=a.constant.getValue();return`Combined coefficients: ${o} ${ai()} ${l} = ${r}`}),ie.createRule("Distributive Property",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;let r=t;return ie.isType(t,"omdParenthesisNode")&&(r=t.expression),!ie.isBinaryOp(r,"add")&&!ie.isBinaryOp(r,"subtract")?!1:{constantNode:e.constant,innerExpr:r,originalInnerNode:t}},(n,e)=>{const{constantNode:t,innerExpr:r}=e,i=t.getValue(),s=n.getFontSize(),a=[];oi(r,a);const o=a.map(l=>{const u=i*l.sign,c=ie.createBinaryOp(ie.createConstant(Math.abs(u),s),"multiply",l.node.clone(),s);return c.provenance.push(n.id,t.id,l.node.id),{node:c,sign:u>=0?1:-1}});return Ts(o,s)},(n,e,t)=>{const{constantNode:r,innerExpr:i}=e,s=r.toString(),a=i.toString();return`Applied distributive property: ${s} ${ai()} (${a})`}),ie.createRule("Expand Polynomial Multiplication",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;let e=ie.unwrapParentheses(n.left),t=ie.unwrapParentheses(n.right);const r=ie.isBinaryOp(e,"add")||ie.isBinaryOp(e,"subtract"),i=ie.isBinaryOp(t,"add")||ie.isBinaryOp(t,"subtract");if(!r||!i)return!1;const s=[],a=[];return oi(e,s),oi(t,a),s.length>4||a.length>4?!1:{leftExpression:e,rightExpression:t,leftTerms:s,rightTerms:a}},(n,e)=>{const{leftTerms:t,rightTerms:r}=e,i=n.getFontSize(),s=[];for(const a of t)for(const o of r){const l=a.sign*o.sign,u=ie.createBinaryOp(a.node.clone(),"multiply",o.node.clone(),i),c=[...a.leafNodes||[],...o.leafNodes||[]];c.forEach(h=>{[u.left,u.right,u].forEach(f=>{f&&!f.provenance.includes(h.id)&&f.provenance.push(h.id)})}),s.push({node:u,sign:l,leafNodes:c})}return Ts(s,i)},(n,e,t)=>{const{leftExpression:r,rightExpression:i}=e,s=pt(r),a=pt(i);return`Expanded polynomial multiplication: (${s})(${a})`}),ie.createRule("Multiply Monomials",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.isMonomial(n.left),t=ie.isMonomial(n.right);return!e||!t||e.variable!==t.variable?!1:{variable:e.variable,leftCoeff:e.coefficient,rightCoeff:t.coefficient,leftPower:e.power,rightPower:t.power,leftNode:n.left,rightNode:n.right}},(n,e)=>{const{variable:t,leftCoeff:r,rightCoeff:i,leftPower:s,rightPower:a,leftNode:o,rightNode:l}=e,u=n.getFontSize(),c=r*i,h=s+a,f=Z0(o),d=Z0(l),p=[...f.coefficientNodes.map(v=>v.id),...d.coefficientNodes.map(v=>v.id)],m=[...f.variableNodes.map(v=>v.id),...d.variableNodes.map(v=>v.id)],y=yE(c,t,h,u,p,m);return y.provenance.push(n.id),y},(n,e,t)=>{const{leftCoeff:r,rightCoeff:i,variable:s,leftPower:a,rightPower:o}=e,l=r*i,u=a+o,c=pt(e.leftNode),h=pt(e.rightNode);return`Multiplied monomials: ${c} ${ai()} ${h} = ${l}${s}${u>1?`^${u}`:""}`}),ie.createRule("Combine Like Factors",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;if(ie.isType(n.left,"omdVariableNode")&&ie.isType(n.right,"omdVariableNode")&&n.left.name===n.right.name)return{variable:n.left.name,leftNode:n.left,rightNode:n.right,power:2};let e=null,t=1,r=1,i=n.left,s=n.right;if(ie.isType(n.left,"omdVariableNode")?(e=n.left.name,t=1):ie.isType(n.left,"omdPowerNode")&&ie.isType(n.left.base,"omdVariableNode")&&n.left.exponent.isConstant()&&(e=n.left.base.name,t=n.left.exponent.getValue()),ie.isType(n.right,"omdVariableNode"))if(e===n.right.name)r=1;else return!1;else if(ie.isType(n.right,"omdPowerNode")&&ie.isType(n.right.base,"omdVariableNode")&&n.right.exponent.isConstant())if(e===n.right.base.name)r=n.right.exponent.getValue();else return!1;else return!1;return e&&Number.isInteger(t)&&Number.isInteger(r)?{variable:e,leftNode:i,rightNode:s,power:t+r}:!1},(n,e)=>{const{variable:t,power:r,leftNode:i,rightNode:s}=e,a=n.getFontSize();let o;if(r===1)o=ie.createMonomial(1,t,1,a);else{const l=ie.createMonomial(1,t,1,a);o=vE(l,r,a)}return o.provenance.push(i.id,s.id,n.id),o},(n,e,t)=>{const{variable:r,power:i}=e,s=pt(e.leftNode),a=pt(e.rightNode);return`Combined like factors: ${s} ${ai()} ${a} = ${r}${i>1?`^${i}`:""}`}),ie.createRule("Combine Multiple Constants in Sums",n=>{if(!ie.isBinaryOp(n)||n.operation!=="add"&&n.operation!=="subtract")return!1;const e=[];if(oi(n,e),e.filter(a=>a.node.isConstant()).length<=1)return!1;const r=e.filter(a=>a.node.isConstant());let i=0,s=1;for(const a of r){const{num:o,den:l}=a.node.getRationalValue(),u=i*l+o*a.sign*s,c=s*l;i=u,s=c;const h=Yn(Math.abs(i),Math.abs(s));i/=h,s/=h}return i===0?!1:{terms:e}},(n,e)=>{const{terms:t}=e,r=t.filter(c=>c.node.isConstant()),i=t.filter(c=>!c.node.isConstant()),s=r.map(c=>c.node);let a=0,o=1;for(const c of r){const{num:h,den:f}=c.node.getRationalValue(),d=a*f+h*c.sign*o,p=o*f;a=d,o=p;const m=Yn(Math.abs(a),Math.abs(o));a/=m,o/=m}let l=[...i];if(a!==0||l.length===0){o<0&&(a=-a,o=-o);const c=a>=0?1:-1,h=Math.abs(a);let f;o===1?f=ie.createConstant(h,n.getFontSize(),...s):(f=new Hr({type:"OperatorNode",fn:"divide",args:[{type:"ConstantNode",value:h},{type:"ConstantNode",value:o}]}),f.setFontSize(n.getFontSize()),s.forEach(d=>{d.id&&!f.provenance.includes(d.id)&&f.provenance.push(d.id)})),l.push({node:f,sign:c})}if(l.length===0)return ie.createConstant(0,n.getFontSize(),...s);const u=Ts(l,n.getFontSize());return u&&(s.forEach(c=>{c.id&&!u.provenance.includes(c.id)&&u.provenance.push(c.id)}),u.provenance.push(n.id)),u},(n,e,t)=>{const{terms:r}=e,i=r.filter(h=>h.node.isConstant());let s=0,a=1;for(const h of i){const{num:f,den:d}=h.node.getRationalValue(),p=s*d+f*h.sign*a,m=a*d;s=p,a=m;const y=Yn(Math.abs(s),Math.abs(a));s/=y,a/=y}const o=i.map(h=>{const f=pt(h.node);return h.sign===1?`+ ${f}`:`- ${f}`});o.length>0&&o[0].startsWith("+ ")&&(o[0]=o[0].substring(2));const l=o.join(" "),u=a===1?`${s}`:`${s}/${a}`;let c=`Combining the constant terms: ${l} = ${u}. `;return s===0?c+="Since the constants sum to zero, they are replaced by 0.":c+="The constants are replaced by their sum.",c}),ie.createRule("Combine Like Terms",n=>{if(!ie.isBinaryOp(n,"add")&&!ie.isBinaryOp(n,"subtract"))return!1;const e=[];oi(n,e);const t=new Map,r=[];for(const s of e){const a=ie.isMonomial(s.node);if(a){const o=`${a.variable}^${a.power}`;t.has(o)||t.set(o,[]),t.get(o).push({term:s,monomialInfo:a,originalNodeId:s.node.id})}else r.push(s)}return Array.from(t.values()).some(s=>s.length>1)?{likeTermGroups:t,otherTerms:r}:!1},(n,e)=>{const{likeTermGroups:t,otherTerms:r}=e;let i=[...r];const s=[];oi(n,s);for(const[a,o]of t)if(o.length===1){const l=s.findIndex(u=>u.node.id===o[0].term.node.id);l!==-1?i.splice(l,0,o[0].term):i.push(o[0].term)}else{let l=0;const u=[],c=[],h=o.map(f=>f.term.node.id);for(const f of o){const d=f.monomialInfo.coefficient*f.term.sign;l+=d;const p=Z0(f.term.node);p.coefficientNodes.forEach(m=>{u.includes(m.id)||u.push(m.id)}),p.variableNodes.forEach(m=>{c.includes(m.id)||c.push(m.id)})}if(l!==0){const f=o[0],d=yE(l,f.monomialInfo.variable,f.monomialInfo.power,n.getFontSize(),u,c),p=s.findIndex(m=>h.includes(m.node.id));i=i.filter(m=>!h.includes(m.node.id)),p!==-1?i.splice(p,0,{node:d,sign:1}):i.push({node:d,sign:1})}else i=i.filter(f=>!h.includes(f.node.id))}return i.length===0?ie.createConstant(0,n.getFontSize()):Ts(i,n.getFontSize())},(n,e,t)=>{const{likeTermGroups:r}=e,i=[];for(const[s,a]of r)if(a.length>1){let o=0;const l=[];for(const f of a){const d=f.monomialInfo.coefficient*f.term.sign;o+=d;const p=f.monomialInfo.variable,m=f.monomialInfo.power,y=m!==1?`^${m}`:"";d===1?l.push(`${p}${y}`):d===-1?l.push(`-${p}${y}`):l.push(`${d}${p}${y}`)}const u=a[0].monomialInfo.variable,c=a[0].monomialInfo.power,h=c!==1?`^${c}`:"";if(o===0)i.push(`${l.join(" + ").replace("+ -","- ")} = 0 (like terms cancelled)`);else{const f=o===1?`${u}${h}`:o===-1?`-${u}${h}`:`${o}${u}${h}`;i.push(`${l.join(" + ").replace("+ -","- ")} = ${f}`)}}return i.length===0?"No like terms were found to combine":i.length===1?`Combined like terms: ${i[0]}`:`Combined like terms: ${i.join("; ")}`}),ie.createRule("Multiply Divide Same Factor",n=>{if(ie.isType(n,"omdRationalNode")){const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(ie.isBinaryOp(e,"multiply")&&ie.isType(t,"omdConstantNode")){const r=ie.hasConstantOperand(e);if(r&&r.constant.getValue()===t.getValue())return{pattern:"rational",factor:r.constant.getValue(),expression:r.other,factorNode:r.constant,denominatorNode:t}}}if(ie.isBinaryOp(n,"multiply")){const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;if(ie.isType(t,"omdRationalNode")){const r=ie.unwrapParentheses(t.denominator);if(ie.isType(r,"omdConstantNode")&&e.constant.getValue()===r.getValue())return{pattern:"multiply",factor:e.constant.getValue(),expression:ie.unwrapParentheses(t.numerator),factorNode:e.constant,denominatorNode:r}}}return!1},(n,e)=>{const{expression:t,factorNode:r,denominatorNode:i}=e,s=t.clone();return s.provenance.push(r.id),s.provenance.push(i.id),s.provenance.push(n.id),s},(n,e,t)=>{const{pattern:r,factor:i}=e;return r==="rational"?`Simplified multiplication and division: (${i} × expression)/${i} = expression`:`Simplified multiplication and division: ${i} × (expression/${i}) = expression`})],rational:Bq,parenthesis:Eq,unary:Aq,power:Tq,sqrt:Mq,function:Oq},Pq={omdBinaryExpressionNode:_s.binary,omdRationalNode:_s.rational,omdParenthesisNode:_s.parenthesis,omdUnaryExpressionNode:_s.unary,omdPowerNode:_s.power,omdSqrtNode:_s.sqrt,omdFunctionNode:_s.function};function zq(n){return Pq[n.type]||[]}function Rq(n){const e=[],t=new Set;function r(i){if(!i||t.has(i))return;if(t.add(i),i.childList&&i.childList.length>0)for(const a of i.childList)r(a);const s=zq(i);for(const a of s){const o=a.canApply(i);if(o){e.push({node:i,rule:a,ruleData:o});break}}}return r(n),e}function _a(n){let e=0,t=n,r=null;const i=Rq(n);if(i.length>0){const s=i[0];try{const a=s.rule.apply(s.node,s.ruleData,n);a&&a.success&&a.newRoot&&(t=a.newRoot,e=1,r=a.historyEntry||{name:s.rule.name,affectedNodes:[n.id],message:`Applied ${s.rule.name}`})}catch(a){console.error(`Error applying rule '${s.rule.name}':`,a)}}return{newRoot:t,foldedCount:e,historyEntry:r}}gq(_a);class Ii extends Pt{constructor(e){if(super(e),this.type="omdPowerNode",!e.args||e.args.length!==2){console.error("omdPowerNode requires an AST node with exactly 2 args (base and exponent)",e);return}this.value=this.parseValue(),this.base=this.createOperand(e.args[0]),this.exponent=this.createOperand(e.args[1]),this.argumentNodeList.base=this.base,this.argumentNodeList.exponent=this.exponent}parseValue(){return"^"}createOperand(e){let t=_t(e),r=new t(e);return this.addChild(r),r}computeDimensions(){this.base.computeDimensions(),this.exponent.setFontSize(this.getFontSize()*3/4),this.exponent.computeDimensions();const e=this.base.width+this.exponent.width,t=this.base.height+this.getSuperscriptOffset();this.setWidthAndHeight(e,t)}updateLayout(){const e=this.height-this.base.height;this.base.updateLayout(),this.base.setPosition(0,e);const t=e-this.getSuperscriptOffset();this.exponent.updateLayout(),this.exponent.setPosition(this.base.width,t)}getSuperscriptOffset(){return this.getFontSize()*.4}getAlignmentBaseline(){return this.height-this.base.height+this.base.getAlignmentBaseline()}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Ii(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.base=this.base.clone(),t.exponent=this.exponent.clone(),t.addChild(t.base),t.addChild(t.exponent),t.argumentNodeList.base=t.base,t.argumentNodeList.exponent=t.exponent,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"OperatorNode",op:"^",fn:"pow",args:[this.base.toMathJSNode(),this.exponent.toMathJSNode()]};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.base.toString(),t=this.exponent.toString();let r=e;this.base.needsParentheses&&this.base.needsParentheses()?r=`(${e})`:(this.base.type==="BinaryExpressionNode"||this.base.constructor&&this.base.type==="omdBinaryExpressionNode")&&(r=`(${e})`);let i=t;return(this.exponent.type==="BinaryExpressionNode"||this.exponent.constructor&&this.exponent.type==="omdBinaryExpressionNode"||this.exponent.constructor&&this.exponent.type==="omdPowerNode")&&(i=`(${t})`),`${r}^${i}`}evaluate(e={}){const t=this.base.evaluate?this.base.evaluate(e):this.base.value!==void 0?parseFloat(this.base.value):NaN,r=this.exponent.evaluate?this.exponent.evaluate(e):this.exponent.value!==void 0?parseFloat(this.exponent.value):NaN;return isNaN(t)||isNaN(r)?NaN:Math.pow(t,r)}isSquare(){return this.exponent.value===2||this.exponent.constructor&&this.exponent.type==="omdConstantNode"&&parseFloat(this.exponent.value)===2}isCube(){return this.exponent.value===3||this.exponent.constructor&&this.exponent.type==="omdConstantNode"&&parseFloat(this.exponent.value)===3}static fromString(e){try{const t=window.math.parse(e);if(t.type!=="OperatorNode"||t.op!=="^")throw new Error("Expression is not a power operation");return new Ii(t)}catch(t){throw console.error("Failed to create power node from string:",t),t}}}class sg extends Uo{constructor(e){super(e),this.type="omdGroupNode",this.symbol=this.parseSymbol(e),this.textElement=super.createTextElement(this.symbol)}parseSymbol(e){return e}parseType(){return"parenthesis"}clone(){const e=new sg(this.text);return e.provenance.push(this.id),e}computeDimensions(){super.computeDimensions()}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"SymbolNode",name:this.symbol};return e.clone=function(){return{...this}},e}}class Os extends Pt{constructor(e){super(e),this.type="omdParenthesisNode";const t=e.content||e.args&&e.args[0];if(!t){console.error("omdParenthesisNode requires inner content",e);return}this.open=this.createParenthesis("("),this.expression=this.createExpression(t),this.closed=this.createParenthesis(")"),this.argumentNodeList.expression=this.expression}createParenthesis(e){let t=new sg(e);return this.addChild(t),t}createExpression(e){let t=_t(e),r=new t(e);return this.addChild(r),r}computeDimensions(){this.open.computeDimensions(),this.expression.computeDimensions(),this.closed.computeDimensions();let e=4*this.getFontSize()/this.getRootFontSize(),t=this.open.width+this.expression.width+this.closed.width,r=Math.max(this.expression.height,this.closed.height,this.open.height);this.setWidthAndHeight(t,r+e)}updateLayout(){this.expression.updateLayout();const e=this.expression.getAlignmentBaseline(),r=this.getAlignmentBaseline()-e;this.expression.setPosition(this.open.width,r);const s=r+e-this.open.height/2;this.open.updateLayout(),this.open.setPosition(0,s),this.closed.updateLayout(),this.closed.setPosition(this.open.width+this.expression.width,s)}getAlignmentBaseline(){return(this.height-this.expression.height)/2+this.expression.getAlignmentBaseline()}clone(){const e={type:"ParenthesisNode",content:{type:"ConstantNode",value:1}},t=new Os(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.open=this.open.clone(),t.addChild(t.open),t.expression=this.expression.clone(),t.addChild(t.expression),t.closed=this.closed.clone(),t.addChild(t.closed),t.argumentNodeList={expression:t.expression},t.astNodeData=t.toMathJSNode(),t.provenance.push(this.id),t}isConstant(){return this.expression?this.expression.isConstant():!1}getValue(){if(!this.expression)throw new Error("Parenthesis node has no expression from which to get a value.");return this.expression.getValue()}toMathJSNode(){const e={type:"ParenthesisNode",content:this.expression.toMathJSNode(),id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return this.content&&(t.content=this.content.clone()),t},e}toString(){return`(${this.expression.toString()})`}evaluate(e={}){if(!this.expression)throw new Error("Parenthesis node has no expression to evaluate");if(this.expression.evaluate)return this.expression.evaluate(e);if(this.expression.isConstant())return this.expression.getValue();throw new Error("Cannot evaluate parenthesis content")}isNecessary(){if(!this.parent||this.expression.type==="omdConstantNode"||this.expression.type==="omdVariableNode")return!1;const e=this.parent;if(e.type==="omdFunctionNode")return!0;if(e.type==="omdPowerNode"){if(e.base===this)return this.expression.type==="omdBinaryExpressionNode";if(e.exponent===this)return!(this.expression.type==="omdConstantNode"||this.expression.type==="omdVariableNode")}return e.type==="omdBinaryExpressionNode"&&this.expression.type==="omdBinaryExpressionNode"}static fromString(e){if(!window.math)throw new Error("Math.js is required for parsing expressions");const t=e.trim();if(!t.startsWith("(")||!t.endsWith(")"))throw new Error("Expression must be enclosed in parentheses");try{const r=window.math.parse(t);if(r.type!=="ParenthesisNode")throw new Error("Parsed expression is not a parenthesis node");return new Os(r)}catch(r){throw new Error(`Failed to parse parenthesis expression: ${r.message}`)}}}class Ci extends Pt{constructor(e){var t;if(super(e),this.type="omdBinaryExpressionNode",!((t=e.args)!=null&&t.length)||e.args.length<2)throw new Error(`omdBinaryExpressionNode requires an AST node with at least 2 arguments. Received: ${JSON.stringify(e)}`);if(this.left=this.createExpressionNode(e.args[0]),this.argumentNodeList.left=this.left,this.operation=this.parseOperation(),this.op=e.implicit?null:this.createOperatorNode(e),this.isImplicit=e.implicit||!1,this.right=this.createExpressionNode(e.args[1]),this.argumentNodeList.right=this.right,this.op&&(e.op==="*"||e.op==="×"||e.fn==="multiply")){if(this._shouldReorderMultiplication(this.left,this.right)){const r=this.left;this.left=this.right,this.right=r,this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right;const i=this.astNodeData.args[0];this.astNodeData.args[0]=this.astNodeData.args[1],this.astNodeData.args[1]=i}this._shouldUseImplicitMultiplication(this.left,this.right)&&(this.removeChild(this.op),this.op=null,this.astNodeData.implicit=!0)}}parseOperation(){return this.astNodeData.fn}createExpressionNode(e){let t=_t(e),r=new t(e);return this.addChild(r),r}createOperatorNode(e){let t={type:"OperatorNode",op:e.op};e.operatorProvenance&&(t.provenance=e.operatorProvenance);let r=new ng(t);return this.addChild(r),r}computeDimensions(){var a;this.left.computeDimensions(),(a=this.op)==null||a.computeDimensions(),this.right.computeDimensions();let e=this.left.width+this.right.width+(this.op!==null?this.op.width:0),t=Math.max(this.left.height,this.right.height),r=0*this.getFontSize()/this.getRootFontSize(),i=e+this.getSpacing()*2,s=t+r;this.setWidthAndHeight(i,s)}updateLayout(){const e=this.getSpacing(),t=Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline());let r=0;if(this.left.updateLayout(),this.left.setPosition(r,t-this.left.getAlignmentBaseline()),r+=this.left.width+e,this.op!==null){const i=this.op.getAlignmentBaseline();this.op.updateLayout(),this.op.setPosition(r,t-i),r+=this.op.width+e}this.right.updateLayout(),this.right.setPosition(r,t-this.right.getAlignmentBaseline())}getAlignmentBaseline(){return this.op?Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline())-this.op.getAlignmentBaseline()+this.op.getAlignmentBaseline():Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline())}clone(){const e={type:"OperatorNode",op:"+",args:[{type:"ConstantNode",value:1},{type:"ConstantNode",value:1}]},t=new Ci(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.left=this.left.clone(),t.addChild(t.left),this.op?(t.op=this.op.clone(),t.addChild(t.op)):t.op=null,t.right=this.right.clone(),t.addChild(t.right),t.argumentNodeList={left:t.left,right:t.right},t.operation=this.operation,t.astNodeData=JSON.parse(JSON.stringify(this.astNodeData)),t.provenance.push(this.id),t}getSpacing(){return this.op===null?0:6*this.getFontSize()/this.getRootFontSize()}_shouldUseImplicitMultiplication(e,t){if(!dE())return this._isCoefficientMultiplication(e,t);const r=this._getNodeCategory(e),i=this._getNodeCategory(t),s=`${r}-${i}`;return this._getImplicitMultiplicationSetting(s)}_getImplicitMultiplicationSetting(e){const i=({"variable-constant":"constant-variable","parenthesis-constant":"constant-parenthesis"}[e]||e).replace(/-([a-z])/g,(s,a)=>a.toUpperCase());return dE(i)}_getNodeCategory(e){return e instanceof Zr&&e.isConstant()?"constant":e instanceof Zi?"variable":e instanceof Ii?"power":e instanceof Os?"parenthesis":"other"}_shouldReorderMultiplication(e,t){const r=this._getNodeCategory(e),i=this._getNodeCategory(t);return r!=="constant"&&i==="constant"}_isCoefficientMultiplication(e,t){const r=e instanceof Zr&&e.isConstant(),i=t instanceof Zi||t instanceof Ii||t instanceof Os;return r&&i}toMathJSNode(){const e={type:"OperatorNode",op:this.op?this.op.opName:"*",fn:this.operation,args:[this.left.toMathJSNode(),this.right.toMathJSNode()],implicit:!this.op,id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.left.toString(),t=this.right.toString(),r=this.op?` ${this.op.toString()} `:"";if(!this.op)return`${e}${t}`;const i=this.left.needsParentheses&&this.left.needsParentheses(this.op.value)?`(${e})`:e,s=this.right.needsParentheses&&this.right.needsParentheses(this.op.value)?`(${t})`:t;return`${i}${r}${s}`}evaluate(e={}){const t={add:(a,o)=>a+o,subtract:(a,o)=>a-o,multiply:(a,o)=>a*o,divide:(a,o)=>{if(o===0)throw new Error("Division by zero.");return a/o}},r=this.left.evaluate(e),i=this.right.evaluate(e);if(this.isImplicit)return r*i;const s=t[this.operation];if(s)return s(r,i);throw new Error(`Unsupported operation for evaluation: ${this.operation}`)}needsParentheses(){const e=this.parent;if(!e||!(e instanceof Ci))return!1;const t=this.op?this.op.opName:"*",r=e.op?e.op.opName:"*",i={"+":1,"-":1,"*":2,"×":2,"/":2,"÷":2,"^":3},s=i[t]||0,a=i[r]||0;return s<a||s===a&&e.right===this&&(t==="-"||t==="/"||t==="÷")}getFunctionForOperator(e){return{"+":"add","-":"subtract","*":"multiply","×":"multiply","/":"divide","÷":"divide"}[e]||"unknown"}setHighlight(e=!0,t=omdColor.highlightColor){this.isExplainHighlighted||(super.setHighlight(e,t),this.left&&typeof this.left.setHighlight=="function"&&this.left.setHighlight(e,t),this.op&&typeof this.op.setHighlight=="function"&&this.op.setHighlight(e,t),this.right&&typeof this.right.setHighlight=="function"&&this.right.setHighlight(e,t))}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.left&&typeof this.left.clearProvenanceHighlights=="function"&&this.left.clearProvenanceHighlights(),this.op&&typeof this.op.clearProvenanceHighlights=="function"&&this.op.clearProvenanceHighlights(),this.right&&typeof this.right.clearProvenanceHighlights=="function"&&this.right.clearProvenanceHighlights()}}class Wo extends Pt{constructor(e){var t;super(e),this.type="omdFunctionNode",this.functionName=((t=e.fn)==null?void 0:t.name)||e.name||"f",this.args=e.args||[],this.createTextElements(),this.createArgumentNodes(),this.computeDimensions(),this.updateLayout()}createTextElements(){const e=t=>{const r=new si;return r.setText(t),r.setTextAnchor("start"),r.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(r),r};this.functionNameElement=e(this.functionName),this.openParenElement=e("("),this.closeParenElement=e(")")}createArgumentNodes(){this.argNodes=[],this.commaElements=[],this.argumentNodeList.args=[],this.args.forEach((e,t)=>{const r=_t(e),i=new r(e);if(this.argNodes.push(i),this.addChild(i),this.argumentNodeList.args.push(i),t<this.args.length-1){const s=new si;s.setText(", "),s.setTextAnchor("start"),s.svgObject.setAttribute("dominant-baseline","middle"),this.commaElements.push(s),this.addChild(s)}})}computeDimensions(){const e=this.getFontSize(),t=e*5/6;this.functionNameElement.setFontSize(e),this.openParenElement.setFontSize(e),this.closeParenElement.setFontSize(e),this.argNodes.forEach(p=>{p.setFontSize(t),p.computeDimensions()}),this.commaElements.forEach(p=>{p.setFontSize(t)});const r=e/this.getRootFontSize(),i=2*r,s=2*r,a=Jn(this.functionName,e),o=Jn("(",e),l=Jn(")",e),u=Jn(", ",t);let c=0,h=0;this.argNodes.forEach((p,m)=>{c+=p.width,h=Math.max(h,p.height),m<this.commaElements.length&&(c+=u.width+i)});const f=a.width+s+o.width+c+l.width+i*2,d=Math.max(h,a.height,o.height,l.height)+4*r;this.setWidthAndHeight(f,d)}updateLayout(){const e=this.getFontSize(),t=e*5/6,r=e/this.getRootFontSize(),i=2*r,s=2*r;let a=0;const o=this.height/2;this.functionNameElement.setPosition(a,o),a+=Jn(this.functionName,e).width,a+=s,this.openParenElement.setPosition(a,o),a+=Jn("(",e).width,this.argNodes.forEach((l,u)=>{l.setPosition(a,(this.height-l.height)/2),l.updateLayout(),a+=l.width,u<this.commaElements.length&&(a+=i,this.commaElements[u].setPosition(a,o),a+=Jn(", ",t).width+i)}),this.closeParenElement.setPosition(a,o)}highlightAll(){this.select(),this.argNodes.forEach(e=>{e.highlightAll&&e.highlightAll()})}unhighlightAll(){this.deselect(),this.argNodes.forEach(e=>{e.unhighlightAll&&e.unhighlightAll()})}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Wo(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.functionName=this.functionName,t.args=JSON.parse(JSON.stringify(this.args)),t.createTextElements(),t.argNodes=this.argNodes.map(i=>i.clone()),t.argNodes.forEach(i=>{i.parent=t,t.addChild(i)}),t.argumentNodeList.args=t.argNodes,t.commaElements=this.commaElements.map(i=>{const s=new si;return s.setText(i.text),s.setTextAnchor(i.textAnchor),s.svgObject.setAttribute("dominant-baseline",i.svgObject.getAttribute("dominant-baseline")),s.parent=t,t.addChild(s),s}),t.addChild(t.closedParen),t.argumentNodeList.args=t.args,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"FunctionNode",fn:{type:"SymbolNode",name:this.functionName,clone:function(){return{...this}}},args:this.argNodes.map(t=>t.toMathJSNode())};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),this.fn&&typeof this.fn.clone=="function"&&(t.fn=this.fn.clone()),t},e}toString(){const e=this.argNodes.map(t=>t.toString());return`${this.functionName}(${e.join(", ")})`}evaluate(e={}){const t=this.argNodes.map(r=>{if(r.evaluate)return r.evaluate(e);if(r.type==="omdConstantNode")return parseFloat(r.value);if(r.type==="omdVariableNode"&&e[r.name]!==void 0)return e[r.name];throw new Error(`Cannot evaluate argument: ${r.toString()}`)});if(window.math&&window.math[this.functionName])try{return window.math[this.functionName](...t)}catch(r){throw new Error(`Error evaluating ${this.functionName}: ${r.message}`)}switch(this.functionName){case"sin":return Math.sin(t[0]);case"cos":return Math.cos(t[0]);case"tan":return Math.tan(t[0]);case"asin":return Math.asin(t[0]);case"acos":return Math.acos(t[0]);case"atan":return Math.atan(t[0]);case"sqrt":return Math.sqrt(t[0]);case"abs":return Math.abs(t[0]);case"log":return Math.log(t[0]);case"log10":return Math.log10(t[0]);case"exp":return Math.exp(t[0]);case"pow":return Math.pow(t[0],t[1]);case"min":return Math.min(...t);case"max":return Math.max(...t);case"floor":return Math.floor(t[0]);case"ceil":return Math.ceil(t[0]);case"round":return Math.round(t[0]);default:throw new Error(`Unknown function: ${this.functionName}`)}}static fromString(e){if(!window.math)throw new Error("Math.js is required for parsing function strings");try{const t=window.math.parse(e);if(t.type!=="FunctionNode")throw new Error("String does not represent a function call");return new Wo(t)}catch(t){throw new Error(`Failed to parse function string: ${t.message}`)}}}class ut extends Pt{constructor(e){if(super(e),this.type="omdEquationNode",(e.type||e.mathjs)==="AssignmentNode"){const r=_t(e.object);this.left=new r(e.object);const i=_t(e.value);this.right=new i(e.value),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right}else if(e.args&&e.args.length===2){const r=_t(e.args[0]);this.left=new r(e.args[0]);const i=_t(e.args[1]);this.right=new i(e.args[1]),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right}else this.left=new Pt({type:"SymbolNode",name:"error"}),this.right=new Pt({type:"SymbolNode",name:"error"}),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right;this.equalsSign=new ng({type:"OperatorNode",op:"="}),this.addChild(this.left),this.addChild(this.equalsSign),this.addChild(this.right),this._backgroundStyle=null,this._propagateBackgroundStyle(this._backgroundStyle)}computeDimensions(){this.left.computeDimensions(),this.equalsSign.computeDimensions(),this.right.computeDimensions();const e=8*this.getFontSize()/this.getRootFontSize();let t=this.left.width+this.equalsSign.width+this.right.width+e*2;const r=Math.max(this.left.height,this.equalsSign.height,this.right.height),{padX:i,padY:s}=this._getEffectivePadding(r),a=r+s*2;t+=i*2,this.setWidthAndHeight(t,a)}updateLayout(){this.argumentNodeList={left:this.left,right:this.right};const e=8*this.getFontSize()/this.getRootFontSize(),t=Math.max(this.left.getAlignmentBaseline(),this.equalsSign.getAlignmentBaseline(),this.right.getAlignmentBaseline()),r=Math.max(this.left.height,this.equalsSign.height,this.right.height);let{padX:i,padY:s}=this._getEffectivePadding(r),a=i;if(this.left.updateLayout(),this.left.setPosition(a,s+(t-this.left.getAlignmentBaseline())),a+=this.left.width+e,this.equalsSign.updateLayout(),this.equalsSign.setPosition(a,s+(t-this.equalsSign.getAlignmentBaseline())),a+=this.equalsSign.width+e,this.right.updateLayout(),this.right.setPosition(a,s+(t-this.right.getAlignmentBaseline())),this.computeDimensions(),this._backgroundStyle){const{backgroundColor:f,cornerRadius:d,pill:p}=this._backgroundStyle;if(f&&(this.backRect.setFillColor(f),this.backRect.setOpacity(1),this.defaultOpaqueBack=!0),p===!0){const m=Math.max(0,Math.floor(this.height/2));this.backRect.setCornerRadius(m),this._applyPillToDescendants()}else typeof d=="number"&&this.backRect.setCornerRadius(d);f&&this._matchChildBackgrounds(f)}this.backRect&&(this.width||this.height)&&this.backRect.setWidthAndHeight(this.width,this.height);const o=Math.min(this.left.ypos,this.equalsSign.ypos,this.right.ypos),l=Math.max(this.left.ypos+this.left.height,this.equalsSign.ypos+this.equalsSign.height,this.right.ypos+this.right.height),u=o,c=Math.max(0,(this.height||0)-l);let h=(u-c)/2-.06*this.getFontSize();Math.abs(h)>.01&&(this.left.setPosition(this.left.xpos,this.left.ypos-h),this.equalsSign.setPosition(this.equalsSign.xpos,this.equalsSign.ypos-h),this.right.setPosition(this.right.xpos,this.right.ypos-h))}_getEffectivePadding(e){var l,u;const t=this.getFontSize()/this.getRootFontSize(),r=2*t,i=2*t,s=(l=this._backgroundStyle)==null?void 0:l.padding;let a=(typeof s=="number"?s:s==null?void 0:s.x)??r,o=(typeof s=="number"?s:s==null?void 0:s.y)??i;if(((u=this._backgroundStyle)==null?void 0:u.pill)===!0){const c=Math.ceil((e+2*o)/2);a<c&&(a=c)}return{padX:a,padY:o}}_propagateBackgroundStyle(e,t=new Set){if(t.has(this))return;t.add(this),this._backgroundStyle=e;function r(i,s,a){if(!(!i||a.has(i))){if(a.add(i),i._propagateBackgroundStyle){i._propagateBackgroundStyle(s,a);return}if(i._backgroundStyle=s,Array.isArray(i.childList))for(const o of i.childList)r(o,s,a);if(i.argumentNodeList)for(const o of Object.values(i.argumentNodeList))if(Array.isArray(o))for(const l of o)r(l,s,a);else r(o,s,a)}}if(Array.isArray(this.childList))for(const i of this.childList)r(i,e,t);if(this.argumentNodeList&&typeof this.argumentNodeList=="object")for(const i of Object.values(this.argumentNodeList))if(Array.isArray(i))for(const s of i)r(s,e,t);else r(i,e,t)}_applyPillToDescendants(){const e=new Set,t=Array.isArray(this.childList)?[...this.childList]:[];for(;t.length;){const r=t.pop();if(!(!r||e.has(r))){if(e.add(r),r!==this&&r.backRect&&typeof r.backRect.setCornerRadius=="function"){const i=typeof r.height=="number"&&r.height>0?r.height:0,s=Math.max(0,Math.floor(i/2));r.backRect.setCornerRadius(s)}if(Array.isArray(r.childList))for(const i of r.childList)t.push(i);if(r.argumentNodeList&&typeof r.argumentNodeList=="object")for(const i of Object.values(r.argumentNodeList))Array.isArray(i)?i.forEach(s=>s&&t.push(s)):i&&t.push(i)}}}_createNodeFromValue(e){if(typeof e=="number"){const t=new Zr({value:e});return t.initialize(),t}if(typeof e=="object"&&e!==null){const t=_t(e),r=new t(e);return typeof r.initialize=="function"&&r.initialize(),r}return null}_applyOperation(e,t,r){const i=this._createNodeFromValue(e);if(!i)return this;const s=this._needsParenthesesForOperation(this.left,t),a=this._needsParenthesesForOperation(this.right,t),o=s?{type:"ParenthesisNode",content:this.left.toMathJSNode()}:this.left.toMathJSNode(),l=a?{type:"ParenthesisNode",content:this.right.toMathJSNode()}:this.right.toMathJSNode(),u={type:"OperatorNode",op:t,fn:r,args:[o,i.toMathJSNode()]},c={type:"OperatorNode",op:t,fn:r,args:[l,i.toMathJSNode()]};let h,f;t==="/"?(h=new Hr(u),f=new Hr(c)):(h=new Ci(u),f=new Ci(c));const d={type:"AssignmentNode",object:h.toMathJSNode(),index:null,value:f.toMathJSNode()},p=new ut(d);return p.setFontSize(this.getFontSize()),p.provenance.push(this.id),p.left&&this.left&&this._establishGranularProvenance(p.left,this.left,e,r),p.right&&this.right&&this._establishGranularProvenance(p.right,this.right,e,r),p.initialize(),p}_needsParenthesesForOperation(e,t){if(!e||e.type!=="omdBinaryExpressionNode")return!1;const r={"+":1,"-":1,"*":2,"/":2,"^":3};let i=e.operation;typeof i=="object"&&i&&i.name&&(i=i.name),e.astNodeData&&e.astNodeData.op&&(i=e.astNodeData.op);const s={add:"+",subtract:"-",multiply:"*",divide:"/",pow:"^"},a=s[i]||i,o=s[t]||t;return!r[a]||!r[o]?!0:r[a]<r[o]}addToBothSides(e){return this._applyOperation(e,"+","add")}subtractFromBothSides(e){return this._applyOperation(e,"-","subtract")}multiplyBothSides(e,t){return this._applyOperation(e,"*","multiply",t)}divideBothSides(e){return this._applyOperation(e,"/","divide")}_establishGranularProvenance(e,t,r,i){if(!(!e||!t))if(e.provenance||(e.provenance=[]),i==="divide")if(t.type==="omdBinaryExpressionNode"&&this._isMultiplicationOperation(t)){const s=t.left.isConstant(),a=t.right.isConstant(),o=typeof r=="object"&&r.getValue?r.getValue():r;s&&t.left.getValue()===o?this._copyProvenanceStructure(e,t.right):a&&t.right.getValue()===o?this._copyProvenanceStructure(e,t.left):this._copyProvenanceStructure(e,t)}else this._copyProvenanceStructure(e,t);else i==="multiply"?(this._copyProvenanceStructure(e,t),e.type==="omdBinaryExpressionNode"&&e.left&&this._copyProvenanceStructure(e.left,t)):i==="add"||i==="subtract"?(e.provenance.push(t.id),e.type==="omdBinaryExpressionNode"&&e.left&&this._copyProvenanceStructure(e.left,t)):this._copyProvenanceStructure(e,t)}_isMultiplicationOperation(e){if(e.type!=="omdBinaryExpressionNode")return!1;const t=e.operation;return t==="multiply"||typeof t=="object"&&t&&t.name==="multiply"||e.op&&e.op.opName==="*"}_copyProvenanceStructure(e,t){if(!(!e||!t)){if(e.provenance||(e.provenance=[]),t.provenance&&t.provenance.length>0){const r=new Set(e.provenance);t.provenance.forEach(i=>{r.has(i)||(r.add(i),e.provenance.push(i))})}if(e.provenance.includes(t.id)||e.provenance.push(t.id),e.type===t.type&&e.argumentNodeList&&t.argumentNodeList)for(const r of Object.keys(t.argumentNodeList)){const i=e.argumentNodeList[r],s=t.argumentNodeList[r];if(i&&s)if(Array.isArray(i)&&Array.isArray(s))for(let a=0;a<Math.min(i.length,s.length);a++)i[a]&&s[a]&&this._copyProvenanceStructure(i[a],s[a]);else this._copyProvenanceStructure(i,s)}}}static fromString(e){if(!e.includes("="))throw new Error("Input string is not a valid equation.");const t=e.split("=");if(t.length>2)throw new Error("Equation can only have one '=' sign.");const r=t[0].trim(),i=t[1].trim();if(!r||!i)throw new Error("Equation must have a left and a right side.");const s={type:"AssignmentNode",object:math.parse(r),value:math.parse(i),clone:function(){return{type:this.type,object:this.object.clone(),value:this.value.clone(),clone:this.clone}}};return new ut(s)}clone(){const e=JSON.parse(JSON.stringify(this.astNodeData)),t=new ut(e);return t._syncProvenanceFrom(this),t.setFontSize(this.getFontSize()),t.argumentNodeList={left:t.left,right:t.right},t}deselect(e){e instanceof Pt||(e=this),this===e&&this.parent instanceof Pt&&this.parent.select(e),this.backRect.setFillColor(omdColor.lightGray),this.defaultOpaqueBack==!1&&this.backRect.setOpacity(.01),this.childList.forEach(t=>{t!==e&&t instanceof Pt&&t.deselect(e)})}toMathJSNode(){let e;return this.astNodeData.type==="AssignmentNode"?e={type:"AssignmentNode",object:this.left.toMathJSNode(),value:this.right.toMathJSNode(),id:this.id,provenance:this.provenance}:e={type:"OperatorNode",op:"=",fn:"equal",args:[this.left.toMathJSNode(),this.right.toMathJSNode()],id:this.id,provenance:this.provenance},e.clone=function(){const t={...this};return this.object&&(t.object=this.object.clone()),this.value&&(t.value=this.value.clone()),this.args&&(t.args=this.args.map(r=>r.clone())),t},e}applyFunction(e){const t=this._createFunctionNode(e,this.left),r=this._createFunctionNode(e,this.right),i=this._createNewEquation(t,r);return i.provenance.push(this.id),i}_createFunctionNode(e,t){const r={type:"FunctionNode",fn:{type:"SymbolNode",name:e},args:[t.toMathJSNode()]},i=_t(r),s=new i(r);return s.setFontSize(this.getFontSize()),s}_createNewEquation(e,t){const r={type:"AssignmentNode",object:e.toMathJSNode(),value:t.toMathJSNode(),clone:function(){return{type:this.type,object:this.object.clone(),value:this.value.clone(),clone:this.clone}}};return new ut(r)}applyOperation(e,t,r="both"){const s={add:{op:"+",fn:"add"},subtract:{op:"-",fn:"subtract"},multiply:{op:"*",fn:"multiply"},divide:{op:"/",fn:"divide"}}[t];if(!s)throw new Error(`Unknown operation: ${t}`);if(r==="both")return this._applyOperation(e,s.op,s.fn);const a=this._createNodeFromValue(e);if(!a)throw new Error("Invalid value provided");let o,l;if(r==="left"){const p=this._needsParenthesesForOperation(this.left,s.op)?{type:"ParenthesisNode",content:this.left.toMathJSNode()}:this.left.toMathJSNode();o={type:"OperatorNode",op:s.op,fn:s.fn,args:[p,a.toMathJSNode()]},l=this.right.toMathJSNode()}else if(r==="right"){const p=this._needsParenthesesForOperation(this.right,s.op)?{type:"ParenthesisNode",content:this.right.toMathJSNode()}:this.right.toMathJSNode();o=this.left.toMathJSNode(),l={type:"OperatorNode",op:s.op,fn:s.fn,args:[p,a.toMathJSNode()]}}else throw new Error(`Invalid side: ${r}. Must be 'left', 'right', or 'both'`);let u,c;r==="left"&&s.op==="/"?(u=new Hr(o),c=_t(l)===Pt?this.right:new(_t(l))(l)):r==="right"&&s.op==="/"?(u=_t(o)===Pt?this.left:new(_t(o))(o),c=new Hr(l)):r==="left"?(u=new Ci(o),c=_t(l)===Pt?this.right:new(_t(l))(l)):(u=_t(o)===Pt?this.left:new(_t(o))(o),c=new Ci(l));const h={type:"AssignmentNode",object:u.toMathJSNode(),value:c.toMathJSNode()},f=new ut(h);return f.setFontSize(this.getFontSize()),f.provenance.push(this.id),f.initialize(),f}swapSides(){const e=this.clone();return[e.left,e.right]=[e.right,e.left],[e.astNodeData.object,e.astNodeData.value]=[e.astNodeData.value,e.astNodeData.object],e.provenance.push(this.id),e.initialize(),e}toString(){return`${this.left.toString()} = ${this.right.toString()}`}setBackgroundStyle(e={}){this._backgroundStyle={...this._backgroundStyle||{},...e},this._propagateBackgroundStyle(this._backgroundStyle),this.backRect&&(this.width||this.height)&&this.updateLayout()}getEqualsAnchorX(){var i,s,a,o;const e=8*this.getFontSize()/this.getRootFontSize(),t=Math.max(((i=this.left)==null?void 0:i.height)||0,((s=this.equalsSign)==null?void 0:s.height)||0,((a=this.right)==null?void 0:a.height)||0),{padX:r}=this._getEffectivePadding(t);return r+this.left.width+e+(((o=this.equalsSign)==null?void 0:o.width)||0)/2}getBackgroundPaddingX(){var t;const e=(t=this._backgroundStyle)==null?void 0:t.padding;return e==null?0:typeof e=="number"?e:e.x??0}getEffectiveBackgroundPaddingX(){var r,i,s;const e=Math.max(((r=this.left)==null?void 0:r.height)||0,((i=this.equalsSign)==null?void 0:i.height)||0,((s=this.right)==null?void 0:s.height)||0),{padX:t}=this._getEffectivePadding(e);return t}_matchChildBackgrounds(e){const t=new Set,r=Array.isArray(this.childList)?[...this.childList]:[];for(;r.length;){const i=r.pop();if(!(!i||t.has(i))){if(t.add(i),i!==this&&i.backRect&&(i.backRect.setFillColor(e),i.backRect.setOpacity(1)),Array.isArray(i.childList))for(const s of i.childList)r.push(s);if(i.argumentNodeList&&typeof i.argumentNodeList=="object")for(const s of Object.values(i.argumentNodeList))Array.isArray(s)?s.forEach(a=>a&&r.push(a)):s&&r.push(s)}}}evaluate(e={}){const t=this.left.evaluate(e),r=this.right.evaluate(e);return{left:t,right:r}}renderTo(e,t={}){const i={...{side:"both",xMin:-10,xMax:10,yMin:-10,yMax:10,stepSize:1},...t};switch(e.toLowerCase()){case"graph":return this._renderToGraph(i);case"table":return this._renderToTable(i);case"hanger":return this._renderToHanger(i);case"tileequation":{const s=this.getLeft().toString(),a=this.getRight().toString(),o=`${s}=${a}`,l=i.plusColor||"#79BBFD",u=i.equalsColor||"#FF6B6B",c=i.xPillColor,h=i.tileBackgroundColor,f=i.dotColor,d=i.tileSize||28,p=i.dotsPerColumn||10;return{omdType:"tileEquation",equation:o,tileSize:d,dotsPerColumn:p,plusColor:l,equalsColor:u,xPill:c?{color:c}:void 0,numberTileDefaults:{backgroundColor:h,dotColor:f}}}default:throw new Error(`Unknown visualization type: ${e}. Supported types are: graph, table, hanger`)}}getLeft(){return this.left}getRight(){return this.right}_renderToGraph(e){const t=this._normalizeExpressionString(this.getLeft().toString()),r=this._normalizeExpressionString(this.getRight().toString());let i=[];const s=a=>a.trim().toLowerCase()==="y";if(e.side==="left")s(t)||i.push({equation:`y = ${t}`,domain:{min:e.xMin,max:e.xMax},color:"blue",strokeWidth:2});else if(e.side==="right")s(r)||i.push({equation:`y = ${r}`,domain:{min:e.xMin,max:e.xMax},color:"red",strokeWidth:2});else if(s(t)||i.push({equation:`y = ${t}`,domain:{min:e.xMin,max:e.xMax},color:"blue",strokeWidth:2}),!s(r)){const a=s(t)?"blue":"red";i.push({equation:`y = ${r}`,domain:{min:e.xMin,max:e.xMax},color:a,strokeWidth:2})}return{omdType:"coordinatePlane",xMin:e.xMin,xMax:e.xMax,yMin:e.yMin,yMax:e.yMax,xLabel:e.xLabel!==void 0?e.xLabel:"x",yLabel:e.yLabel!==void 0?e.yLabel:"y",size:e.size!==void 0?e.size:"medium",tickInterval:e.tickInterval!==void 0?e.tickInterval:1,forceAllTickLabels:e.forceAllTickLabels!==void 0?e.forceAllTickLabels:!0,showTickLabels:e.showTickLabels!==void 0?e.showTickLabels:!0,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,graphEquations:i,lineSegments:[],dotValues:[],shapeSet:[]}}_renderToTable(e){const t=p=>{const m=this._normalizeExpressionString(p);return/^[a-zA-Z]\s*=/.test(m)?m:`y = ${m}`};if(e.side==="left"){const p=this._normalizeExpressionString(this.getLeft().toString()),m=t(p);return{omdType:"table",title:`Function Table: ${m}`,headers:["x","y"],equation:m,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}else if(e.side==="right"){const p=this._normalizeExpressionString(this.getRight().toString()),m=t(p);return{omdType:"table",title:`Function Table: ${m}`,headers:["x","y"],equation:m,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}const r=this._normalizeExpressionString(this.getLeft().toString()),i=this._normalizeExpressionString(this.getRight().toString());if(r.toLowerCase().trim()==="y"){const p=t(i);return{omdType:"table",title:`Function Table: ${p}`,headers:["x","y"],equation:p,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}if(i.toLowerCase().trim()==="y"){const p=t(r);return{omdType:"table",title:`Function Table: ${p}`,headers:["x","y"],equation:p,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}const s=this.getLeft(),a=this.getRight(),o=s.toString(),l=a.toString(),u=["x",o,l],c=[],h=e.xMin,f=e.xMax,d=e.stepSize||1;for(let p=h;p<=f;p+=d)try{const m=s.evaluate({x:p}),y=a.evaluate({x:p});isFinite(m)&&isFinite(y)&&c.push([p,Number(m),Number(y)])}catch{}return{omdType:"table",title:`Equation Table: ${this.toString()}`,headers:u,data:c,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}_renderSingleSideTable(e,t,r={}){const i=this._normalizeExpressionString(e.toString());return{omdType:"table",title:`${t}: ${i}`,headers:["x","y"],equation:`y = ${i}`,xMin:r.xMin??-5,xMax:r.xMax??5,stepSize:r.stepSize??1}}_renderToHanger(e={}){const t=this._convertToHangerValues(this.getLeft()),r=this._convertToHangerValues(this.getRight());return{omdType:"balanceHanger",leftValues:t,rightValues:r,tilt:"none",backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0}}_normalizeExpressionString(e){return!e||typeof e!="string"?String(e||""):e.replace(/(\d)([a-zA-Z])/g,"$1*$2").replace(/([a-zA-Z])(\d)/g,"$1*$2")}_convertToHangerValues(e){const t=[];if(e.type==="omdConstantNode"){const r=e.getValue();r!==0&&t.push(r)}else if(e.type==="omdVariableNode")t.push(e.name||"x");else if(e.type==="omdBinaryExpressionNode"){const r=this._convertToHangerValues(e.left),i=this._convertToHangerValues(e.right);if(e.operation==="add"||e.operation==="plus")t.push(...r,...i);else if(e.operation==="subtract"||e.operation==="minus"){t.push(...r);for(const s of i)typeof s=="number"?t.push(-s):t.push(`-${s}`)}else if(e.operation==="multiply")if(e.left.type==="omdConstantNode"&&e.right.type==="omdVariableNode"){const s=Math.abs(e.left.getValue()),a=e.right.name||"x";for(let o=0;o<s;o++)t.push(a)}else if(e.right.type==="omdConstantNode"&&e.left.type==="omdVariableNode"){const s=Math.abs(e.right.getValue()),a=e.left.name||"x";for(let o=0;o<s;o++)t.push(a)}else t.push(e.toString());else t.push(e.toString())}else t.push(e.toString());return t}}function Lq(n,e){var t,r;switch(n){case"AssignmentNode":return ut;case"OperatorNode":return(e==null?void 0:e.op)==="-"&&e.args.length===1&&!e.implicit?Qi:(e==null?void 0:e.op)==="="?ut:(e==null?void 0:e.op)==="^"?Ii:(e==null?void 0:e.op)==="/"?Hr:Ci;case"ParenthesisNode":return Os;case"ConstantNode":return Zr;case"SymbolNode":return Zi;case"FunctionNode":return(((t=e==null?void 0:e.fn)==null?void 0:t.name)==="multiply"||(e==null?void 0:e.name)==="multiply")&&e.implicit?Ci:((r=e==null?void 0:e.fn)==null?void 0:r.name)==="sqrt"||(e==null?void 0:e.name)==="sqrt"?Fs:Wo;default:return Pt}}function _t(n){let e=n.type;return n.mathjs&&(e=n.mathjs),Lq(e,n)}function Jn(n,e){const t=document.createElement("span");t.style.visibility="hidden",t.style.position="absolute",t.style.whiteSpace="nowrap",t.style.fontFamily="Albert Sans",t.style.fontSize=`${e||16}px`,t.textContent=n,document.body.appendChild(t);const r=t.offsetWidth,i=t.offsetHeight;return document.body.removeChild(t),{width:r,height:i}}const Zo=class Zo extends Pt{constructor(e,t){super({}),this.operation=e,this.value=t,this.type="omdOperationDisplayNode",this._initializeDisplay(),this._createOperationElements(),this._disableAllInteractions(),this._addChildElements()}_initializeDisplay(){this.hideBackgroundByDefault(),this.backRect&&(this.backRect.setOpacity(0),this.backRect.setFillColor("transparent")),this._makeNodeNonHighlightable()}_createOperationElements(){const t=`${this._getOperatorSymbol(this.operation)}${this._valueToString(this.value)}`;this.leftToken=new Zi(t),this.rightToken=new Zi(t),typeof this.leftToken.initialize=="function"&&this.leftToken.initialize(),typeof this.rightToken.initialize=="function"&&this.rightToken.initialize();const r=typeof this.getFontSize=="function"?this.getFontSize():null;r&&typeof this.leftToken.setFontSize=="function"&&this.leftToken.setFontSize(r),r&&typeof this.rightToken.setFontSize=="function"&&this.rightToken.setFontSize(r),[this.leftToken,this.rightToken].forEach(i=>{this._disableHighlighting(i)})}_disableAllInteractions(){[this.leftToken,this.rightToken].forEach(e=>{this._disableElement(e)})}_addChildElements(){this.addChild(this.leftToken),this.addChild(this.rightToken)}_getOperatorSymbol(e){return Zo.OPERATOR_SYMBOLS[e]||""}_createValueElement(e){return new Zi(this._valueToString(e))}_valueToString(e){if(e instanceof Pt)return e.toString();if(typeof e=="object"&&e!==null)try{const t=_t(e),r=new t(e);return typeof r.initialize=="function"&&r.initialize(),r.toString()}catch{return String(e??"")}return String(e??"")}_disableElement(e){e&&(this._hideElementBackground(e),this._disableMouseInteractions(e),this._disableHighlighting(e),this._disableChildElements(e))}_hideElementBackground(e){e.backRect&&(e.hideBackgroundByDefault(),e.backRect.setOpacity(0))}_disableMouseInteractions(e){e.svgObject&&(e.svgObject.onmouseenter=null,e.svgObject.onmouseleave=null,e.svgObject.style.cursor="default")}_disableHighlighting(e){e.setHighlight=()=>{},e.lowlight=()=>{},e.setFillColor=()=>{},e.backRect&&(e.backRect.setOpacity(0),e.backRect.setFillColor("transparent"),e.backRect.setFillColor=()=>{},e.backRect.setOpacity=()=>{})}_makeNodeNonHighlightable(){this.setHighlight=()=>{},this.lowlight=()=>{},this.setFillColor=()=>{},this.backRect&&(this.backRect.setOpacity(0),this.backRect.setFillColor("transparent"),this.backRect.setFillColor=()=>{},this.backRect.setOpacity=()=>{})}_disableChildElements(e){e.childList&&e.childList.forEach(r=>this._disableElement(r)),["left","right","base","exponent","argument","expression","numerator","denominator"].forEach(r=>{e[r]&&this._disableElement(e[r])})}computeDimensions(){this.leftToken&&typeof this.leftToken.updateLayout=="function"&&this.leftToken.updateLayout(),this.rightToken&&typeof this.rightToken.updateLayout=="function"&&this.rightToken.updateLayout();const e=this.leftToken?this.leftToken.width:0,t=this.rightToken?this.rightToken.width:0,r=typeof this.gap=="number"?this.gap:45;this.gap=r,this.leftClusterWidth=e;const i=Math.max(this.leftToken?this.leftToken.height:0,this.rightToken?this.rightToken.height:0),s=6,a=e+r+t,o=i+s*2;this.setWidthAndHeight(a,o)}updateLayout(){[this.leftToken,this.rightToken].forEach(i=>{i.updateLayout()}),this.computeDimensions();const e=this.gap||30,t=this.leftToken.width;let r=0;this.leftToken.setPosition(r,(this.height-this.leftToken.height)/2),r=t+e,this.rightToken.setPosition(r,(this.height-this.rightToken.height)/2),this.rightToken.show(),this._makeNodeNonHighlightable(),super.updateLayout()}getLeftWidthForAlignment(){return typeof this.leftClusterWidth!="number"&&this.computeDimensions(),this.leftClusterWidth||0}showLeftOnly(){this.rightToken.hide();const e=this.leftToken.width,t=typeof this.getFontSize=="function"?this.getFontSize():32,r=this.leftToken.height,i=Math.ceil(t*.35);this.setWidthAndHeight(e,r+i*2),this.leftToken.setPosition(0,(this.height-this.leftToken.height)/2)}clone(){const e=new Zo(this.operation,this.value);return e.provenance.push(this.id),e._makeNodeNonHighlightable(),e}};eu(Zo,"OPERATOR_SYMBOLS",{add:"+",subtract:"-",multiply:"×",divide:"÷"});let Bs=Zo;const es=class es extends Pt{setAlignmentMode(e){e!=="equals"&&e!=="center"?(console.warn(`Invalid alignment mode: ${e}. Using 'equals'.`),this.alignmentMode="equals"):this.alignmentMode=e,this.steps&&this.steps.length>0&&this.updateLayout()}getAlignmentMode(){return this.alignmentMode||"equals"}setFilterLevel(e=0){this.currentFilterLevels=[e],this.updateStepsVisibility(t=>(t.stepMark??0)===e)}setFilterLevels(e=[0]){this.currentFilterLevels=[...e],this.updateStepsVisibility(t=>{const r=t.stepMark??0;return e.includes(r)})}_reapplyCurrentFilter(){this.currentFilterLevels&&this.currentFilterLevels.length>0&&this.updateStepsVisibility(e=>{const t=e.stepMark??0;return this.currentFilterLevels.includes(t)})}getFilterLevel(){return 0}constructor(e){super({}),this.type="omdEquationSequenceNode",this.steps=e,this.argumentNodeList.steps=this.steps,this.steps.forEach(t=>this.addChild(t)),this._initializeState(),this._initializeLayout(),this._initializeNodeMap(),this._disableContainerInteractions(),this._markInitialSteps(),this._applyDefaultFilter(),this.defaultEquationBackground=null}_initializeState(){this.currentStepIndex=0,this.stepDescriptions=[],this.importanceLevels=[],this.simplificationHistory=[],this.currentFilterLevels=[0]}_initializeLayout(){this.hideBackgroundByDefault(),this.layoutHelper=new qr,this.layoutHelper.setSpacer(15),this.alignmentMode="equals"}_initializeNodeMap(){this.nodeMap=new Map,this.rebuildNodeMap()}_disableContainerInteractions(){this.svgObject.onmouseenter=null,this.svgObject.onmouseleave=null,this.svgObject.style.cursor="default",this.svgObject.onclick=null}_markInitialSteps(){!this.steps||!Array.isArray(this.steps)||this.steps.forEach((e,t)=>{e instanceof ut&&(e.stepMark=0)})}_applyDefaultFilter(){this.steps&&Array.isArray(this.steps)&&this.steps.length>0&&this.updateStepsVisibility(e=>(e.stepMark??0)===0)}getCurrentEquation(){if(!this.steps||this.steps.length===0)return null;for(let e=this.steps.length-1;e>=0;e--)if(this.steps[e]instanceof ut)return this.steps[e];return null}addStep(e,t,r){let i={};typeof t=="string"?i={description:t,stepMark:r??2}:t&&(i=t);const s=typeof e=="string"?this._stringToNode(e):e,a=this.steps.length;return i.description!==void 0&&(this.stepDescriptions[a]=i.description),i.stepMark!==void 0?this.importanceLevels[a]=i.stepMark:this.importanceLevels[a]=0,this.defaultEquationBackground&&typeof(s==null?void 0:s.setBackgroundStyle)=="function"&&s.setBackgroundStyle(this.defaultEquationBackground),s.setFontSize(this.getFontSize()),s.initialize(),this.steps.push(s),this.addChild(s),this.argumentNodeList.steps=this.steps,this.rebuildNodeMap(),s instanceof ut?s.stepMark=i.stepMark??this._determineStepMark(s,i):i.stepMark!==void 0?s.stepMark=i.stepMark:s.stepMark=0,this.computeDimensions(),this.updateLayout(),window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),this._reapplyCurrentFilter(),a}setDefaultEquationBackground(e=null){this.defaultEquationBackground=e,e&&((this.steps||[]).forEach(t=>{typeof(t==null?void 0:t.setBackgroundStyle)=="function"&&t.setBackgroundStyle(e)}),this.computeDimensions(),this.updateLayout())}_determineStepMark(e,t){return t.isSimplification?2:this._isFullySimplified(e)?0:2}_isFullySimplified(e){if(!(e instanceof ut))return!1;const t=this._isSimpleExpression(e.left),r=this._isSimpleExpression(e.right);return t&&r}_isSimpleExpression(e){return e.isConstant()||e.type==="omdVariableNode"?!0:e.type==="omdBinaryExpressionNode"?this._isSimpleExpression(e.left)&&this._isSimpleExpression(e.right):!1}rebuildNodeMap(){this.nodeMap||(this.nodeMap=new Map);const e=new Map;this.steps.forEach((t,r)=>{t.findAllNodes().forEach(s=>{e.set(s.id,s)})}),e.set(this.id,this),this.preserveProvenanceHistory(e),this.nodeMap=e}preserveProvenanceHistory(e){const t=this._collectAllProvenanceIds(e);this._preserveReferencedNodes(t,e)}_collectAllProvenanceIds(e){const t=new Set,r=new Set;return e.forEach(i=>this._collectNodeProvenanceIds(i,t,r)),t}_collectNodeProvenanceIds(e,t,r){var i;!e||!e.id||r.has(e.id)||(r.add(e.id),((i=e.provenance)==null?void 0:i.length)>0&&e.provenance.forEach(s=>t.add(s)),e.argumentNodeList&&Object.values(e.argumentNodeList).flat().forEach(s=>{this._collectNodeProvenanceIds(s,t,r)}))}_preserveReferencedNodes(e,t){const r=new Set;e.forEach(i=>this._preserveNodeAndContext(i,t,r))}_preserveNodeAndContext(e,t,r){var s,a;if(r.has(e)||t.has(e)||!((s=this.nodeMap)!=null&&s.has(e)))return;r.add(e);const i=this.nodeMap.get(e);t.set(e,i),((a=i.provenance)==null?void 0:a.length)>0&&i.provenance.forEach(o=>{this._preserveNodeAndContext(o,t,r)}),this._preserveParentContext(i,t),this._preserveSiblingContext(i,t)}_preserveParentContext(e,t){let r=e.parent;for(;r&&r.id;)!t.has(r.id)&&this.nodeMap.has(r.id)&&t.set(r.id,this.nodeMap.get(r.id)),r=r.parent}_preserveSiblingContext(e,t){var r;(r=e.parent)!=null&&r.argumentNodeList&&Object.values(e.parent.argumentNodeList).flat().forEach(i=>{i&&i.id&&!t.has(i.id)&&this.nodeMap.has(i.id)&&t.set(i.id,this.nodeMap.get(i.id))})}recordSimplificationHistory(e,t,r,i={}){const s={name:e,affectedNodes:[...t],message:r,stepNumber:this.steps.length,...i};this.simplificationHistory.push(s)}getSimplificationHistory(){return[...this.simplificationHistory]}clearSimplificationHistory(){this.simplificationHistory=[]}setFontSize(e){super.setFontSize(e),this.steps.forEach(t=>{t.setFontSize(e)}),this.computeDimensions(),this.updateLayout()}refresh(e,t=!0){this.computeDimensions(),this.updateLayout(),e.render(this),t&&e.centerNode()}applyEquationOperation(e,t){if(!es.OPERATION_MAP[t])return console.error(`Invalid operation: ${t}`),this;const r=this.getCurrentEquation();if(!r)return console.error("No equation to apply operation to."),this;let i=e;if(typeof e=="string"){if(!window.math)throw new Error("Math.js is required for parsing expressions");i=isNaN(e)?window.math.parse(e):parseFloat(e)}const s=new Bs(t,e);this.addStep(s,{stepMark:0});const a=r.clone(),o=es.OPERATION_MAP[t],l=a[o](i,s.id),u=l.clone(),{foldedCount:c}=_a(u),h=c===0;return this.addStep(l,{stepMark:h?0:1,description:this._getOperationDescription(t,e,!h)}),this}_getOperationDescription(e,t,r){const s={add:`Added ${t} to both sides`,subtract:`Subtracted ${t} from both sides`,multiply:`Multiplied both sides by ${t}`,divide:`Divided both sides by ${t}`}[e]||`Applied ${e} with ${t}`;return r?`${s} (unsimplified)`:s}applyEquationFunction(e){const t=this.getCurrentEquation();if(!t)throw new Error("No equation found in sequence to operate on");const i=t.clone().applyFunction(e),s=i.clone(),{foldedCount:a}=_a(s),o=a===0?0:1,l=`Applied ${e} to both sides`;return this.addStep(i,{stepMark:o,description:l}),this}simplify(){const e=this.steps[this.steps.length-1];if(!e)return{success:!1,message:"No expression found to simplify"};try{const t=e.clone(),r=_a(t);return r.foldedCount>0?this._handleSuccessfulSimplification(e,r):{success:!1,foldedCount:0,message:"No simplifications available"}}catch(t){return console.error("Error during simplification:",t),{success:!1,message:`Simplification error: ${t.message}`}}}_handleSuccessfulSimplification(e,{newRoot:t,foldedCount:r,historyEntry:i}){i&&(i.stepNumber=this.steps.length-1,i.originalStep=e.toString(),this.simplificationHistory.push(i));const s=t.clone(),{foldedCount:a}=_a(s),o=a===0,l=o?`Fully simplified result (${r} operation${r>1?"s":""} applied)`:`Simplification step (${r} operation${r>1?"s":""} applied)`;this.addStep(t,{stepMark:o?0:2,description:l,isSimplification:!0});const u=o?`Fully simplified! Applied ${r} simplification step(s).`:`Simplified! Applied ${r} simplification step(s), more are available.`;return{success:!0,foldedCount:r,isFinalSimplification:o,message:u}}simplifyAll(e=50){let t=0,r,i=0;do r=this.steps.length,this.simplify().success&&i++,t++;while(this.steps.length>r&&t<e);return t>=e?{success:!1,totalSteps:i,iterations:t,message:`Stopped after ${e} iterations to avoid an infinite loop.`}:{success:!0,totalSteps:i,iterations:t,message:`All possible simplifications completed. Added ${i} simplification steps.`}}evaluate(e={}){const t=this.getCurrentStep();if(!t||typeof t.evaluate!="function"){console.warn("Evaluation not supported for the current step.");return}try{const r=t.evaluate(e);if(typeof r=="object"&&r.left!==void 0&&r.right!==void 0){const{left:i,right:s}=r,a=Math.abs(i-s)<1e-9}}catch(r){console.error("Evaluation failed:",r.message)}}validateSequenceProvenance(){const e=[];return this._validateStepsProvenance(e),this._findOrphanedNodes(e),e}_validateStepsProvenance(e){this.steps.forEach((t,r)=>{t.validateProvenance(this.nodeMap).forEach(s=>e.push({...s,stepIndex:r}))})}_findOrphanedNodes(e){const t=new Set(this.steps.flatMap(i=>i.findAllNodes().map(s=>s.id))),r=this._collectAllProvenanceIds(this.nodeMap);this.nodeMap.forEach((i,s)=>{!t.has(s)&&!r.has(s)&&e.push({type:"orphaned_node",nodeId:s,nodeType:i.type})})}select(){}deselect(){}highlight(e){this.childList.forEach(t=>{t instanceof kt&&t!==this.backRect&&t.highlight(e)})}clearProvenanceHighlights(){this.childList.forEach(e=>{e instanceof kt&&typeof e.clearProvenanceHighlights=="function"&&e!==this.backRect&&e.clearProvenanceHighlights()})}computeDimensions(){const e=this.steps.filter(i=>i.visible!==!1);if(e.length===0){this.setWidthAndHeight(0,0);return}e.forEach(i=>i.computeDimensions()),this.alignPointX=this._calculateAlignmentPoint(e);const{maxWidth:t,totalHeight:r}=this._calculateTotalDimensions(e);this.setWidthAndHeight(t,r)}_calculateAlignmentPoint(e){const t=[];return e.forEach(r=>{if(r instanceof ut){if(typeof r.getEqualsAnchorX=="function")t.push(r.getEqualsAnchorX());else if(r.equalsSign&&r.left){const i=8*r.getFontSize()/r.getRootFontSize();t.push(r.left.width+i+r.equalsSign.width/2)}}}),t.length>0?Math.max(...t):0}_calculateTotalDimensions(e){let t=0,r=0;const i=15*this.getFontSize()/this.getRootFontSize();return e.forEach((s,a)=>{let o=0;s instanceof ut?o=this.alignPointX+s.equalsSign.width+s.right.width:o=s.width,t=Math.max(t,o),r+=s.height,a<e.length-1&&(r+=i)}),{maxWidth:t,totalHeight:r}}_computeStepXOffset(e){if(this.alignmentMode==="center")return(this.width-e.width)/2;if(e instanceof ut){const t=typeof e.getEqualsAnchorX=="function"?e.getEqualsAnchorX():e.left.width;return this.alignPointX-t}if(e instanceof Bs){const t=typeof e.getLeftWidthForAlignment=="function"?e.getLeftWidthForAlignment():e.width/2,r=(typeof e.gap=="number"?e.gap:0)/2;return this.alignPointX-(t+r)}return(this.width-e.width)/2}updateLayout(){const e=15*this.getFontSize()/this.getRootFontSize(),t=this.steps.filter(i=>i.visible!==!1);t.forEach(i=>i.updateLayout()),this.alignPointX=this._calculateAlignmentPoint(t);let r=0;t.forEach((i,s)=>{const a=this._computeStepXOffset(i);i.setPosition(a,r),r+=i.height,s<t.length-1&&(r+=e)})}static fromStringArray(e){const t=e.map(r=>{const i=r.trim();if(i.includes("="))return ut.fromString(i);throw new Error(`Step string "${i}" is not a valid equation for omdEquationSequenceNode.`)});return new es(t)}clone(){const e=this.steps.map(r=>r.clone()),t=new es(e);return t.provenance.push(this.id),t.nodeMap=new Map,t.findAllNodes().forEach(r=>t.nodeMap.set(r.id,r)),t}toMathJSNode(){return this.steps[this.steps.length-1].toMathJSNode()}getCurrentStep(){var t;if(!this.steps||this.steps.length===0)return null;let e=-1;for(let r=this.steps.length-1;r>=0;r--){const i=this.steps[r];if(i&&i.visible!==!1){if(((t=i.constructor)==null?void 0:t.name)==="omdEquationNode"){e=r;break}e===-1&&(e=r)}}return e===-1&&(e=this.steps.length-1),e<0&&(e=0),e>=this.steps.length&&(e=this.steps.length-1),this.currentStepIndex=e,this.steps[e]}navigateToStep(e){return e<0||e>=this.steps.length?!1:(this.currentStepIndex=e,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0)}nextStep(){return this.currentStepIndex<this.steps.length-1?(this.currentStepIndex++,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0):!1}previousStep(){return this.currentStepIndex>0?(this.currentStepIndex--,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0):!1}getFilteredSteps(e){const t=[];return this.steps.forEach((r,i)=>{const s=this.importanceLevels[i]!==void 0?this.importanceLevels[i]:r.stepMark!==void 0?r.stepMark:0;s<=e&&t.push({step:r,description:this.stepDescriptions[i]||"",importance:s,index:i})}),t}renderCurrentStep(){const e=this.getCurrentStep();if(!e)return new jsvgGroup().svgObject;const t=new jsvgGroup;e.computeDimensions(),e.updateLayout();const r=e.render();return t.addChild(r),t.svgObject}toString(){return this.steps.length===0?"":this.steps.map((e,t)=>{const r=this.stepDescriptions[t]?` (${this.stepDescriptions[t]})`:"";return`Step ${t+1}: ${e.toString()}${r}`}).join("\\n")}clear(){this.steps.forEach(e=>{this.removeChild(e)}),this.steps=[],this.stepDescriptions=[],this.importanceLevels=[],this.argumentNodeList.steps=[],this.currentStepIndex=0,this.clearSimplificationHistory(),this.rebuildNodeMap(),this.computeDimensions(),this.updateLayout(),window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters()}static fromSteps(e){if(!Array.isArray(e))throw new Error("fromSteps requires an array of expression strings");const t=new es([]);return e.forEach((r,i)=>{const s=r.trim();let a;if(s.includes("="))a=ut.fromString(s);else{if(!window.math)throw new Error("Math.js is required for parsing expressions");const o=window.math.parse(s),l=_t(o);a=new l(o)}t.addStep(a,{stepMark:0,description:""})}),t}_stringToNode(e){const t=e.trim();if(t.includes("="))return ut.fromString(t);if(!window.math)throw new Error("Math.js is required for parsing expressions");const r=window.math.parse(t),i=_t(r);return new i(r)}show(){super.show(),this.layoutManager&&this.layoutManager.updateVisualVisibility()}hide(){super.hide(),this.layoutManager&&this.layoutManager.updateVisualVisibility()}updateStepsVisibility(e){!this.steps||!Array.isArray(this.steps)||(this.steps.forEach(t=>{if(!t)return;e(t)?(t.visible=!0,t.svgObject&&(t.svgObject.style.display="")):(t.visible=!1,t.svgObject&&(t.svgObject.style.display="none"));const r=wq(t.stepMark??0);t.svgObject&&(t.svgObject.style.fontWeight=r.toString())}),this.layoutManager&&this.layoutManager.updateVisualVisibility(),this.computeDimensions(),this.updateLayout())}};eu(es,"OPERATION_MAP",{add:"addToBothSides",subtract:"subtractFromBothSides",multiply:"multiplyBothSides",divide:"divideBothSides"});let jo=es;class je{static isLeafNode(e){if(!e)return!1;const t=["omdConstantNode","omdVariableNode","omdOperatorNode"];return!!(e.constructor&&t.includes(e.type)||e.type==="constant"||e.type==="variable"||e.type==="operator"||!e.left&&!e.right&&!e.argument&&!e.expression)}static isBinaryNode(e){return e?e.type==="omdBinaryExpressionNode"&&e.left&&e.right:!1}static isUnaryNode(e){return e?e.type==="omdUnaryExpressionNode"&&e.argument:!1}static hasExpression(e){return e?e.expression!==void 0:!1}static getNodeValue(e){if(!e)return"undefined";try{return e.constructor&&e.type==="omdVariableNode"&&e.name!==void 0?String(e.name):e.constructor&&e.type==="omdConstantNode"&&typeof e.number=="number"?String(e.number):e.isConstant&&e.isConstant()&&e.getValue&&typeof e.getValue=="function"?String(e.getValue()):e.toString&&typeof e.toString=="function"?e.toString():e.value!==void 0?String(e.value):e.number!==void 0?String(e.number):e.constructor?e.type:"unknown"}catch(t){return console.error("Error getting node value:",t),"error"}}static findLeafNodes(e){if(!e)return[];if(this.isLeafNode(e))return[e];const t=[];try{this.isBinaryNode(e)?(t.push(...this.findLeafNodes(e.left)),t.push(...this.findLeafNodes(e.right))):this.isUnaryNode(e)?t.push(...this.findLeafNodes(e.argument)):this.hasExpression(e)&&t.push(...this.findLeafNodes(e.expression))}catch(r){console.error("Error finding leaf nodes:",r,e)}return t}static findVariableNodes(e){return this.findLeafNodes(e).filter(r=>r.constructor&&r.type==="omdVariableNode")}static findConstantNodes(e){return this.findLeafNodes(e).filter(r=>r.constructor&&r.type==="omdConstantNode")}static findLeafNodesWithValue(e,t){const r=this.findLeafNodes(e),i=r.filter(a=>a.toString()===t);if(i.length>0)return i;const s=parseFloat(t);if(!isNaN(s)){const a=r.filter(o=>o.constructor&&o.type==="omdConstantNode"&&o.number!==void 0?Math.abs(o.number-s)<1e-4:!1);if(a.length>0)return a}return r.filter(a=>{const o=a.toString();return o.includes(t)||t.includes(o)})}static findAllNodes(e){if(!e)return[];const t=[e];try{e.childList&&Array.isArray(e.childList)&&e.childList.forEach(r=>{r&&r!==e.backRect&&t.push(...this.findAllNodes(r))}),e.argumentNodeList&&Object.values(e.argumentNodeList).forEach(r=>{r&&r!==e&&(Array.isArray(r)?r.forEach(i=>{i&&i!==e&&t.push(...this.findAllNodes(i))}):t.push(...this.findAllNodes(r)))})}catch(r){console.error("Error finding all nodes:",r,e)}return t}static findRightmostNodeWithValue(e,t){const i=this.findLeafNodes(e).filter(a=>a.toString()===t||a.constructor&&a.type==="omdConstantNode"&&a.number!==void 0&&Math.abs(a.number-parseFloat(t))<1e-4);if(i.length===0)return null;const s=i.filter(a=>{const o=a.parent;return o&&o.constructor&&o.type==="omdBinaryExpressionNode"&&o.operation==="subtract"&&o.right===a});return s.length>0?s[s.length-1]:i[i.length-1]}}class Iq{static findChangedNodes(e,t,r={}){const{educationalMode:i=!1}=r,s=this.findEquationSpecialCases(e,t);if(s.length>0)return s;const a=[];if(e.left.toString()!==t.left.toString()){const o=this.diffSubtrees(e.left,t.left,i);a.push(...o)}if(e.right.toString()!==t.right.toString()){const o=this.diffSubtrees(e.right,t.right,i);a.push(...o)}return a}static findEquationSpecialCases(e,t){const r=e.left.toString(),i=t.left.toString(),s=e.right.toString(),a=t.right.toString();if(i.startsWith(r)&&a.startsWith(s)){const o=i.substring(r.length).trim(),l=a.substring(s.length).trim();if(o.startsWith("-")&&l.startsWith("-")&&o.substring(1).trim()===l.substring(1).trim()){const u=o.substring(1).trim(),c=[],h=je.findRightmostNodeWithValue(t.left,u);if(h)if(je.isLeafNode(h))c.push(h);else{const d=je.findLeafNodes(h);c.push(...d)}const f=je.findRightmostNodeWithValue(t.right,u);if(f)if(je.isLeafNode(f))c.push(f);else{const d=je.findLeafNodes(f);c.push(...d)}return c}if(o.startsWith("+")&&l.startsWith("+")&&o.substring(1).trim()===l.substring(1).trim()){const u=o.substring(1).trim(),c=[],h=je.findRightmostNodeWithValue(t.left,u);if(h)if(je.isLeafNode(h))c.push(h);else{const d=je.findLeafNodes(h);c.push(...d)}const f=je.findRightmostNodeWithValue(t.right,u);if(f)if(je.isLeafNode(f))c.push(f);else{const d=je.findLeafNodes(f);c.push(...d)}return c}}return[]}static diffSubtrees(e,t,r=!1){const i=this.findCommonPrefixHighlights(e,t);if(i.length>0)return i;const s=this.findVariablePreservationHighlights(e,t);if(s.length>0)return s;const a=this.findTypeDifferenceHighlights(e,t);if(a.length>0)return a;const o=this.findSubtractionPatternHighlights(e,t);if(o.length>0)return o;const l=this.findAllSubtreeMatches(e,t),u=this.selectOptimalMatching(l);let c=this.findUnmatchedLeafNodes(t,u);if(r&&c.length===0){const h=this.findEducationalHighlights(e,t,u);c.push(...h)}return c}static findEducationalHighlights(e,t,r){const i=[],s=this.findAdditiveIdentityChanges(e,t);i.push(...s);const a=this.findMultiplicativeIdentityChanges(e,t);i.push(...a);const o=this.findDoubleNegativeChanges(e,t);return i.push(...o),i}static findAdditiveIdentityChanges(e,t){const r=e.toString(),i=t.toString();if((r.includes(" + 0")||r.includes(" - 0"))&&!i.includes(" + 0")&&!i.includes(" - 0")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findMultiplicativeIdentityChanges(e,t){const r=e.toString(),i=t.toString();if((r.includes(" * 1")||r.includes(" / 1"))&&!i.includes(" * 1")&&!i.includes(" / 1")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findDoubleNegativeChanges(e,t){const r=e.toString(),i=t.toString();if(r.includes("--")&&!i.includes("--")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findCommonPrefixHighlights(e,t){if(!je.isBinaryNode(t))return[];const r=e.toString(),i=t.toString(),s=this._findCommonPrefix(r,i);if(!s||s.length<=1)return[];const a=r.substring(s.length).trim(),o=i.substring(s.length).trim();if(o==="0"){const l=je.findLeafNodesWithValue(t,"0");if(l.length>0)return l}if(a===""&&o.startsWith("- ")){const l=o.substring(2).trim(),u=je.findLeafNodesWithValue(t,l);if(u.length>0)return u}return[]}static findVariablePreservationHighlights(e,t){if(!je.isBinaryNode(e)||!je.isBinaryNode(t))return[];const r=e.toString(),i=t.toString(),s=/(\d*[a-zA-Z])/,a=r.match(s),o=i.match(s);if(a&&o&&a[0]===o[0]){const l=je.findConstantNodes(e);return je.findConstantNodes(t).filter(h=>!l.some(f=>f.toString()===h.toString()))}return[]}static findTypeDifferenceHighlights(e,t){const r=e.constructor?e.type:"unknown",i=t.constructor?t.type:"unknown";if(r===i)return[];if(je.isBinaryNode(t)){const a=e.toString(),o=t.left?t.left.toString():"",l=t.right?t.right.toString():"";if(a===o){if(t.right)return je.findLeafNodes(t.right)}else if(a===l&&t.left)return je.findLeafNodes(t.left)}return je.findLeafNodes(t)}static findSubtractionPatternHighlights(e,t){var r;if(je.isBinaryNode(t)&&t.operation==="subtract"){const i=e.toString(),s=(r=t.left)==null?void 0:r.toString();if(i===s&&t.right)return je.findLeafNodes(t.right)}return[]}static _findCommonPrefix(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return e.substring(0,r)}static findAllSubtreeMatches(e,t){const r=[],i=this.getAllSubtrees(e),s=this.getAllSubtrees(t);for(const a of i)for(const o of s){const l=this.calculateSimilarity(a,o);l.isMatch&&r.push({oldNode:a,newNode:o,size:l.size,score:l.score,type:l.type})}return r}static getAllSubtrees(e){if(!e)return[];const t=[e];return je.isBinaryNode(e)?(t.push(...this.getAllSubtrees(e.left)),t.push(...this.getAllSubtrees(e.right))):je.isUnaryNode(e)?t.push(...this.getAllSubtrees(e.argument)):je.hasExpression(e)&&t.push(...this.getAllSubtrees(e.expression)),t}static calculateSimilarity(e,t){if(this.treesStructurallyEqual(e,t)){const r=this.getSubtreeSize(e);return{isMatch:!0,size:r,score:r*10,type:"exact"}}if(e.toString()===t.toString()){const r=this.getSubtreeSize(e);return{isMatch:!0,size:r,score:r*8,type:"equivalent"}}if(je.isLeafNode(e)&&je.isLeafNode(t)){const r=je.getNodeValue(e),i=je.getNodeValue(t);if(r===i)return{isMatch:!0,size:1,score:5,type:"leaf"}}return{isMatch:!1,size:0,score:0,type:"none"}}static treesStructurallyEqual(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.constructor?e.type:"unknown",i=t.constructor?t.type:"unknown";if(r!==i)return!1;if(je.isLeafNode(e)){const s=je.getNodeValue(e),a=je.getNodeValue(t);return s===a}return je.isBinaryNode(e)?e.operation!==t.operation?!1:this.treesStructurallyEqual(e.left,t.left)&&this.treesStructurallyEqual(e.right,t.right):je.isUnaryNode(e)?e.operation!==t.operation?!1:this.treesStructurallyEqual(e.argument,t.argument):je.hasExpression(e)?this.treesStructurallyEqual(e.expression,t.expression):!1}static getSubtreeSize(e){if(!e)return 0;let t=1;return je.isBinaryNode(e)?(t+=this.getSubtreeSize(e.left),t+=this.getSubtreeSize(e.right)):je.isUnaryNode(e)?t+=this.getSubtreeSize(e.argument):je.hasExpression(e)&&(t+=this.getSubtreeSize(e.expression)),t}static selectOptimalMatching(e){const t=e.slice().sort((a,o)=>o.score-a.score),r=[],i=new Set,s=new Set;for(const a of t)!this.hasNodeOverlap(a.oldNode,i)&&!this.hasNodeOverlap(a.newNode,s)&&(r.push(a),this.markSubtreeAsUsed(a.oldNode,i),this.markSubtreeAsUsed(a.newNode,s));return r}static hasNodeOverlap(e,t){return this.getAllSubtrees(e).some(i=>t.has(i))}static markSubtreeAsUsed(e,t){this.getAllSubtrees(e).forEach(i=>t.add(i))}static findUnmatchedLeafNodes(e,t){const r=je.findLeafNodes(e),i=new Set;for(const a of t)this.getAllSubtrees(a.newNode).forEach(l=>i.add(l));return r.filter(a=>!i.has(a))}static findUnmatchedOldNodes(e,t){const r=je.findLeafNodes(e),i=new Set;for(const a of t)this.getAllSubtrees(a.oldNode).forEach(l=>i.add(l));return r.filter(a=>!i.has(a))}static debugPrintTree(e,t=0){if(!e)return"";const r=" ".repeat(t),i=e.constructor?e.type:"unknown",s=e.toString?e.toString():"unknown";let a=`${r}${i}: "${s}"
60
+ In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.`,examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]},Uz={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, dimension)","std(A, normalization)","std(A, dimension, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]},Vz={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]},Wz={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)","sum(A, dimension)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","variance"]},jz={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, dimension)","variance(A, normalization)","variance(A, dimension, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]},Gz={name:"corr",category:"Statistics",syntax:["corr(A,B)"],description:"Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.",examples:["corr([2, 4, 6, 8],[1, 2, 3, 6])","corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))"],seealso:["max","mean","min","median","min","prod","std","sum"]},Xz={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]},Yz={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]},Jz={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]},Zz={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the inverse hyperbolic tangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]},Qz={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]},Kz={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the inverse hyperbolic cosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},eR={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]},tR={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},rR={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]},iR={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]},nR={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]},sR={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]},aR={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]},oR={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]},uR={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},lR={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]},cR={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]},hR={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]},fR={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]},dR={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]},pR={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]},mR={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]},gR={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},vR={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]},yR={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]},bR={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]},xR={name:"toBest",category:"Units",syntax:["toBest(x)","toBest(x, unitList)","toBest(x, unitList, options)"],description:"Converts to the most appropriate display unit.",examples:['toBest(unit(5000, "m"))','toBest(unit(3500000, "W"))','toBest(unit(0.000000123, "A"))','toBest(unit(10, "m"), "cm")','toBest(unit(10, "m"), "mm,km", {offset: 1.5})'],seealso:[]},wR={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},SR={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables, and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]},NR={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]},CR={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]},DR={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},AR={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]},ER={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]},MR={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]},TR={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]},FR={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},_R={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},OR={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]},BR={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "bigint")','numeric("4", "BigNumber")','numeric("4", "Fraction")','numeric(4, "Fraction")','numeric(fraction(2, 5), "number")'],seealso:["number","bigint","fraction","bignumber","string","format"]},kR={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},PR={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $1, $2, $3", [6, 9, 4])'],seealso:["format"]},zR={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]},RR={name:"solveODE",category:"Numeric",syntax:["solveODE(func, tspan, y0)","solveODE(func, tspan, y0, options)"],description:"Numerical Integration of Ordinary Differential Equations.",examples:["f(t,y) = y","tspan = [0, 4]","solveODE(f, tspan, 1)","solveODE(f, tspan, [1, 2])",'solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })'],seealso:["derivative","simplifyCore"]},OS={bignumber:wk,bigint:Sk,boolean:Nk,complex:Ck,createUnit:Dk,fraction:Ak,index:Ek,matrix:Mk,number:Tk,sparse:Fk,splitUnit:_k,string:Ok,unit:Bk,e:FS,E:FS,false:ak,i:ok,Infinity:uk,LN2:ck,LN10:lk,LOG2E:fk,LOG10E:hk,NaN:dk,null:pk,pi:_S,PI:_S,phi:mk,SQRT1_2:gk,SQRT2:vk,tau:yk,true:bk,version:xk,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant. Deprecated in favor of coulombConstant",examples:["coulombConstant"]},coulombConstant:{description:"Coulomb's constant",examples:["coulombConstant"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Bohr magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Bohr radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:Rk,lsolve:Ik,lsolveAll:$k,lup:qk,lusolve:Hk,leafCount:Lk,polynomialRoot:Uk,resolve:jk,simplify:Gk,simplifyConstant:Xk,simplifyCore:Yk,symbolicEqual:Zk,rationalize:Wk,slu:Jk,usolve:Qk,usolveAll:Kk,qr:Vk,abs:eP,add:tP,cbrt:rP,ceil:iP,cube:nP,divide:sP,dotDivide:aP,dotMultiply:oP,dotPow:uP,exp:lP,expm:cP,expm1:hP,fix:fP,floor:dP,gcd:pP,hypot:mP,lcm:vP,log:yP,log2:wP,log1p:xP,log10:bP,mod:SP,multiply:NP,norm:CP,nthRoot:DP,nthRoots:AP,pow:EP,round:MP,sign:TP,sqrt:FP,sqrtm:_P,square:PP,subtract:zP,unaryMinus:RP,unaryPlus:LP,xgcd:IP,invmod:gP,bitAnd:$P,bitNot:qP,bitOr:HP,bitXor:UP,leftShift:VP,rightArithShift:WP,rightLogShift:jP,bellNumbers:GP,catalan:XP,composition:YP,stirlingS2:JP,config:kk,import:Pk,typed:zk,arg:ZP,conj:QP,re:e5,im:KP,evaluate:t5,help:s5,parse:i5,parser:r5,compile:n5,distance:a5,intersect:o5,and:u5,not:l5,nullish:c5,or:h5,xor:f5,mapSlices:d5,concat:m5,count:g5,cross:v5,column:p5,ctranspose:y5,det:b5,diag:x5,diff:w5,dot:S5,getMatrixDataType:E5,identity:M5,filter:C5,flatten:D5,forEach:A5,inv:T5,pinv:F5,eigs:N5,kron:_5,matrixFromFunction:k5,matrixFromRows:P5,matrixFromColumns:B5,map:O5,ones:z5,partitionSelect:R5,range:L5,resize:$5,reshape:I5,rotate:q5,rotationMatrix:H5,row:U5,size:V5,sort:W5,squeeze:j5,subset:G5,trace:X5,transpose:Y5,zeros:J5,fft:Z5,ifft:Q5,sylvester:OP,schur:BP,lyap:kP,solveODE:RR,combinations:K5,combinationsWithRep:ez,factorial:tz,gamma:rz,kldivergence:nz,lgamma:iz,multinomial:sz,permutations:az,pickRandom:oz,random:uz,randomInt:lz,compare:cz,compareNatural:hz,compareText:fz,deepEqual:dz,equal:pz,equalText:mz,larger:gz,largerEq:vz,smaller:yz,smallerEq:bz,unequal:xz,setCartesian:wz,setDifference:Sz,setDistinct:Nz,setIntersect:Cz,setIsSubset:Dz,setMultiplicity:Az,setPowerset:Ez,setSize:Mz,setSymDifference:Tz,setUnion:Fz,zpk2tf:_z,freqz:Oz,erf:Bz,zeta:kz,cumsum:Vz,mad:Pz,max:zz,mean:Rz,median:Lz,min:Iz,mode:$z,prod:qz,quantileSeq:Hz,std:Uz,sum:Wz,variance:jz,corr:Gz,acos:Xz,acosh:Yz,acot:Jz,acoth:Zz,acsc:Qz,acsch:Kz,asec:eR,asech:tR,asin:rR,asinh:iR,atan:nR,atanh:aR,atan2:sR,cos:oR,cosh:uR,cot:lR,coth:cR,csc:hR,csch:fR,sec:dR,sech:pR,sin:mR,sinh:gR,tan:vR,tanh:yR,to:bR,toBest:xR,clone:SR,format:NR,bin:wR,oct:kR,hex:DR,isNaN:ER,isInteger:AR,isNegative:MR,isNumeric:TR,hasNumericValue:CR,isPositive:FR,isPrime:_R,isZero:OR,print:PR,typeOf:zR,numeric:BR},BS="help",LR=["typed","mathWithTransform","Help"],Wf=R(BS,LR,n=>{var{typed:e,mathWithTransform:t,Help:r}=n;return e(BS,{any:function(s){var a,o=s;if(typeof s!="string"){for(a in t)if(Te(t,a)&&s===t[a]){o=a;break}}var l=_r(OS,o);if(!l){var u=typeof o=="function"?o.name:o;throw new Error('No documentation found on "'+u+'"')}return new r(l)}})}),kS="chain",IR=["typed","Chain"],jf=R(kS,IR,n=>{var{typed:e,Chain:t}=n;return e(kS,{"":function(){return new t},any:function(i){return new t(i)}})}),PS="det",$R=["typed","matrix","subtractScalar","multiply","divideScalar","isZero","unaryMinus"],Gf=R(PS,$R,n=>{var{typed:e,matrix:t,subtractScalar:r,multiply:i,divideScalar:s,isZero:a,unaryMinus:o}=n;return e(PS,{any:function(c){return $e(c)},"Array | Matrix":function(c){var h;switch(Re(c)?h=c.size():Array.isArray(c)?(c=t(c),h=c.size()):h=[],h.length){case 0:return $e(c);case 1:if(h[0]===1)return $e(c.valueOf()[0]);if(h[0]===0)return 1;throw new RangeError("Matrix must be square (size: "+at(h)+")");case 2:{var f=h[0],d=h[1];if(f===d)return l(c.clone().valueOf(),f);if(d===0)return 1;throw new RangeError("Matrix must be square (size: "+at(h)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+at(h)+")")}}});function l(u,c,h){if(c===1)return $e(u[0][0]);if(c===2)return r(i(u[0][0],u[1][1]),i(u[1][0],u[0][1]));for(var f=!1,d=new Array(c).fill(0).map((N,D)=>D),p=0;p<c;p++){var m=d[p];if(a(u[m][p])){var y=void 0;for(y=p+1;y<c;y++)if(!a(u[d[y]][p])){m=d[y],d[y]=d[p],d[p]=m,f=!f;break}if(y===c)return u[m][p]}for(var v=u[m][p],S=p===0?1:u[d[p-1]][p-1],g=p+1;g<c;g++)for(var b=d[g],w=p+1;w<c;w++)u[b][w]=s(r(i(u[b][w],v),i(u[b][p],u[m][w])),S)}var x=u[d[c-1]][c-1];return f?o(x):x}}),zS="inv",qR=["typed","matrix","divideScalar","addScalar","multiply","unaryMinus","det","identity","abs"],Xf=R(zS,qR,n=>{var{typed:e,matrix:t,divideScalar:r,addScalar:i,multiply:s,unaryMinus:a,det:o,identity:l,abs:u}=n;return e(zS,{"Array | Matrix":function(f){var d=Re(f)?f.size():Ge(f);switch(d.length){case 1:if(d[0]===1)return Re(f)?t([r(1,f.valueOf()[0])]):[r(1,f[0])];throw new RangeError("Matrix must be square (size: "+at(d)+")");case 2:{var p=d[0],m=d[1];if(p===m)return Re(f)?t(c(f.valueOf(),p,m),f.storage()):c(f,p,m);throw new RangeError("Matrix must be square (size: "+at(d)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+at(d)+")")}},any:function(f){return r(1,f)}});function c(h,f,d){var p,m,y,v,S;if(f===1){if(v=h[0][0],v===0)throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,v)]]}else if(f===2){var g=o(h);if(g===0)throw Error("Cannot calculate inverse, determinant is zero");return[[r(h[1][1],g),r(a(h[0][1]),g)],[r(a(h[1][0]),g),r(h[0][0],g)]]}else{var b=h.concat();for(p=0;p<f;p++)b[p]=b[p].concat();for(var w=l(f).valueOf(),x=0;x<d;x++){var N=u(b[x][x]),D=x;for(p=x+1;p<f;)u(b[p][x])>N&&(N=u(b[p][x]),D=p),p++;if(N===0)throw Error("Cannot calculate inverse, determinant is zero");p=D,p!==x&&(S=b[x],b[x]=b[p],b[p]=S,S=w[x],w[x]=w[p],w[p]=S);var C=b[x],A=w[x];for(p=0;p<f;p++){var E=b[p],F=w[p];if(p!==x){if(E[x]!==0){for(y=r(a(E[x]),C[x]),m=x;m<d;m++)E[m]=i(E[m],s(y,C[m]));for(m=0;m<d;m++)F[m]=i(F[m],s(y,A[m]))}}else{for(y=C[x],m=x;m<d;m++)E[m]=r(E[m],y);for(m=0;m<d;m++)F[m]=r(F[m],y)}}}return w}}}),RS="pinv",HR=["typed","matrix","inv","deepEqual","equal","dotDivide","dot","ctranspose","divideScalar","multiply","add","Complex"],Yf=R(RS,HR,n=>{var{typed:e,matrix:t,inv:r,deepEqual:i,equal:s,dotDivide:a,dot:o,ctranspose:l,divideScalar:u,multiply:c,add:h,Complex:f}=n;return e(RS,{"Array | Matrix":function(g){var b=Re(g)?g.size():Ge(g);switch(b.length){case 1:return v(g)?l(g):b[0]===1?r(g):a(l(g),o(g,g));case 2:{if(v(g))return l(g);var w=b[0],x=b[1];if(w===x)try{return r(g)}catch(N){if(!(N instanceof Error&&N.message.match(/Cannot calculate inverse, determinant is zero/)))throw N}return Re(g)?t(d(g.valueOf(),w,x),g.storage()):d(g,w,x)}default:throw new RangeError("Matrix must be two dimensional (size: "+at(b)+")")}},any:function(g){return s(g,0)?$e(g):u(1,g)}});function d(S,g,b){var{C:w,F:x}=m(S,g,b),N=c(r(c(l(w),w)),l(w)),D=c(l(x),r(c(x,l(x))));return c(D,N)}function p(S,g,b){for(var w=$e(S),x=0,N=0;N<g;N++){if(b<=x)return w;for(var D=N;y(w[D][x]);)if(D++,g===D&&(D=N,x++,b===x))return w;[w[D],w[N]]=[w[N],w[D]];for(var C=w[N][x],A=0;A<b;A++)w[N][A]=a(w[N][A],C);for(var E=0;E<g;E++)if(E!==N){C=w[E][x];for(var F=0;F<b;F++)w[E][F]=h(w[E][F],c(-1,c(C,w[N][F])))}x++}return w}function m(S,g,b){var w=p(S,g,b),x=S.map((D,C)=>D.filter((A,E)=>E<g&&!y(o(w[E],w[E])))),N=w.filter((D,C)=>!y(o(w[C],w[C])));return{C:x,F:N}}function y(S){return s(h(S,f(1,1)),h(0,f(1,1)))}function v(S){return i(h(S,f(1,1)),h(c(S,0),f(1,1)))}});function UR(n){var{addScalar:e,subtract:t,flatten:r,multiply:i,multiplyScalar:s,divideScalar:a,sqrt:o,abs:l,bignumber:u,diag:c,size:h,reshape:f,inv:d,qr:p,usolve:m,usolveAll:y,equal:v,complex:S,larger:g,smaller:b,matrixFromColumns:w,dot:x}=n;function N(_,V,z,de){var ae=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,oe=D(_,V,z,de,ae);C(_,V,z,de,ae,oe);var{values:$,C:H}=A(_,V,z,de,ae);if(ae){var J=E(_,V,H,oe,$,z,de);return{values:$,eigenvectors:J}}return{values:$}}function D(_,V,z,de,ae){var oe=de==="BigNumber",$=de==="Complex",H=oe?u(0):0,J=oe?u(1):$?S(1):1,K=oe?u(1):1,te=oe?u(10):2,fe=s(te,te),le;ae&&(le=Array(V).fill(J));for(var Se=!1;!Se;){Se=!0;for(var _e=0;_e<V;_e++){for(var Be=H,Ee=H,Pe=0;Pe<V;Pe++)_e!==Pe&&(Be=e(Be,l(_[Pe][_e])),Ee=e(Ee,l(_[_e][Pe])));if(!v(Be,0)&&!v(Ee,0)){for(var q=K,Z=Be,ne=a(Ee,te),P=s(Ee,te);b(Z,ne);)Z=s(Z,fe),q=s(q,te);for(;g(Z,P);)Z=a(Z,fe),q=a(q,te);var W=b(a(e(Z,Ee),q),s(e(Be,Ee),.95));if(W){Se=!1;for(var Q=a(1,q),re=0;re<V;re++)_e!==re&&(_[_e][re]=s(_[_e][re],Q),_[re][_e]=s(_[re][_e],q));ae&&(le[_e]=s(le[_e],Q))}}}}return ae?c(le):null}function C(_,V,z,de,ae,oe){var $=de==="BigNumber",H=de==="Complex",J=$?u(0):H?S(0):0;$&&(z=u(z));for(var K=0;K<V-2;K++){for(var te=0,fe=J,le=K+1;le<V;le++){var Se=_[le][K];b(l(fe),l(Se))&&(fe=Se,te=le)}if(!b(l(fe),z)){if(te!==K+1){var _e=_[te];_[te]=_[K+1],_[K+1]=_e;for(var Be=0;Be<V;Be++){var Ee=_[Be][te];_[Be][te]=_[Be][K+1],_[Be][K+1]=Ee}if(ae){var Pe=oe[te];oe[te]=oe[K+1],oe[K+1]=Pe}}for(var q=K+2;q<V;q++){var Z=a(_[q][K],fe);if(Z!==0){for(var ne=0;ne<V;ne++)_[q][ne]=t(_[q][ne],s(Z,_[K+1][ne]));for(var P=0;P<V;P++)_[P][K+1]=e(_[P][K+1],s(Z,_[P][q]));if(ae)for(var W=0;W<V;W++)oe[q][W]=t(oe[q][W],s(Z,oe[K+1][W]))}}}}return oe}function A(_,V,z,de,ae){var oe=de==="BigNumber",$=de==="Complex",H=oe?u(1):$?S(1):1;oe&&(z=u(z));for(var J=$e(_),K=[],te=V,fe=[],le=ae?c(Array(V).fill(H)):void 0,Se=ae?c(Array(te).fill(H)):void 0,_e=0;_e<=100;){_e+=1;for(var Be=J[te-1][te-1],Ee=0;Ee<te;Ee++)J[Ee][Ee]=t(J[Ee][Ee],Be);var{Q:Pe,R:q}=p(J);J=i(q,Pe);for(var Z=0;Z<te;Z++)J[Z][Z]=e(J[Z][Z],Be);if(ae&&(Se=i(Se,Pe)),te===1||b(l(J[te-1][te-2]),z)){_e=0,K.push(J[te-1][te-1]),ae&&(fe.unshift([[1]]),k(Se,V),le=i(le,Se),te>1&&(Se=c(Array(te-1).fill(H)))),te-=1,J.pop();for(var ne=0;ne<te;ne++)J[ne].pop()}else if(te===2||b(l(J[te-2][te-3]),z)){_e=0;var P=F(J[te-2][te-2],J[te-2][te-1],J[te-1][te-2],J[te-1][te-1]);K.push(...P),ae&&(fe.unshift(O(J[te-2][te-2],J[te-2][te-1],J[te-1][te-2],J[te-1][te-1],P[0],P[1],z,de)),k(Se,V),le=i(le,Se),te>2&&(Se=c(Array(te-2).fill(H)))),te-=2,J.pop(),J.pop();for(var W=0;W<te;W++)J[W].pop(),J[W].pop()}if(te===0)break}if(K.sort((se,ce)=>+t(l(se),l(ce))),_e>100){var Q=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+K.join(", "));throw Q.values=K,Q.vectors=[],Q}var re=ae?i(le,B(fe,V)):void 0;return{values:K,C:re}}function E(_,V,z,de,ae,oe,$){var H=d(z),J=i(H,_,z),K=$==="BigNumber",te=$==="Complex",fe=K?u(0):te?S(0):0,le=K?u(1):te?S(1):1,Se=[],_e=[];for(var Be of ae){var Ee=T(Se,Be,v);Ee===-1?(Se.push(Be),_e.push(1)):_e[Ee]+=1}for(var Pe=[],q=Se.length,Z=Array(V).fill(fe),ne=c(Array(V).fill(le)),P=function(){var re=Se[W],se=t(J,i(re,ne)),ce=y(se,Z);for(ce.shift();ce.length<_e[W];){var ge=I(se,V,ce,oe,$);if(ge===null)break;ce.push(ge)}var xe=i(d(de),z);ce=ce.map(Ae=>i(xe,Ae)),Pe.push(...ce.map(Ae=>({value:re,vector:r(Ae)})))},W=0;W<q;W++)P();return Pe}function F(_,V,z,de){var ae=e(_,de),oe=t(s(_,de),s(V,z)),$=s(ae,.5),H=s(o(t(s(ae,ae),s(4,oe))),.5);return[e($,H),t($,H)]}function O(_,V,z,de,ae,oe,$,H){var J=H==="BigNumber",K=H==="Complex",te=J?u(0):K?S(0):0,fe=J?u(1):K?S(1):1;if(b(l(z),$))return[[fe,te],[te,fe]];if(g(l(t(ae,oe)),$))return[[t(ae,de),t(oe,de)],[z,z]];var le=t(_,ae),Se=t(de,ae);return b(l(V),$)&&b(l(Se),$)?[[le,fe],[z,te]]:[[V,te],[Se,fe]]}function k(_,V){for(var z=0;z<_.length;z++)_[z].push(...Array(V-_[z].length).fill(0));for(var de=_.length;de<V;de++)_.push(Array(V).fill(0)),_[de][de]=1;return _}function B(_,V){for(var z=[],de=0;de<V;de++)z[de]=Array(V).fill(0);var ae=0;for(var oe of _){for(var $=oe.length,H=0;H<$;H++)for(var J=0;J<$;J++)z[ae+H][ae+J]=oe[H][J];ae+=$}return z}function T(_,V,z){for(var de=0;de<_.length;de++)if(z(_[de],V))return de;return-1}function I(_,V,z,de,ae){for(var oe=ae==="BigNumber"?u(1e3):1e3,$,H=0;H<5;++H){$=U(V,z,ae);try{$=m(_,$)}catch{continue}if(g(Y($),oe))break}if(H>=5)return null;for(H=0;;){var J=m(_,$);if(b(Y(L($,[J])),de))break;if(++H>=10)return null;$=ee(J)}return $}function U(_,V,z){var de=z==="BigNumber",ae=z==="Complex",oe=Array(_).fill(0).map($=>2*Math.random()-1);return de&&(oe=oe.map($=>u($))),ae&&(oe=oe.map($=>S($))),oe=L(oe,V),ee(oe,z)}function L(_,V){var z=h(_);for(var de of V)de=f(de,z),_=t(_,i(a(x(de,_),x(de,de)),de));return _}function Y(_){return l(o(x(_,_)))}function ee(_,V){var z=V==="BigNumber",de=V==="Complex",ae=z?u(1):de?S(1):1;return i(a(ae,Y(_)),_)}return N}function VR(n){var{config:e,addScalar:t,subtract:r,abs:i,atan:s,cos:a,sin:o,multiplyScalar:l,inv:u,bignumber:c,multiply:h,add:f}=n;function d(C,A){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.relTol,F=arguments.length>3?arguments[3]:void 0,O=arguments.length>4?arguments[4]:void 0;if(F==="number")return p(C,E,O);if(F==="BigNumber")return m(C,E,O);throw TypeError("Unsupported data type: "+F)}function p(C,A,E){var F=C.length,O=Math.abs(A/F),k,B;if(E){B=new Array(F);for(var T=0;T<F;T++)B[T]=Array(F).fill(0),B[T][T]=1}for(var I=x(C);Math.abs(I[1])>=Math.abs(O);){var U=I[0][0],L=I[0][1];k=y(C[U][U],C[L][L],C[U][L]),C=w(C,k,U,L),E&&(B=S(B,k,U,L)),I=x(C)}for(var Y=Array(F).fill(0),ee=0;ee<F;ee++)Y[ee]=C[ee][ee];return D($e(Y),B,E)}function m(C,A,E){var F=C.length,O=i(A/F),k,B;if(E){B=new Array(F);for(var T=0;T<F;T++)B[T]=Array(F).fill(0),B[T][T]=1}for(var I=N(C);i(I[1])>=i(O);){var U=I[0][0],L=I[0][1];k=v(C[U][U],C[L][L],C[U][L]),C=b(C,k,U,L),E&&(B=g(B,k,U,L)),I=N(C)}for(var Y=Array(F).fill(0),ee=0;ee<F;ee++)Y[ee]=C[ee][ee];return D($e(Y),B,E)}function y(C,A,E){var F=A-C;return Math.abs(F)<=e.relTol?Math.PI/4:.5*Math.atan(2*E/(A-C))}function v(C,A,E){var F=r(A,C);return i(F)<=e.relTol?c(-1).acos().div(4):l(.5,s(h(2,E,u(F))))}function S(C,A,E,F){for(var O=C.length,k=Math.cos(A),B=Math.sin(A),T=Array(O).fill(0),I=Array(O).fill(0),U=0;U<O;U++)T[U]=k*C[U][E]-B*C[U][F],I[U]=B*C[U][E]+k*C[U][F];for(var L=0;L<O;L++)C[L][E]=T[L],C[L][F]=I[L];return C}function g(C,A,E,F){for(var O=C.length,k=a(A),B=o(A),T=Array(O).fill(c(0)),I=Array(O).fill(c(0)),U=0;U<O;U++)T[U]=r(l(k,C[U][E]),l(B,C[U][F])),I[U]=t(l(B,C[U][E]),l(k,C[U][F]));for(var L=0;L<O;L++)C[L][E]=T[L],C[L][F]=I[L];return C}function b(C,A,E,F){for(var O=C.length,k=c(a(A)),B=c(o(A)),T=l(k,k),I=l(B,B),U=Array(O).fill(c(0)),L=Array(O).fill(c(0)),Y=h(c(2),k,B,C[E][F]),ee=t(r(l(T,C[E][E]),Y),l(I,C[F][F])),_=f(l(I,C[E][E]),Y,l(T,C[F][F])),V=0;V<O;V++)U[V]=r(l(k,C[E][V]),l(B,C[F][V])),L[V]=t(l(B,C[E][V]),l(k,C[F][V]));C[E][E]=ee,C[F][F]=_,C[E][F]=c(0),C[F][E]=c(0);for(var z=0;z<O;z++)z!==E&&z!==F&&(C[E][z]=U[z],C[z][E]=U[z],C[F][z]=L[z],C[z][F]=L[z]);return C}function w(C,A,E,F){for(var O=C.length,k=Math.cos(A),B=Math.sin(A),T=k*k,I=B*B,U=Array(O).fill(0),L=Array(O).fill(0),Y=T*C[E][E]-2*k*B*C[E][F]+I*C[F][F],ee=I*C[E][E]+2*k*B*C[E][F]+T*C[F][F],_=0;_<O;_++)U[_]=k*C[E][_]-B*C[F][_],L[_]=B*C[E][_]+k*C[F][_];C[E][E]=Y,C[F][F]=ee,C[E][F]=0,C[F][E]=0;for(var V=0;V<O;V++)V!==E&&V!==F&&(C[E][V]=U[V],C[V][E]=U[V],C[F][V]=L[V],C[V][F]=L[V]);return C}function x(C){for(var A=C.length,E=0,F=[0,1],O=0;O<A;O++)for(var k=O+1;k<A;k++)Math.abs(E)<Math.abs(C[O][k])&&(E=Math.abs(C[O][k]),F=[O,k]);return[F,E]}function N(C){for(var A=C.length,E=0,F=[0,1],O=0;O<A;O++)for(var k=O+1;k<A;k++)i(E)<i(C[O][k])&&(E=i(C[O][k]),F=[O,k]);return[F,E]}function D(C,A,E){var F=C.length,O=Array(F),k;if(E){k=Array(F);for(var B=0;B<F;B++)k[B]=Array(F)}for(var T=0;T<F;T++){for(var I=0,U=C[0],L=0;L<C.length;L++)i(C[L])<i(U)&&(I=L,U=C[I]);if(O[T]=C.splice(I,1)[0],E)for(var Y=0;Y<F;Y++)k[T][Y]=A[Y][I],A[Y].splice(I,1)}if(!E)return{values:O};var ee=k.map((_,V)=>({value:O[V],vector:_}));return{values:O,eigenvectors:ee}}return d}var WR="eigs",jR=["config","typed","matrix","addScalar","equal","subtract","abs","atan","cos","sin","multiplyScalar","divideScalar","inv","bignumber","multiply","add","larger","column","flatten","number","complex","sqrt","diag","size","reshape","qr","usolve","usolveAll","im","re","smaller","matrixFromColumns","dot"],Jf=R(WR,jR,n=>{var{config:e,typed:t,matrix:r,addScalar:i,subtract:s,equal:a,abs:o,atan:l,cos:u,sin:c,multiplyScalar:h,divideScalar:f,inv:d,bignumber:p,multiply:m,add:y,larger:v,column:S,flatten:g,number:b,complex:w,sqrt:x,diag:N,size:D,reshape:C,qr:A,usolve:E,usolveAll:F,im:O,re:k,smaller:B,matrixFromColumns:T,dot:I}=n,U=VR({config:e,addScalar:i,subtract:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:h,inv:d,bignumber:p,multiply:m,add:y}),L=UR({addScalar:i,subtract:s,multiply:m,multiplyScalar:h,flatten:g,divideScalar:f,sqrt:x,abs:o,bignumber:p,diag:N,size:D,reshape:C,qr:A,inv:d,usolve:E,usolveAll:F,equal:a,complex:w,larger:v,smaller:B,matrixFromColumns:T,dot:I});return t("eigs",{Array:function(oe){return Y(r(oe))},"Array, number|BigNumber":function(oe,$){return Y(r(oe),{precision:$})},"Array, Object"(ae,oe){return Y(r(ae),oe)},Matrix:function(oe){return Y(oe,{matricize:!0})},"Matrix, number|BigNumber":function(oe,$){return Y(oe,{precision:$,matricize:!0})},"Matrix, Object":function(oe,$){var H={matricize:!0};return wt(H,$),Y(oe,H)}});function Y(ae){var oe,$=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},H="eigenvectors"in $?$.eigenvectors:!0,J=(oe=$.precision)!==null&&oe!==void 0?oe:e.relTol,K=ee(ae,J,H);return $.matricize&&(K.values=r(K.values),H&&(K.eigenvectors=K.eigenvectors.map(te=>{var{value:fe,vector:le}=te;return{value:fe,vector:r(le)}}))),H&&Object.defineProperty(K,"vectors",{enumerable:!1,get:()=>{throw new Error("eigs(M).vectors replaced with eigs(M).eigenvectors")}}),K}function ee(ae,oe,$){var H=ae.toArray(),J=ae.size();if(J.length!==2||J[0]!==J[1])throw new RangeError("Matrix must be square (size: ".concat(at(J),")"));var K=J[0];if(V(H,K,oe)&&(z(H,K),_(H,K,oe))){var te=de(ae,H,K);return U(H,K,oe,te,$)}var fe=de(ae,H,K);return L(H,K,oe,fe,$)}function _(ae,oe,$){for(var H=0;H<oe;H++)for(var J=H;J<oe;J++)if(v(p(o(s(ae[H][J],ae[J][H]))),$))return!1;return!0}function V(ae,oe,$){for(var H=0;H<oe;H++)for(var J=0;J<oe;J++)if(v(p(o(O(ae[H][J]))),$))return!1;return!0}function z(ae,oe){for(var $=0;$<oe;$++)for(var H=0;H<oe;H++)ae[$][H]=k(ae[$][H])}function de(ae,oe,$){var H=ae.datatype();if(H==="number"||H==="BigNumber"||H==="Complex")return H;for(var J=!1,K=!1,te=!1,fe=0;fe<$;fe++)for(var le=0;le<$;le++){var Se=oe[fe][le];if(Je(Se)||vn(Se))J=!0;else if(Xe(Se))K=!0;else if(ci(Se))te=!0;else throw TypeError("Unsupported type in Matrix: "+Dt(Se))}if(K&&te&&console.warn("Complex BigNumbers not supported, this operation will lose precission."),te){for(var _e=0;_e<$;_e++)for(var Be=0;Be<$;Be++)oe[_e][Be]=w(oe[_e][Be]);return"Complex"}if(K){for(var Ee=0;Ee<$;Ee++)for(var Pe=0;Pe<$;Pe++)oe[Ee][Pe]=p(oe[Ee][Pe]);return"BigNumber"}if(J){for(var q=0;q<$;q++)for(var Z=0;Z<$;Z++)oe[q][Z]=b(oe[q][Z]);return"number"}else throw TypeError("Matrix contains unsupported types only.")}}),LS="expm",GR=["typed","abs","add","identity","inv","multiply"],Zf=R(LS,GR,n=>{var{typed:e,abs:t,add:r,identity:i,inv:s,multiply:a}=n;return e(LS,{Matrix:function(h){var f=h.size();if(f.length!==2||f[0]!==f[1])throw new RangeError("Matrix must be square (size: "+at(f)+")");for(var d=f[0],p=1e-15,m=o(h),y=l(m,p),v=y.q,S=y.j,g=a(h,Math.pow(2,-S)),b=i(d),w=i(d),x=1,N=g,D=-1,C=1;C<=v;C++)C>1&&(N=a(N,g),D=-D),x=x*(v-C+1)/((2*v-C+1)*C),b=r(b,a(x,N)),w=r(w,a(x*D,N));for(var A=a(s(w),b),E=0;E<S;E++)A=a(A,A);return Ki(h)?h.createSparseMatrix(A):A}});function o(c){for(var h=c.size()[0],f=0,d=0;d<h;d++){for(var p=0,m=0;m<h;m++)p+=t(c.get([d,m]));f=Math.max(p,f)}return f}function l(c,h){for(var f=30,d=0;d<f;d++)for(var p=0;p<=d;p++){var m=d-p;if(u(c,p,m)<h)return{q:p,j:m}}throw new Error("Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)")}function u(c,h,f){for(var d=1,p=2;p<=h;p++)d*=p;for(var m=d,y=h+1;y<=2*h;y++)m*=y;var v=m*(2*h+1);return 8*Math.pow(c/Math.pow(2,f),2*h)*d*d/(m*v)}}),IS="sqrtm",XR=["typed","abs","add","multiply","map","sqrt","subtract","inv","size","max","identity"],Qf=R(IS,XR,n=>{var{typed:e,abs:t,add:r,multiply:i,map:s,sqrt:a,subtract:o,inv:l,size:u,max:c,identity:h}=n,f=1e3,d=1e-6;function p(m){var y,v=0,S=m,g=h(u(m));do{var b=S;if(S=i(.5,r(b,l(g))),g=i(.5,r(g,l(b))),y=c(t(o(S,b))),y>d&&++v>f)throw new Error("computing square root of matrix: iterative method could not converge")}while(y>d);return S}return e(IS,{"Array | Matrix":function(y){var v=Re(y)?y.size():Ge(y);switch(v.length){case 1:if(v[0]===1)return s(y,a);throw new RangeError("Matrix must be square (size: "+at(v)+")");case 2:{var S=v[0],g=v[1];if(S===g)return p(y);throw new RangeError("Matrix must be square (size: "+at(v)+")")}default:throw new RangeError("Matrix must be at most two dimensional (size: "+at(v)+")")}}})}),$S="sylvester",YR=["typed","schur","matrixFromColumns","matrix","multiply","range","concat","transpose","index","subset","add","subtract","identity","lusolve","abs"],Kf=R($S,YR,n=>{var{typed:e,schur:t,matrixFromColumns:r,matrix:i,multiply:s,range:a,concat:o,transpose:l,index:u,subset:c,add:h,subtract:f,identity:d,lusolve:p,abs:m}=n;return e($S,{"Matrix, Matrix, Matrix":y,"Array, Matrix, Matrix":function(S,g,b){return y(i(S),g,b)},"Array, Array, Matrix":function(S,g,b){return y(i(S),i(g),b)},"Array, Matrix, Array":function(S,g,b){return y(i(S),g,i(b))},"Matrix, Array, Matrix":function(S,g,b){return y(S,i(g),b)},"Matrix, Array, Array":function(S,g,b){return y(S,i(g),i(b))},"Matrix, Matrix, Array":function(S,g,b){return y(S,g,i(b))},"Array, Array, Array":function(S,g,b){return y(i(S),i(g),i(b)).toArray()}});function y(v,S,g){for(var b=S.size()[0],w=v.size()[0],x=t(v),N=x.T,D=x.U,C=t(s(-1,S)),A=C.T,E=C.U,F=s(s(l(D),g),E),O=a(0,w),k=[],B=(te,fe)=>o(te,fe,1),T=(te,fe)=>o(te,fe,0),I=0;I<b;I++)if(I<b-1&&m(c(A,u(I+1,I)))>1e-5){for(var U=T(c(F,u(O,I)),c(F,u(O,I+1))),L=0;L<I;L++)U=h(U,T(s(k[L],c(A,u(L,I))),s(k[L],c(A,u(L,I+1)))));var Y=s(d(w),s(-1,c(A,u(I,I)))),ee=s(d(w),s(-1,c(A,u(I+1,I)))),_=s(d(w),s(-1,c(A,u(I,I+1)))),V=s(d(w),s(-1,c(A,u(I+1,I+1)))),z=T(B(h(N,Y),ee),B(_,h(N,V))),de=p(z,U);k[I]=de.subset(u(a(0,w),0)),k[I+1]=de.subset(u(a(w,2*w),0)),I++}else{for(var ae=c(F,u(O,I)),oe=0;oe<I;oe++)ae=h(ae,s(k[oe],c(A,u(oe,I))));var $=c(A,u(I,I)),H=f(N,s($,d(w)));k[I]=p(H,ae)}var J=i(r(...k)),K=s(D,s(J,l(E)));return K}}),qS="schur",JR=["typed","matrix","identity","multiply","qr","norm","subtract"],ed=R(qS,JR,n=>{var{typed:e,matrix:t,identity:r,multiply:i,qr:s,norm:a,subtract:o}=n;return e(qS,{Array:function(c){var h=l(t(c));return{U:h.U.valueOf(),T:h.T.valueOf()}},Matrix:function(c){return l(c)}});function l(u){var c=u.size()[0],h=u,f=r(c),d=0,p;do{p=h;var m=s(h),y=m.Q,v=m.R;if(h=i(v,y),f=i(f,y),d++>100)break}while(a(o(h,p))>1e-4);return{U:f,T:h}}}),HS="lyap",ZR=["typed","matrix","sylvester","multiply","transpose"],td=R(HS,ZR,n=>{var{typed:e,matrix:t,sylvester:r,multiply:i,transpose:s}=n;return e(HS,{"Matrix, Matrix":function(o,l){return r(o,s(o),i(-1,l))},"Array, Matrix":function(o,l){return r(t(o),s(t(o)),i(-1,l))},"Matrix, Array":function(o,l){return r(o,s(t(o)),t(i(-1,l)))},"Array, Array":function(o,l){return r(t(o),s(t(o)),t(i(-1,l))).toArray()}})}),QR="divide",KR=["typed","matrix","multiply","equalScalar","divideScalar","inv"],rd=R(QR,KR,n=>{var{typed:e,matrix:t,multiply:r,equalScalar:i,divideScalar:s,inv:a}=n,o=pr({typed:e,equalScalar:i}),l=gi({typed:e});return e("divide",Dy({"Array | Matrix, Array | Matrix":function(c,h){return r(c,a(h))},"DenseMatrix, any":function(c,h){return l(c,h,s,!1)},"SparseMatrix, any":function(c,h){return o(c,h,s,!1)},"Array, any":function(c,h){return l(t(c),h,s,!1).valueOf()},"any, Array | Matrix":function(c,h){return r(c,a(h))}},s.signatures))}),US="distance",eL=["typed","addScalar","subtractScalar","divideScalar","multiplyScalar","deepEqual","sqrt","abs"],id=R(US,eL,n=>{var{typed:e,addScalar:t,subtractScalar:r,multiplyScalar:i,divideScalar:s,deepEqual:a,sqrt:o,abs:l}=n;return e(US,{"Array, Array, Array":function(w,x,N){if(w.length===2&&x.length===2&&N.length===2){if(!c(w))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(x))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!c(N))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(a(x,N))throw new TypeError("LinePoint1 should not be same with LinePoint2");var D=r(N[1],x[1]),C=r(x[0],N[0]),A=r(i(N[0],x[1]),i(x[0],N[1]));return y(w[0],w[1],D,C,A)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(w,x,N){if(Object.keys(w).length===2&&Object.keys(x).length===2&&Object.keys(N).length===2){if(!c(w))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(x))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!c(N))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if(a(p(x),p(N)))throw new TypeError("LinePoint1 should not be same with LinePoint2");if("pointX"in w&&"pointY"in w&&"lineOnePtX"in x&&"lineOnePtY"in x&&"lineTwoPtX"in N&&"lineTwoPtY"in N){var D=r(N.lineTwoPtY,x.lineOnePtY),C=r(x.lineOnePtX,N.lineTwoPtX),A=r(i(N.lineTwoPtX,x.lineOnePtY),i(x.lineOnePtX,N.lineTwoPtY));return y(w.pointX,w.pointY,D,C,A)}else throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(w,x){if(w.length===2&&x.length===3){if(!c(w))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!h(x))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return y(w[0],w[1],x[0],x[1],x[2])}else if(w.length===3&&x.length===6){if(!h(w))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!d(x))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return v(w[0],w[1],w[2],x[0],x[1],x[2],x[3],x[4],x[5])}else if(w.length===x.length&&w.length>0){if(!f(w))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!f(x))throw new TypeError("All values of an array should be numbers or BigNumbers");return S(w,x)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(w,x){if(Object.keys(w).length===2&&Object.keys(x).length===3){if(!c(w))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!h(x))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in w&&"pointY"in w&&"xCoeffLine"in x&&"yCoeffLine"in x&&"constant"in x)return y(w.pointX,w.pointY,x.xCoeffLine,x.yCoeffLine,x.constant);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===3&&Object.keys(x).length===6){if(!h(w))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!d(x))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in w&&"pointY"in w&&"x0"in x&&"y0"in x&&"z0"in x&&"a"in x&&"b"in x&&"c"in x)return v(w.pointX,w.pointY,w.pointZ,x.x0,x.y0,x.z0,x.a,x.b,x.c);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===2&&Object.keys(x).length===2){if(!c(w))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(x))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in w&&"pointOneY"in w&&"pointTwoX"in x&&"pointTwoY"in x)return S([w.pointOneX,w.pointOneY],[x.pointTwoX,x.pointTwoY]);throw new TypeError("Key names do not match")}else if(Object.keys(w).length===3&&Object.keys(x).length===3){if(!h(w))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!h(x))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in w&&"pointOneY"in w&&"pointOneZ"in w&&"pointTwoX"in x&&"pointTwoY"in x&&"pointTwoZ"in x)return S([w.pointOneX,w.pointOneY,w.pointOneZ],[x.pointTwoX,x.pointTwoY,x.pointTwoZ]);throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},Array:function(w){if(!m(w))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return g(w)}});function u(b){return typeof b=="number"||Xe(b)}function c(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])}function h(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])&&u(b[2])}function f(b){return Array.isArray(b)||(b=p(b)),b.every(u)}function d(b){return b.constructor!==Array&&(b=p(b)),u(b[0])&&u(b[1])&&u(b[2])&&u(b[3])&&u(b[4])&&u(b[5])}function p(b){for(var w=Object.keys(b),x=[],N=0;N<w.length;N++)x.push(b[w[N]]);return x}function m(b){if(b[0].length===2&&u(b[0][0])&&u(b[0][1])){if(b.some(w=>w.length!==2||!u(w[0])||!u(w[1])))return!1}else if(b[0].length===3&&u(b[0][0])&&u(b[0][1])&&u(b[0][2])){if(b.some(w=>w.length!==3||!u(w[0])||!u(w[1])||!u(w[2])))return!1}else return!1;return!0}function y(b,w,x,N,D){var C=l(t(t(i(x,b),i(N,w)),D)),A=o(t(i(x,x),i(N,N)));return s(C,A)}function v(b,w,x,N,D,C,A,E,F){var O=[r(i(r(D,w),F),i(r(C,x),E)),r(i(r(C,x),A),i(r(N,b),F)),r(i(r(N,b),E),i(r(D,w),A))];O=o(t(t(i(O[0],O[0]),i(O[1],O[1])),i(O[2],O[2])));var k=o(t(t(i(A,A),i(E,E)),i(F,F)));return s(O,k)}function S(b,w){for(var x=b.length,N=0,D=0,C=0;C<x;C++)D=r(b[C],w[C]),N=t(i(D,D),N);return o(N)}function g(b){for(var w=[],x=[],N=[],D=0;D<b.length-1;D++)for(var C=D+1;C<b.length;C++)b[0].length===2?(x=[b[D][0],b[D][1]],N=[b[C][0],b[C][1]]):b[0].length===3&&(x=[b[D][0],b[D][1],b[D][2]],N=[b[C][0],b[C][1],b[C][2]]),w.push(S(x,N));return w}}),tL="intersect",rL=["typed","config","abs","add","addScalar","matrix","multiply","multiplyScalar","divideScalar","subtract","smaller","equalScalar","flatten","isZero","isNumeric"],nd=R(tL,rL,n=>{var{typed:e,config:t,abs:r,add:i,addScalar:s,matrix:a,multiply:o,multiplyScalar:l,divideScalar:u,subtract:c,smaller:h,equalScalar:f,flatten:d,isZero:p,isNumeric:m}=n;return e("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":v,"Matrix, Matrix, Matrix":function(E,F,O){var k=y(E.valueOf(),F.valueOf(),O.valueOf());return k===null?null:a(k)},"Matrix, Matrix, Matrix, Matrix":function(E,F,O,k){var B=v(E.valueOf(),F.valueOf(),O.valueOf(),k.valueOf());return B===null?null:a(B)}});function y(A,E,F){if(A=S(A),E=S(E),F=S(F),!b(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!b(E))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!w(F))throw new TypeError("Array with 4 numbers expected as third argument");return C(A[0],A[1],A[2],E[0],E[1],E[2],F[0],F[1],F[2],F[3])}function v(A,E,F,O){if(A=S(A),E=S(E),F=S(F),O=S(O),A.length===2){if(!g(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!g(E))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!g(F))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!g(O))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return x(A,E,F,O)}else if(A.length===3){if(!b(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!b(E))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!b(F))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!b(O))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return D(A[0],A[1],A[2],E[0],E[1],E[2],F[0],F[1],F[2],O[0],O[1],O[2])}else throw new TypeError("Arrays with two or thee dimensional points expected")}function S(A){return A.length===1?A[0]:A.length>1&&Array.isArray(A[0])&&A.every(E=>Array.isArray(E)&&E.length===1)?d(A):A}function g(A){return A.length===2&&m(A[0])&&m(A[1])}function b(A){return A.length===3&&m(A[0])&&m(A[1])&&m(A[2])}function w(A){return A.length===4&&m(A[0])&&m(A[1])&&m(A[2])&&m(A[3])}function x(A,E,F,O){var k=A,B=F,T=c(k,E),I=c(B,O),U=c(l(T[0],I[1]),l(I[0],T[1]));if(p(U)||h(r(U),t.relTol))return null;var L=l(I[0],k[1]),Y=l(I[1],k[0]),ee=l(I[0],B[1]),_=l(I[1],B[0]),V=u(s(c(c(L,Y),ee),_),U);return i(o(T,V),k)}function N(A,E,F,O,k,B,T,I,U,L,Y,ee){var _=l(c(A,E),c(F,O)),V=l(c(k,B),c(T,I)),z=l(c(U,L),c(Y,ee));return s(s(_,V),z)}function D(A,E,F,O,k,B,T,I,U,L,Y,ee){var _=N(A,T,L,T,E,I,Y,I,F,U,ee,U),V=N(L,T,O,A,Y,I,k,E,ee,U,B,F),z=N(A,T,O,A,E,I,k,E,F,U,B,F),de=N(L,T,L,T,Y,I,Y,I,ee,U,ee,U),ae=N(O,A,O,A,k,E,k,E,B,F,B,F),oe=c(l(_,V),l(z,de)),$=c(l(ae,de),l(V,V));if(p($))return null;var H=u(oe,$),J=u(s(_,l(H,V)),de),K=s(A,l(H,c(O,A))),te=s(E,l(H,c(k,E))),fe=s(F,l(H,c(B,F))),le=s(T,l(J,c(L,T))),Se=s(I,l(J,c(Y,I))),_e=s(U,l(J,c(ee,U)));return f(K,le)&&f(te,Se)&&f(fe,_e)?[K,te,fe]:null}function C(A,E,F,O,k,B,T,I,U,L){var Y=l(A,T),ee=l(O,T),_=l(E,I),V=l(k,I),z=l(F,U),de=l(B,U),ae=c(c(c(L,Y),_),z),oe=c(c(c(s(s(ee,V),de),Y),_),z),$=u(ae,oe),H=s(A,l($,c(O,A))),J=s(E,l($,c(k,E))),K=s(F,l($,c(B,F)));return[H,J,K]}}),VS="sum",iL=["typed","config","add","numeric"],bo=R(VS,iL,n=>{var{typed:e,config:t,add:r,numeric:i}=n;return e(VS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":a,"...":function(l){if(na(l))throw new TypeError("Scalar values expected in function sum");return s(l)}});function s(o){var l;return Fn(o,function(u){try{l=l===void 0?u:r(l,u)}catch(c){throw Br(c,"sum",u)}}),l===void 0&&(l=i(0,t.number)),typeof l=="string"&&(l=i(l,wn(l,t))),l}function a(o,l){try{var u=ku(o,l,r);return u}catch(c){throw Br(c,"sum")}}}),sd="cumsum",nL=["typed","add","unaryPlus"],xo=R(sd,nL,n=>{var{typed:e,add:t,unaryPlus:r}=n;return e(sd,{Array:i,Matrix:function(u){return u.create(i(u.valueOf(),u.datatype()))},"Array, number | BigNumber":a,"Matrix, number | BigNumber":function(u,c){return u.create(a(u.valueOf(),c),u.datatype())},"...":function(u){if(na(u))throw new TypeError("All values expected to be scalar in function cumsum");return i(u)}});function i(l){try{return s(l)}catch(u){throw Br(u,sd)}}function s(l){if(l.length===0)return[];for(var u=[r(l[0])],c=1;c<l.length;++c)u.push(t(u[c-1],l[c]));return u}function a(l,u){var c=Ge(l);if(u<0||u>=c.length)throw new Kr(u,c.length);try{return o(l,u)}catch(h){throw Br(h,sd)}}function o(l,u){var c,h,f;if(u<=0){var d=l[0][0];if(Array.isArray(d)){for(f=xb(l),h=[],c=0;c<f.length;c++)h[c]=o(f[c],u-1);return h}else return s(l)}else{for(h=[],c=0;c<l.length;c++)h[c]=o(l[c],u-1);return h}}}),WS="mean",sL=["typed","add","divide"],wo=R(WS,sL,n=>{var{typed:e,add:t,divide:r}=n;return e(WS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":i,"...":function(o){if(na(o))throw new TypeError("Scalar values expected in function mean");return s(o)}});function i(a,o){try{var l=ku(a,o,t),u=Array.isArray(a)?Ge(a):a.size();return r(l,u[o])}catch(c){throw Br(c,"mean")}}function s(a){var o,l=0;if(Fn(a,function(u){try{o=o===void 0?u:t(o,u),l++}catch(c){throw Br(c,"mean",u)}}),l===0)throw new Error("Cannot calculate the mean of an empty array");return r(o,l)}}),jS="median",aL=["typed","add","divide","compare","partitionSelect"],ad=R(jS,aL,n=>{var{typed:e,add:t,divide:r,compare:i,partitionSelect:s}=n;function a(u){try{u=gt(u.valueOf());var c=u.length;if(c===0)throw new Error("Cannot calculate median of an empty array");if(c%2===0){for(var h=c/2-1,f=s(u,h+1),d=u[h],p=0;p<h;++p)i(u[p],d)>0&&(d=u[p]);return l(d,f)}else{var m=s(u,(c-1)/2);return o(m)}}catch(y){throw Br(y,"median")}}var o=e({"number | BigNumber | Complex | Unit":function(c){return c}}),l=e({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(c,h){return r(t(c,h),2)}});return e(jS,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(c,h){throw new Error("median(A, dim) is not yet supported")},"...":function(c){if(na(c))throw new TypeError("Scalar values expected in function median");return a(c)}})}),GS="mad",oL=["typed","abs","map","median","subtract"],od=R(GS,oL,n=>{var{typed:e,abs:t,map:r,median:i,subtract:s}=n;return e(GS,{"Array | Matrix":a,"...":function(l){return a(l)}});function a(o){if(o=gt(o.valueOf()),o.length===0)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var l=i(o);return i(r(o,function(u){return t(s(u,l))}))}catch(u){throw u instanceof TypeError&&u.message.includes("median")?new TypeError(u.message.replace("median","mad")):Br(u,"mad")}}}),fv="unbiased",XS="variance",uL=["typed","add","subtract","multiply","divide","mapSlices","isNaN"],So=R(XS,uL,n=>{var{typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o}=n;return e(XS,{"Array | Matrix":function(h){return l(h,fv)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(h,f){return u(h,f,fv)},"Array | Matrix, number | BigNumber, string":u,"...":function(h){return l(h,fv)}});function l(c,h){var f,d=0;if(c.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(Fn(c,function(y){try{f=f===void 0?y:t(f,y),d++}catch(v){throw Br(v,"variance",y)}}),d===0)throw new Error("Cannot calculate variance of an empty array");var p=s(f,d);if(f=void 0,Fn(c,function(y){var v=r(y,p);f=f===void 0?i(v,v):t(f,i(v,v))}),o(f))return f;switch(h){case"uncorrected":return s(f,d);case"biased":return s(f,d+1);case"unbiased":{var m=Xe(f)?f.mul(0):0;return d===1?m:s(f,d-1)}default:throw new Error('Unknown normalization "'+h+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(c,h,f){try{if(c.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return a(c,h,d=>l(d,f))}catch(d){throw Br(d,"variance")}}}),YS="quantileSeq",lL=["typed","?bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger","mapSlices"],No=R(YS,lL,n=>{var{typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d}=n;return e(YS,{"Array | Matrix, number | BigNumber":(S,g)=>m(S,g,!1),"Array | Matrix, number | BigNumber, number":(S,g,b)=>p(S,g,!1,b,m),"Array | Matrix, number | BigNumber, boolean":m,"Array | Matrix, number | BigNumber, boolean, number":(S,g,b,w)=>p(S,g,b,w,m),"Array | Matrix, Array | Matrix":(S,g)=>y(S,g,!1),"Array | Matrix, Array | Matrix, number":(S,g,b)=>p(S,g,!1,b,y),"Array | Matrix, Array | Matrix, boolean":y,"Array | Matrix, Array | Matrix, boolean, number":(S,g,b,w)=>p(S,g,b,w,y)});function p(S,g,b,w,x){return d(S,w,N=>x(N,g,b))}function m(S,g,b){var w,x=S.valueOf();if(c(g,0))throw new Error("N/prob must be non-negative");if(h(g,1))return Je(g)?v(x,g,b):t(v(x,g,b));if(f(g,1)){if(!u(g))throw new Error("N must be a positive integer");if(f(g,4294967295))throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var N=r(g,1);w=[];for(var D=0;c(D,g);D++){var C=s(D+1,N);w.push(v(x,C,b))}return Je(g)?w:t(w)}}function y(S,g,b){for(var w=S.valueOf(),x=g.valueOf(),N=[],D=0;D<x.length;++D)N.push(v(w,x[D],b));return N}function v(S,g,b){var w=gt(S),x=w.length;if(x===0)throw new Error("Cannot calculate quantile of an empty sequence");var N=Je(g)?g*(x-1):g.times(x-1),D=Je(g)?Math.floor(N):N.floor().toNumber(),C=Je(g)?N%1:N.minus(D);if(u(N))return b?w[N]:o(w,Je(g)?N:N.valueOf());var A,E;if(b)A=w[D],E=w[D+1];else{E=o(w,D+1),A=w[D];for(var F=0;F<D;++F)l(w[F],A)>0&&(A=w[F])}return r(a(A,i(1,C)),a(E,C))}}),JS="std",cL=["typed","map","sqrt","variance"],Co=R(JS,cL,n=>{var{typed:e,map:t,sqrt:r,variance:i}=n;return e(JS,{"Array | Matrix":s,"Array | Matrix, string":s,"Array | Matrix, number | BigNumber":s,"Array | Matrix, number | BigNumber, string":s,"...":function(o){return s(o)}});function s(a,o){if(a.length===0)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{var l=i.apply(null,arguments);return Or(l)?t(l,r):r(l)}catch(u){throw u instanceof TypeError&&u.message.includes(" variance")?new TypeError(u.message.replace(" variance"," std")):u}}}),ZS="corr",hL=["typed","matrix","mean","sqrt","sum","add","subtract","multiply","pow","divide"],ud=R(ZS,hL,n=>{var{typed:e,matrix:t,sqrt:r,sum:i,add:s,subtract:a,multiply:o,pow:l,divide:u}=n;return e(ZS,{"Array, Array":function(d,p){return c(d,p)},"Matrix, Matrix":function(d,p){var m=c(d.toArray(),p.toArray());return Array.isArray(m)?t(m):m}});function c(f,d){var p=[];if(Array.isArray(f[0])&&Array.isArray(d[0])){if(f.length!==d.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same length.");for(var m=0;m<f.length;m++){if(f[m].length!==d[m].length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same number of elements.");p.push(h(f[m],d[m]))}return p}else{if(f.length!==d.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same number of elements.");return h(f,d)}}function h(f,d){var p=f.length,m=i(f),y=i(d),v=f.reduce((x,N,D)=>s(x,o(N,d[D])),0),S=i(f.map(x=>l(x,2))),g=i(d.map(x=>l(x,2))),b=a(o(p,v),o(m,y)),w=r(o(a(o(p,S),l(m,2)),a(o(p,g),l(y,2))));return u(b,w)}}),QS="combinations",fL=["typed"],ld=R(QS,fL,n=>{var{typed:e}=n;return e(QS,{"number, number":Wb,"BigNumber, BigNumber":function(r,i){var s=r.constructor,a,o,l=r.minus(i),u=new s(1);if(!KS(r)||!KS(i))throw new TypeError("Positive integer value expected in function combinations");if(i.gt(r))throw new TypeError("k must be less than n in function combinations");if(a=u,i.lt(l))for(o=u;o.lte(l);o=o.plus(u))a=a.times(i.plus(o)).dividedBy(o);else for(o=u;o.lte(i);o=o.plus(u))a=a.times(l.plus(o)).dividedBy(o);return a}})});function KS(n){return n.isInteger()&&n.gte(0)}var eN="combinationsWithRep",dL=["typed"],cd=R(eN,dL,n=>{var{typed:e}=n;return e(eN,{"number, number":function(r,i){if(!ke(r)||r<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!ke(i)||i<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(r<1)throw new TypeError("k must be less than or equal to n + k - 1");if(i<r-1){var s=sn(r,r+i-1);return s/sn(1,i)}var a=sn(i+1,r+i-1);return a/sn(1,r-1)},"BigNumber, BigNumber":function(r,i){var s=r.constructor,a,o,l=new s(1),u=r.minus(l);if(!tN(r)||!tN(i))throw new TypeError("Positive integer value expected in function combinationsWithRep");if(r.lt(l))throw new TypeError("k must be less than or equal to n + k - 1 in function combinationsWithRep");if(a=l,i.lt(u))for(o=l;o.lte(u);o=o.plus(l))a=a.times(i.plus(o)).dividedBy(o);else for(o=l;o.lte(i);o=o.plus(l))a=a.times(u.plus(o)).dividedBy(o);return a}})});function tN(n){return n.isInteger()&&n.gte(0)}var rN="gamma",pL=["typed","config","multiplyScalar","pow","BigNumber","Complex"],hd=R(rN,pL,n=>{var{typed:e,config:t,multiplyScalar:r,pow:i,BigNumber:s,Complex:a}=n;function o(u){if(u.im===0)return Lu(u.re);if(u.re<.5){var c=new a(1-u.re,-u.im),h=new a(Math.PI*u.re,Math.PI*u.im);return new a(Math.PI).div(h.sin()).div(o(c))}u=new a(u.re-1,u.im);for(var f=new a(oa[0],0),d=1;d<oa.length;++d){var p=new a(oa[d],0);f=f.add(p.div(u.add(d)))}var m=new a(u.re+Gb+.5,u.im),y=Math.sqrt(2*Math.PI),v=m.pow(u.add(.5)),S=m.neg().exp();return f.mul(y).mul(v).mul(S)}return e(rN,{number:Lu,Complex:o,BigNumber:function(c){if(c.isInteger())return c.isNegative()||c.isZero()?new s(1/0):l(c.minus(1));if(!c.isFinite())return new s(c.isNegative()?NaN:1/0);throw new Error("Integer BigNumber expected")}});function l(u){if(u<8)return new s([1,1,2,6,24,120,720,5040][u]);var c=t.precision+(Math.log(u.toNumber())|0),h=s.clone({precision:c});if(u%2===1)return u.times(l(new s(u-1)));for(var f=u,d=new h(u),p=u.toNumber();f>2;)f-=2,p+=f,d=d.times(p);return new s(d.toPrecision(s.precision))}}),iN="lgamma",mL=["Complex","typed"],fd=R(iN,mL,n=>{var{Complex:e,typed:t}=n,r=7,i=7,s=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return t(iN,{number:Iu,Complex:a,BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(u){var c=6.283185307179586,h=1.1447298858494002,f=.1;if(u.isNaN())return new e(NaN,NaN);if(u.im===0)return new e(Iu(u.re),0);if(u.re>=r||Math.abs(u.im)>=i)return o(u);if(u.re<=f){var d=rM(c,u.im)*Math.floor(.5*u.re+.25),p=u.mul(Math.PI).sin().log(),m=a(new e(1-u.re,-u.im));return new e(h,d).sub(p).sub(m)}else return u.im>=0?l(u):l(u.conjugate()).conjugate()}function o(u){for(var c=u.sub(.5).mul(u.log()).sub(u).add(Xb),h=new e(1,0).div(u),f=h.div(u),d=s[0],p=s[1],m=2*f.re,y=f.re*f.re+f.im*f.im,v=2;v<8;v++){var S=p;p=-y*d+s[v],d=m*d+S}var g=h.mul(f.mul(d).add(p));return c.add(g)}function l(u){var c=0,h=0,f=u;for(u=u.add(1);u.re<=r;){f=f.mul(u);var d=f.im<0?1:0;d!==0&&h===0&&c++,h=d,u=u.add(1)}return o(u).sub(f.log()).sub(new e(0,c*2*Math.PI*1))}}),nN="factorial",gL=["typed","gamma"],dd=R(nN,gL,n=>{var{typed:e,gamma:t}=n;return e(nN,{number:function(i){if(i<0)throw new Error("Value must be non-negative");return t(i+1)},BigNumber:function(i){if(i.isNegative())throw new Error("Value must be non-negative");return t(i.plus(1))},"Array | Matrix":e.referToSelf(r=>i=>et(i,r))})}),sN="kldivergence",vL=["typed","matrix","divide","sum","multiply","map","dotDivide","log","isNumeric"],pd=R(sN,vL,n=>{var{typed:e,matrix:t,divide:r,sum:i,multiply:s,map:a,dotDivide:o,log:l,isNumeric:u}=n;return e(sN,{"Array, Array":function(f,d){return c(t(f),t(d))},"Matrix, Array":function(f,d){return c(f,t(d))},"Array, Matrix":function(f,d){return c(t(f),d)},"Matrix, Matrix":function(f,d){return c(f,d)}});function c(h,f){var d=f.size().length,p=h.size().length;if(d>1)throw new Error("first object must be one dimensional");if(p>1)throw new Error("second object must be one dimensional");if(d!==p)throw new Error("Length of two vectors must be equal");var m=i(h);if(m===0)throw new Error("Sum of elements in first object must be non zero");var y=i(f);if(y===0)throw new Error("Sum of elements in second object must be non zero");var v=r(h,i(h)),S=r(f,i(f)),g=i(s(v,a(o(v,S),b=>l(b))));return u(g)?g:Number.NaN}}),aN="multinomial",yL=["typed","add","divide","multiply","factorial","isInteger","isPositive"],md=R(aN,yL,n=>{var{typed:e,add:t,divide:r,multiply:i,factorial:s,isInteger:a,isPositive:o}=n;return e(aN,{"Array | Matrix":function(u){var c=0,h=1;return Fn(u,function(f){if(!a(f)||!o(f))throw new TypeError("Positive integer value expected in function multinomial");c=t(c,f),h=i(h,s(f))}),r(s(c),h)}})}),oN="permutations",bL=["typed","factorial"],gd=R(oN,bL,n=>{var{typed:e,factorial:t}=n;return e(oN,{"number | BigNumber":t,"number, number":function(i,s){if(!ke(i)||i<0)throw new TypeError("Positive integer value expected in function permutations");if(!ke(s)||s<0)throw new TypeError("Positive integer value expected in function permutations");if(s>i)throw new TypeError("second argument k must be less than or equal to first argument n");return sn(i-s+1,i)},"BigNumber, BigNumber":function(i,s){var a,o;if(!uN(i)||!uN(s))throw new TypeError("Positive integer value expected in function permutations");if(s.gt(i))throw new TypeError("second argument k must be less than or equal to first argument n");var l=i.mul(0).add(1);for(a=l,o=i.minus(s).plus(1);o.lte(i);o=o.plus(1))a=a.times(o);return a}})});function uN(n){return n.isInteger()&&n.gte(0)}var dv={exports:{}};dv.exports,function(n){(function(e,t,r){function i(l){var u=this,c=o();u.next=function(){var h=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=h-(u.c=h|0)},u.c=1,u.s0=c(" "),u.s1=c(" "),u.s2=c(" "),u.s0-=c(l),u.s0<0&&(u.s0+=1),u.s1-=c(l),u.s1<0&&(u.s1+=1),u.s2-=c(l),u.s2<0&&(u.s2+=1),c=null}function s(l,u){return u.c=l.c,u.s0=l.s0,u.s1=l.s1,u.s2=l.s2,u}function a(l,u){var c=new i(l),h=u&&u.state,f=c.next;return f.int32=function(){return c.next()*4294967296|0},f.double=function(){return f()+(f()*2097152|0)*11102230246251565e-32},f.quick=f,h&&(typeof h=="object"&&s(h,c),f.state=function(){return s(c,{})}),f}function o(){var l=4022871197,u=function(c){c=String(c);for(var h=0;h<c.length;h++){l+=c.charCodeAt(h);var f=.02519603282416938*l;l=f>>>0,f-=l,f*=l,l=f>>>0,f-=l,l+=f*4294967296}return(l>>>0)*23283064365386963e-26};return u}t&&t.exports?t.exports=a:this.alea=a})(cs,n)}(dv);var xL=dv.exports,pv={exports:{}};pv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c<u.length+64;c++)l.x^=u.charCodeAt(c)|0,l.next()}function s(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xor128=a})(cs,n)}(pv);var wL=pv.exports,mv={exports:{}};mv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c<u.length+64;c++)l.x^=u.charCodeAt(c)|0,c==u.length&&(l.d=l.x<<10^l.x>>>4),l.next()}function s(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xorwow=a})(cs,n)}(mv);var SL=mv.exports,gv={exports:{}};gv.exports,function(n){(function(e,t,r){function i(o){var l=this;l.next=function(){var c=l.x,h=l.i,f,d;return f=c[h],f^=f>>>7,d=f^f<<24,f=c[h+1&7],d^=f^f>>>10,f=c[h+3&7],d^=f^f>>>3,f=c[h+4&7],d^=f^f<<7,f=c[h+7&7],f=f^f<<13,d^=f^f<<9,c[h]=d,l.i=h+1&7,d};function u(c,h){var f,d=[];if(h===(h|0))d[0]=h;else for(h=""+h,f=0;f<h.length;++f)d[f&7]=d[f&7]<<15^h.charCodeAt(f)+d[f+1&7]<<13;for(;d.length<8;)d.push(0);for(f=0;f<8&&d[f]===0;++f);for(f==8?d[7]=-1:d[f],c.x=d,c.i=0,f=256;f>0;--f)c.next()}u(l,o)}function s(o,l){return l.x=o.x.slice(),l.i=o.i,l}function a(o,l){o==null&&(o=+new Date);var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(c.x&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xorshift7=a})(cs,n)}(gv);var NL=gv.exports,vv={exports:{}};vv.exports,function(n){(function(e,t,r){function i(o){var l=this;l.next=function(){var c=l.w,h=l.X,f=l.i,d,p;return l.w=c=c+1640531527|0,p=h[f+34&127],d=h[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,p=h[f]=p^d,l.i=f,p+(c^c>>>16)|0};function u(c,h){var f,d,p,m,y,v=[],S=128;for(h===(h|0)?(d=h,h=null):(h=h+"\0",d=0,S=Math.max(S,h.length)),p=0,m=-32;m<S;++m)h&&(d^=h.charCodeAt((m+32)%h.length)),m===0&&(y=d),d^=d<<10,d^=d>>>15,d^=d<<4,d^=d>>>13,m>=0&&(y=y+1640531527|0,f=v[m&127]^=d+y,p=f==0?p+1:0);for(p>=128&&(v[(h&&h.length||0)&127]=-1),p=127,m=4*128;m>0;--m)d=v[p+34&127],f=v[p=p+1&127],d^=d<<13,f^=f<<17,d^=d>>>15,f^=f>>>12,v[p]=d^f;c.w=y,c.X=v,c.i=p}u(l,o)}function s(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function a(o,l){o==null&&(o=+new Date);var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(c.X&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.xor4096=a})(cs,n)}(vv);var CL=vv.exports,yv={exports:{}};yv.exports,function(n){(function(e,t,r){function i(o){var l=this,u="";l.next=function(){var h=l.b,f=l.c,d=l.d,p=l.a;return h=h<<25^h>>>7^f,f=f-d|0,d=d<<24^d>>>8^p,p=p-h|0,l.b=h=h<<20^h>>>12^f,l.c=f=f-d|0,l.d=d<<16^f>>>16^p,l.a=p-h|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c<u.length+20;c++)l.b^=u.charCodeAt(c)|0,l.next()}function s(o,l){return l.a=o.a,l.b=o.b,l.c=o.c,l.d=o.d,l}function a(o,l){var u=new i(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var f=u.next()>>>11,d=(u.next()>>>0)/4294967296,p=(f+d)/(1<<21);while(p===0);return p},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&s(c,u),h.state=function(){return s(u,{})}),h}t&&t.exports?t.exports=a:this.tychei=a})(cs,n)}(yv);var DL=yv.exports,lN={exports:{}};const vd=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})),AL=b3(vd);(function(n){(function(e,t,r){var i=256,s=6,a=52,o="random",l=r.pow(i,s),u=r.pow(2,a),c=u*2,h=i-1,f;function d(b,w,x){var N=[];w=w==!0?{entropy:!0}:w||{};var D=v(y(w.entropy?[b,g(t)]:b??S(),3),N),C=new p(N),A=function(){for(var E=C.g(s),F=l,O=0;E<u;)E=(E+O)*i,F*=i,O=C.g(1);for(;E>=c;)E/=2,F/=2,O>>>=1;return(E+O)/F};return A.int32=function(){return C.g(4)|0},A.quick=function(){return C.g(4)/4294967296},A.double=A,v(g(C.S),t),(w.pass||x||function(E,F,O,k){return k&&(k.S&&m(k,C),E.state=function(){return m(C,{})}),O?(r[o]=E,F):E})(A,D,"global"in w?w.global:this==r,w.state)}function p(b){var w,x=b.length,N=this,D=0,C=N.i=N.j=0,A=N.S=[];for(x||(b=[x++]);D<i;)A[D]=D++;for(D=0;D<i;D++)A[D]=A[C=h&C+b[D%x]+(w=A[D])],A[C]=w;(N.g=function(E){for(var F,O=0,k=N.i,B=N.j,T=N.S;E--;)F=T[k=h&k+1],O=O*i+T[h&(T[k]=T[B=h&B+F])+(T[B]=F)];return N.i=k,N.j=B,O})(i)}function m(b,w){return w.i=b.i,w.j=b.j,w.S=b.S.slice(),w}function y(b,w){var x=[],N=typeof b,D;if(w&&N=="object")for(D in b)try{x.push(y(b[D],w-1))}catch{}return x.length?x:N=="string"?b:b+"\0"}function v(b,w){for(var x=b+"",N,D=0;D<x.length;)w[h&D]=h&(N^=w[h&D]*19)+x.charCodeAt(D++);return g(w)}function S(){try{var b;return f&&(b=f.randomBytes)?b=b(i):(b=new Uint8Array(i),(e.crypto||e.msCrypto).getRandomValues(b)),g(b)}catch{var w=e.navigator,x=w&&w.plugins;return[+new Date,e,x,e.screen,g(t)]}}function g(b){return String.fromCharCode.apply(0,b)}if(v(r.random(),t),n.exports){n.exports=d;try{f=AL}catch{}}else r["seed"+o]=d})(typeof self<"u"?self:cs,[],Math)})(lN);var EL=lN.exports,ML=xL,TL=wL,FL=SL,_L=NL,OL=CL,BL=DL,hs=EL;hs.alea=ML,hs.xor128=TL,hs.xorwow=FL,hs.xorshift7=_L,hs.xor4096=OL,hs.tychei=BL;var kL=hs;const cN=$c(kL);var PL=cN(Date.now());function pa(n){var e;function t(i){e=i===null?PL:cN(String(i))}t(n);function r(){return e()}return r}var hN="pickRandom",zL=["typed","config","?on"],yd=R(hN,zL,n=>{var{typed:e,config:t,on:r}=n,i=pa(t.randomSeed);return r&&r("config",function(a,o){a.randomSeed!==o.randomSeed&&(i=pa(a.randomSeed))}),e(hN,{"Array | Matrix":function(o){return s(o,{})},"Array | Matrix, Object":function(o,l){return s(o,l)},"Array | Matrix, number":function(o,l){return s(o,{number:l})},"Array | Matrix, Array | Matrix":function(o,l){return s(o,{weights:l})},"Array | Matrix, Array | Matrix, number":function(o,l,u){return s(o,{number:u,weights:l})},"Array | Matrix, number, Array | Matrix":function(o,l,u){return s(o,{number:l,weights:u})}});function s(a,o){var{number:l,weights:u,elementWise:c=!0}=o,h=typeof l>"u";h&&(l=1);var f=Re(a)?a.create:Re(u)?u.create:null;a=a.valueOf(),u&&(u=u.valueOf()),c===!0&&(a=gt(a),u=gt(u));var d=0;if(typeof u<"u"){if(u.length!==a.length)throw new Error("Weights must have the same length as possibles");for(var p=0,m=u.length;p<m;p++){if(!Je(u[p])||u[p]<0)throw new Error("Weights must be an array of positive numbers");d+=u[p]}}for(var y=a.length,v=[],S;v.length<l;){if(typeof u>"u")S=a[Math.floor(i()*y)];else for(var g=i()*d,b=0,w=a.length;b<w;b++)if(g-=u[b],g<0){S=a[b];break}v.push(S)}return h?v[0]:f?f(v):v}});function bv(n,e){var t=[];if(n=n.slice(0),n.length>1)for(var r=0,i=n.shift();r<i;r++)t.push(bv(n,e));else for(var s=0,a=n.shift();s<a;s++)t.push(e());return t}var fN="random",RL=["typed","config","?on"],bd=R(fN,RL,n=>{var{typed:e,config:t,on:r}=n,i=pa(t.randomSeed);return r&&r("config",function(o,l){o.randomSeed!==l.randomSeed&&(i=pa(o.randomSeed))}),e(fN,{"":()=>a(0,1),number:o=>a(0,o),"number, number":(o,l)=>a(o,l),"Array | Matrix":o=>s(o,0,1),"Array | Matrix, number":(o,l)=>s(o,0,l),"Array | Matrix, number, number":(o,l,u)=>s(o,l,u)});function s(o,l,u){var c=bv(o.valueOf(),()=>a(l,u));return Re(o)?o.create(c,"number"):c}function a(o,l){return o+i()*(l-o)}}),dN="randomInt",LL=["typed","config","log2","?on"],xd=R(dN,LL,n=>{var{typed:e,config:t,log2:r,on:i}=n,s=pa(t.randomSeed);return i&&i("config",function(u,c){u.randomSeed!==c.randomSeed&&(s=pa(u.randomSeed))}),e(dN,{"":()=>o(0,2),number:u=>o(0,u),"number, number":(u,c)=>o(u,c),bigint:u=>l(0n,u),"bigint, bigint":l,"Array | Matrix":u=>a(u,0,1),"Array | Matrix, number":(u,c)=>a(u,0,c),"Array | Matrix, number, number":(u,c,h)=>a(u,c,h)});function a(u,c,h){var f=bv(u.valueOf(),()=>o(c,h));return Re(u)?u.create(f,"number"):f}function o(u,c){return Math.floor(u+s()*(c-u))}function l(u,c){var h=2n**30n,f=c-u;if(f<=h)return u+BigInt(o(0,Number(f)));for(var d=r(f),p=f;p>=f;){p=0n;for(var m=0;m<d;++m)p=2n*p+(s()<.5?0n:1n)}return u+p}}),pN="stirlingS2",IL=["typed","addScalar","subtractScalar","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],wd=R(pN,IL,n=>{var{typed:e,addScalar:t,subtractScalar:r,multiplyScalar:i,divideScalar:s,pow:a,factorial:o,combinations:l,isNegative:u,isInteger:c,number:h,bignumber:f,larger:d}=n,p=[],m=[];return e(pN,{"number | BigNumber, number | BigNumber":function(v,S){if(!c(v)||u(v)||!c(S)||u(S))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(d(S,v))throw new TypeError("k must be less than or equal to n in function stirlingS2");var g=!(Je(v)&&Je(S)),b=g?m:p,w=g?f:h,x=h(v),N=h(S);if(b[x]&&b[x].length>N)return b[x][N];for(var D=0;D<=x;++D)if(b[D]||(b[D]=[w(D===0?1:0)]),D!==0)for(var C=b[D],A=b[D-1],E=C.length;E<=D&&E<=N;++E)E===D?C[E]=1:C[E]=t(i(w(E),A[E]),A[E-1]);return b[x][N]}})}),mN="bellNumbers",$L=["typed","addScalar","isNegative","isInteger","stirlingS2"],Sd=R(mN,$L,n=>{var{typed:e,addScalar:t,isNegative:r,isInteger:i,stirlingS2:s}=n;return e(mN,{"number | BigNumber":function(o){if(!i(o)||r(o))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var l=0,u=0;u<=o;u++)l=t(l,s(o,u));return l}})}),gN="catalan",qL=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],Nd=R(gN,qL,n=>{var{typed:e,addScalar:t,divideScalar:r,multiplyScalar:i,combinations:s,isNegative:a,isInteger:o}=n;return e(gN,{"number | BigNumber":function(u){if(!o(u)||a(u))throw new TypeError("Non-negative integer value expected in function catalan");return r(s(i(u,2),u),t(u,1))}})}),vN="composition",HL=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],Cd=R(vN,HL,n=>{var{typed:e,addScalar:t,combinations:r,isPositive:i,isNegative:s,isInteger:a,larger:o}=n;return e(vN,{"number | BigNumber, number | BigNumber":function(u,c){if(!a(u)||!i(u)||!a(c)||!i(c))throw new TypeError("Positive integer value expected in function composition");if(o(c,u))throw new TypeError("k must be less than or equal to n in function composition");return r(t(u,-1),t(c,-1))}})}),yN="leafCount",UL=["parse","typed"],Dd=R(yN,UL,n=>{var{parse:e,typed:t}=n;function r(i){var s=0;return i.forEach(a=>{s+=r(a)}),s||1}return t(yN,{Node:function(s){return r(s)}})});function bN(n){return ct(n)||qt(n)&&n.isUnary()&&ct(n.args[0])}function Ad(n){return!!(ct(n)||(qi(n)||qt(n))&&n.args.every(Ad)||Ai(n)&&Ad(n.content))}function xN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function xv(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?xN(Object(t),!0).forEach(function(r){Yt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):xN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var VL="simplifyUtil",WL=["FunctionNode","OperatorNode","SymbolNode"],wv=R(VL,WL,n=>{var{FunctionNode:e,OperatorNode:t,SymbolNode:r}=n,i=!0,s=!1,a="defaultF",o={add:{trivial:i,total:i,commutative:i,associative:i},unaryPlus:{trivial:i,total:i,commutative:i,associative:i},subtract:{trivial:s,total:i,commutative:s,associative:s},multiply:{trivial:i,total:i,commutative:i,associative:i},divide:{trivial:s,total:i,commutative:s,associative:s},paren:{trivial:i,total:i,commutative:i,associative:s},defaultF:{trivial:s,total:i,commutative:s,associative:s}},l={divide:{total:s},log:{total:s}},u={subtract:{total:s},abs:{trivial:i},log:{total:i}};function c(g,b){var w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o,x=a;if(typeof g=="string"?x=g:qt(g)?x=g.fn.toString():qi(g)?x=g.name:Ai(g)&&(x="paren"),Te(w,x)){var N=w[x];if(Te(N,b))return N[b];if(Te(o,x))return o[x][b]}if(Te(w,a)){var D=w[a];return Te(D,b)?D[b]:o[a][b]}if(Te(o,x)){var C=o[x];if(Te(C,b))return C[b]}return o[a][b]}function h(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o;return c(g,"commutative",b)}function f(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o;return c(g,"associative",b)}function d(g,b){var w=xv({},g);for(var x in b)Te(g,x)?w[x]=xv(xv({},b[x]),g[x]):w[x]=b[x];return w}function p(g,b){if(!g.args||g.args.length===0)return g;g.args=m(g,b);for(var w=0;w<g.args.length;w++)p(g.args[w],b)}function m(g,b){var w,x=[],N=function(C){for(var A=0;A<C.args.length;A++){var E=C.args[A];qt(E)&&w===E.op?N(E):x.push(E)}};return f(g,b)?(w=g.op,N(g),x):g.args}function y(g,b){if(!(!g.args||g.args.length===0)){for(var w=S(g),x=g.args.length,N=0;N<x;N++)y(g.args[N],b);if(x>2&&f(g,b)){for(var D=g.args.pop();g.args.length>0;)D=w([g.args.pop(),D]);g.args=D.args}}}function v(g,b){if(!(!g.args||g.args.length===0)){for(var w=S(g),x=g.args.length,N=0;N<x;N++)v(g.args[N],b);if(x>2&&f(g,b)){for(var D=g.args.shift();g.args.length>0;)D=w([D,g.args.shift()]);g.args=D.args}}}function S(g){return qt(g)?function(b){try{return new t(g.op,g.fn,b,g.implicit)}catch(w){return console.error(w),[]}}:function(b){return new e(new r(g.name),b)}}return{createMakeNodeFunction:S,hasProperty:c,isCommutative:h,isAssociative:f,mergeContext:d,flatten:p,allChildren:m,unflattenr:y,unflattenl:v,defaultContext:o,realContext:l,positiveContext:u}}),jL="simplify",GL=["typed","parse","equal","resolve","simplifyConstant","simplifyCore","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode","replacer"],Ed=R(jL,GL,n=>{var{typed:e,parse:t,equal:r,resolve:i,simplifyConstant:s,simplifyCore:a,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:h,ObjectNode:f,OperatorNode:d,ParenthesisNode:p,SymbolNode:m,replacer:y}=n,{hasProperty:v,isCommutative:S,isAssociative:g,mergeContext:b,flatten:w,unflattenr:x,unflattenl:N,createMakeNodeFunction:D,defaultContext:C,realContext:A,positiveContext:E}=wv({FunctionNode:c,OperatorNode:d,SymbolNode:m});e.addConversion({from:"Object",to:"Map",convert:Us});var F=e("simplify",{Node:L,"Node, Map":($,H)=>L($,!1,H),"Node, Map, Object":($,H,J)=>L($,!1,H,J),"Node, Array":L,"Node, Array, Map":L,"Node, Array, Map, Object":L});e.removeConversion({from:"Object",to:"Map",convert:Us}),F.defaultContext=C,F.realContext=A,F.positiveContext=E;function O($){return $.transform(function(H){return Ai(H)?O(H.content):H})}var k={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};F.rules=[a,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(cl*v) -> v * (-cl)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(cl*v) -> (-cl) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*cl) -> v * (-cl)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" vd * ( vd * n1 + n2)",r:"vd^2 * n1 + vd * n2"},{s:" vd * (vd^n4 * n1 + n2) -> vd^(1+n4) * n1 + vd * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * ( vd * n1 + n2) -> vd^(n3+1) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * (vd^n4 * n1 + n2) -> vd^(n3+n4) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},s,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"vd*n + vd",r:"vd*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*vd + vd -> (n+1)*vd",assuming:{multiply:{commutative:!1}}},{s:"vd + n*vd -> (1+n)*vd",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n^n1 * n -> n^(n1+1)",assuming:{divide:{total:!0},multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*cd + cd",r:"(n+1)*cd"},{s:"cd*n + cd -> cd*(n+1)",assuming:{multiply:{commutative:!1}}},{s:"cd + cd*n -> cd*(1+n)",assuming:{multiply:{commutative:!1}}},s,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"ce+ve -> ve+ce",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"vd*cd -> cd*vd",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{l:"n+-(n1)",r:"n-(n1)"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];function B($,H){var J={};if($.s){var K=$.s.split("->");if(K.length===2)J.l=K[0],J.r=K[1];else throw SyntaxError("Could not parse rule: "+$.s)}else J.l=$.l,J.r=$.r;J.l=O(t(J.l)),J.r=O(t(J.r));for(var te of["imposeContext","repeat","assuming"])te in $&&(J[te]=$[te]);if($.evaluate&&(J.evaluate=t($.evaluate)),g(J.l,H)){var fe=!S(J.l,H),le;fe&&(le=U());var Se=D(J.l),_e=U();J.expanded={},J.expanded.l=Se([J.l,_e]),w(J.expanded.l,H),x(J.expanded.l,H),J.expanded.r=Se([J.r,_e]),fe&&(J.expandedNC1={},J.expandedNC1.l=Se([le,J.l]),J.expandedNC1.r=Se([le,J.r]),J.expandedNC2={},J.expandedNC2.l=Se([le,J.expanded.l]),J.expandedNC2.r=Se([le,J.expanded.r]))}return J}function T($,H){for(var J=[],K=0;K<$.length;K++){var te=$[K],fe=void 0,le=typeof te;switch(le){case"string":te={s:te};case"object":fe=B(te,H);break;case"function":fe=te;break;default:throw TypeError("Unsupported type of rule: "+le)}J.push(fe)}return J}var I=0;function U(){return new m("_p"+I++)}function L($,H){var J=arguments.length>2&&arguments[2]!==void 0?arguments[2]:La(),K=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},te=K.consoleDebug;H=T(H||F.rules,K.context);var fe=i($,J);fe=O(fe);for(var le={},Se=fe.toString({parenthesis:"all"});!le[Se];){le[Se]=!0,I=0;var _e=Se;te&&console.log("Working on: ",Se);for(var Be=0;Be<H.length;Be++){var Ee="";if(typeof H[Be]=="function"?(fe=H[Be](fe,K),te&&(Ee=H[Be].name)):(w(fe,K.context),fe=ee(fe,H[Be],K.context),te&&(Ee="".concat(H[Be].l.toString()," -> ").concat(H[Be].r.toString()))),te){var Pe=fe.toString({parenthesis:"all"});Pe!==_e&&(console.log("Applying",Ee,"produced",Pe),_e=Pe)}N(fe,K.context)}Se=fe.toString({parenthesis:"all"})}return fe}function Y($,H,J){var K=$;if($)for(var te=0;te<$.length;++te){var fe=ee($[te],H,J);fe!==$[te]&&(K===$&&(K=$.slice()),K[te]=fe)}return K}function ee($,H,J){if(H.assuming){for(var K in H.assuming)for(var te in H.assuming[K])if(v(K,te,J)!==H.assuming[K][te])return $}var fe=b(H.imposeContext,J),le=$;if(le instanceof d||le instanceof c){var Se=Y(le.args,H,J);Se!==le.args&&(le=le.clone(),le.args=Se)}else if(le instanceof p){if(le.content){var _e=ee(le.content,H,J);_e!==le.content&&(le=new p(_e))}}else if(le instanceof l){var Be=Y(le.items,H,J);Be!==le.items&&(le=new l(Be))}else if(le instanceof o){var Ee=le.object;le.object&&(Ee=ee(le.object,H,J));var Pe=le.index;le.index&&(Pe=ee(le.index,H,J)),(Ee!==le.object||Pe!==le.index)&&(le=new o(Ee,Pe))}else if(le instanceof h){var q=Y(le.dimensions,H,J);q!==le.dimensions&&(le=new h(q))}else if(le instanceof f){var Z=!1,ne={};for(var P in le.properties)ne[P]=ee(le.properties[P],H,J),ne[P]!==le.properties[P]&&(Z=!0);Z&&(le=new f(ne))}var W=H.r,Q=ae(H.l,le,fe)[0];if(!Q&&H.expanded&&(W=H.expanded.r,Q=ae(H.expanded.l,le,fe)[0]),!Q&&H.expandedNC1&&(W=H.expandedNC1.r,Q=ae(H.expandedNC1.l,le,fe)[0],Q||(W=H.expandedNC2.r,Q=ae(H.expandedNC2.l,le,fe)[0])),Q){var re=le.implicit;le=W.clone(),re&&"implicit"in W&&(le.implicit=!0),le=le.transform(function(se){return se.isSymbolNode&&Te(Q.placeholders,se.name)?Q.placeholders[se.name].clone():se})}return H.repeat&&le!==$&&(le=ee(le,H,J)),le}function _($,H){var J=[],K,te,fe=D($);if(S($,H))for(var le=0;le<$.args.length;le++)te=$.args.slice(0),te.splice(le,1),K=te.length===1?te[0]:fe(te),J.push(fe([$.args[le],K]));else for(var Se=1;Se<$.args.length;Se++){var _e=$.args[0];Se>1&&(_e=fe($.args.slice(0,Se))),te=$.args.slice(Se),K=te.length===1?te[0]:fe(te),J.push(fe([_e,K]))}return J}function V($,H){var J={placeholders:{}};if(!$.placeholders&&!H.placeholders)return J;if($.placeholders){if(!H.placeholders)return $}else return H;for(var K in $.placeholders)if(Te($.placeholders,K)&&(J.placeholders[K]=$.placeholders[K],Te(H.placeholders,K)&&!oe($.placeholders[K],H.placeholders[K])))return null;for(var te in H.placeholders)Te(H.placeholders,te)&&(J.placeholders[te]=H.placeholders[te]);return J}function z($,H){var J=[];if($.length===0||H.length===0)return J;for(var K,te=0;te<$.length;te++)for(var fe=0;fe<H.length;fe++)K=V($[te],H[fe]),K&&J.push(K);return J}function de($){if($.length===0)return $;for(var H=$.reduce(z),J=[],K={},te=0;te<H.length;te++){var fe=JSON.stringify(H[te],y);K[fe]||(K[fe]=!0,J.push(H[te]))}return J}function ae($,H,J,K){var te=[{placeholders:{}}];if($ instanceof d&&H instanceof d||$ instanceof c&&H instanceof c){if($ instanceof d){if($.op!==H.op||$.fn!==H.fn)return[]}else if($ instanceof c&&$.name!==H.name)return[];if(H.args.length===1&&$.args.length===1||!g(H,J)&&H.args.length===$.args.length||K){for(var fe=[],le=0;le<$.args.length;le++){var Se=ae($.args[le],H.args[le],J);if(Se.length===0)break;fe.push(Se)}if(fe.length!==$.args.length){if(!S(H,J)||$.args.length===1)return[];if($.args.length>2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var _e=ae($.args[0],H.args[1],J);if(_e.length===0)return[];var Be=ae($.args[1],H.args[0],J);if(Be.length===0)return[];fe=[_e,Be]}te=de(fe)}else if(H.args.length>=2&&$.args.length===2){for(var Ee=_(H,J),Pe=[],q=0;q<Ee.length;q++){var Z=ae($,Ee[q],J,!0);Pe=Pe.concat(Z)}return Pe}else{if($.args.length>2)throw Error("Unexpected non-binary associative function: "+$.toString());return[]}}else if($ instanceof m){if($.name.length===0)throw new Error("Symbol in rule has 0 length...!?");if(k[$.name]){if($.name!==H.name)return[]}else switch($.name[1]>="a"&&$.name[1]<="z"?$.name.substring(0,2):$.name[0]){case"n":case"_p":te[0].placeholders[$.name]=H;break;case"c":case"cl":if(ct(H))te[0].placeholders[$.name]=H;else return[];break;case"v":if(!ct(H))te[0].placeholders[$.name]=H;else return[];break;case"vl":if(Xt(H))te[0].placeholders[$.name]=H;else return[];break;case"cd":if(bN(H))te[0].placeholders[$.name]=H;else return[];break;case"vd":if(!bN(H))te[0].placeholders[$.name]=H;else return[];break;case"ce":if(Ad(H))te[0].placeholders[$.name]=H;else return[];break;case"ve":if(!Ad(H))te[0].placeholders[$.name]=H;else return[];break;default:throw new Error("Invalid symbol in rule: "+$.name)}}else if($ instanceof u){if(!r($.value,H.value))return[]}else return[];return te}function oe($,H){if($ instanceof u&&H instanceof u){if(!r($.value,H.value))return!1}else if($ instanceof m&&H instanceof m){if($.name!==H.name)return!1}else if($ instanceof d&&H instanceof d||$ instanceof c&&H instanceof c){if($ instanceof d){if($.op!==H.op||$.fn!==H.fn)return!1}else if($ instanceof c&&$.name!==H.name)return!1;if($.args.length!==H.args.length)return!1;for(var J=0;J<$.args.length;J++)if(!oe($.args[J],H.args[J]))return!1}else return!1;return!0}return F}),XL="simplifyConstant",YL=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],Md=R(XL,YL,n=>{var{typed:e,config:t,mathWithTransform:r,matrix:i,fraction:s,bignumber:a,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:h,ObjectNode:f,OperatorNode:d,SymbolNode:p}=n,{isCommutative:m,isAssociative:y,allChildren:v,createMakeNodeFunction:S}=wv({FunctionNode:c,OperatorNode:d,SymbolNode:p}),g=e("simplifyConstant",{Node:B=>N(k(B,{})),"Node, Object":function(T,I){return N(k(T,I))}});function b(B){return vn(B)?B.valueOf():B instanceof Array?B.map(b):Re(B)?i(b(B.valueOf())):B}function w(B,T,I){try{return r[B].apply(null,T)}catch{return T=T.map(b),C(r[B].apply(null,T),I)}}var x=e({Fraction:E,number:function(T){return T<0?A(new u(-T)):new u(T)},BigNumber:function(T){return T<0?A(new u(-T)):new u(T)},bigint:function(T){return T<0n?A(new u(-T)):new u(T)},Complex:function(T){throw new Error("Cannot convert Complex number to Node")},string:function(T){return new u(T)},Matrix:function(T){return new l(T.valueOf().map(I=>x(I)))}});function N(B){return bt(B)?B:x(B)}function D(B,T){var I=T&&T.exactFractions!==!1;if(I&&isFinite(B)&&s){var U=s(B),L=T&&typeof T.fractionsLimit=="number"?T.fractionsLimit:1/0;if(U.valueOf()===B&&U.n<L&&U.d<L)return U}return B}var C=e({"string, Object":function(T,I){var U=wn(T,t);if(U==="BigNumber")return a===void 0&&rv(),a(T);if(U==="bigint")return BigInt(T);if(U==="Fraction")return s===void 0&&Cx(),s(T);var L=parseFloat(T);return D(L,I)},"Fraction, Object":function(T,I){return T},"BigNumber, Object":function(T,I){return T},"number, Object":function(T,I){return D(T,I)},"bigint, Object":function(T,I){return T},"Complex, Object":function(T,I){return T.im!==0?T:D(T.re,I)},"Matrix, Object":function(T,I){return i(D(T.valueOf()))},"Array, Object":function(T,I){return T.map(D)}});function A(B){return new d("-","unaryMinus",[B])}function E(B){var T=L=>t.number==="BigNumber"&&a?a(L):Number(L),I=B.s*B.n,U=I<0n?new d("-","unaryMinus",[new u(-T(I))]):new u(T(I));return B.d===1n?U:new d("/","divide",[U,new u(T(B.d))])}function F(B,T,I){if(!xn(T))return new o(N(B),N(T));if(Vr(B)||Re(B)){for(var U=Array.from(T.dimensions);U.length>0;)if(ct(U[0])&&typeof U[0].value!="string"){var L=C(U.shift().value,I);Vr(B)?B=B.items[L-1]:(B=B.valueOf()[L-1],B instanceof Array&&(B=i(B)))}else if(U.length>1&&ct(U[1])&&typeof U[1].value!="string"){var Y=C(U[1].value,I),ee=[],_=Vr(B)?B.items:B.valueOf();for(var V of _)if(Vr(V))ee.push(V.items[Y-1]);else if(Re(B))ee.push(V[Y-1]);else break;if(ee.length===_.length)Vr(B)?B=new l(ee):B=i(ee),U.splice(1,1);else break}else break;return U.length===T.dimensions.length?new o(N(B),T):U.length>0?(T=new h(U),new o(N(B),T)):B}if(js(B)&&T.dimensions.length===1&&ct(T.dimensions[0])){var z=T.dimensions[0].value;return z in B.properties?B.properties[z]:new u}return new o(N(B),T)}function O(B,T,I,U){var L=T.shift(),Y=T.reduce((ee,_)=>{if(!bt(_)){var V=ee.pop();if(bt(V))return[V,_];try{return ee.push(w(B,[V,_],U)),ee}catch{ee.push(V)}}ee.push(N(ee.pop()));var z=ee.length===1?ee[0]:I(ee);return[I([z,N(_)])]},[L]);return Y.length===1?Y[0]:I([Y[0],x(Y[1])])}function k(B,T){switch(B.type){case"SymbolNode":return B;case"ConstantNode":switch(typeof B.value){case"number":return C(B.value,T);case"bigint":return C(B.value,T);case"string":return B.value;default:if(!isNaN(B.value))return C(B.value,T)}return B;case"FunctionNode":if(r[B.name]&&r[B.name].rawArgs)return B;{var I=["add","multiply"];if(!I.includes(B.name)){var U=B.args.map(K=>k(K,T));if(!U.some(bt))try{return w(B.name,U,T)}catch{}if(B.name==="size"&&U.length===1&&Vr(U[0])){for(var L=[],Y=U[0];Vr(Y);)L.push(Y.items.length),Y=Y.items[0];return i(L)}return new c(B.name,U.map(N))}}case"OperatorNode":{var ee=B.fn.toString(),_,V,z=S(B);if(qt(B)&&B.isUnary())_=[k(B.args[0],T)],bt(_[0])?V=z(_):V=w(ee,_,T);else if(y(B,T.context))if(_=v(B,T.context),_=_.map(K=>k(K,T)),m(ee,T.context)){for(var de=[],ae=[],oe=0;oe<_.length;oe++)bt(_[oe])?ae.push(_[oe]):de.push(_[oe]);de.length>1?(V=O(ee,de,z,T),ae.unshift(V),V=O(ee,ae,z,T)):V=O(ee,_,z,T)}else V=O(ee,_,z,T);else _=B.args.map(K=>k(K,T)),V=O(ee,_,z,T);return V}case"ParenthesisNode":return k(B.content,T);case"AccessorNode":return F(k(B.object,T),k(B.index,T),T);case"ArrayNode":{var $=B.items.map(K=>k(K,T));return $.some(bt)?new l($.map(N)):i($)}case"IndexNode":return new h(B.dimensions.map(K=>g(K,T)));case"ObjectNode":{var H={};for(var J in B.properties)H[J]=g(B.properties[J],T);return new f(H)}case"AssignmentNode":case"BlockNode":case"FunctionAssignmentNode":case"RangeNode":case"ConditionalNode":default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(B.type))}}return g}),wN="simplifyCore",JL=["typed","parse","equal","isZero","add","subtract","multiply","divide","pow","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Td=R(wN,JL,n=>{var{typed:e,parse:t,equal:r,isZero:i,add:s,subtract:a,multiply:o,divide:l,pow:u,AccessorNode:c,ArrayNode:h,ConstantNode:f,FunctionNode:d,IndexNode:p,ObjectNode:m,OperatorNode:y,ParenthesisNode:v,SymbolNode:S}=n,g=new f(0),b=new f(1),w=new f(!0),x=new f(!1);function N(E){return qt(E)&&["and","not","or"].includes(E.op)}var{hasProperty:D,isCommutative:C}=wv({FunctionNode:d,OperatorNode:y,SymbolNode:S});function A(E){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},O=F?F.context:void 0;if(D(E,"trivial",O)){if(qi(E)&&E.args.length===1)return A(E.args[0],F);var k=!1,B=0;if(E.forEach(ae=>{++B,B===1&&(k=A(ae,F))}),B===1)return k}var T=E;if(qi(T)){var I=t4(T.name);if(I){if(T.args.length>2&&D(T,"associative",O))for(;T.args.length>2;){var U=T.args.pop(),L=T.args.pop();T.args.push(new y(I,T.name,[U,L]))}T=new y(I,T.name,T.args)}else return new d(A(T.fn),T.args.map(ae=>A(ae,F)))}if(qt(T)&&T.isUnary()){var Y=A(T.args[0],F);if(T.op==="~"&&qt(Y)&&Y.isUnary()&&Y.op==="~"||T.op==="not"&&qt(Y)&&Y.isUnary()&&Y.op==="not"&&N(Y.args[0]))return Y.args[0];var ee=!0;if(T.op==="-"&&qt(Y)&&(Y.isBinary()&&Y.fn==="subtract"&&(T=new y("-","subtract",[Y.args[1],Y.args[0]]),ee=!1),Y.isUnary()&&Y.op==="-"))return Y.args[0];if(ee)return new y(T.op,T.fn,[Y])}if(qt(T)&&T.isBinary()){var _=A(T.args[0],F),V=A(T.args[1],F);if(T.op==="+"){if(ct(_)&&i(_.value))return V;if(ct(V)&&i(V.value))return _;qt(V)&&V.isUnary()&&V.op==="-"&&(V=V.args[0],T=new y("-","subtract",[_,V]))}if(T.op==="-")return qt(V)&&V.isUnary()&&V.op==="-"?A(new y("+","add",[_,V.args[0]]),F):ct(_)&&i(_.value)?A(new y("-","unaryMinus",[V])):ct(V)&&i(V.value)?_:new y(T.op,T.fn,[_,V]);if(T.op==="*"){if(ct(_)){if(i(_.value))return g;if(r(_.value,1))return V}if(ct(V)){if(i(V.value))return g;if(r(V.value,1))return _;if(C(T,O))return new y(T.op,T.fn,[V,_],T.implicit)}return new y(T.op,T.fn,[_,V],T.implicit)}if(T.op==="/")return ct(_)&&i(_.value)?g:ct(V)&&r(V.value,1)?_:new y(T.op,T.fn,[_,V]);if(T.op==="^"&&ct(V)){if(i(V.value))return b;if(r(V.value,1))return _}if(T.op==="and"){if(ct(_))if(_.value){if(N(V))return V;if(ct(V))return V.value?w:x}else return x;if(ct(V))if(V.value){if(N(_))return _}else return x}if(T.op==="or"){if(ct(_)){if(_.value)return w;if(N(V))return V}if(ct(V)){if(V.value)return w;if(N(_))return _}}return new y(T.op,T.fn,[_,V])}if(qt(T))return new y(T.op,T.fn,T.args.map(ae=>A(ae,F)));if(Vr(T))return new h(T.items.map(ae=>A(ae,F)));if(en(T))return new c(A(T.object,F),A(T.index,F));if(xn(T))return new p(T.dimensions.map(ae=>A(ae,F)));if(js(T)){var z={};for(var de in T.properties)z[de]=A(T.properties[de],F);return new m(z)}return T}return e(wN,{Node:A,"Node,Object":A})}),ZL="resolve",QL=["typed","parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],Fd=R(ZL,QL,n=>{var{typed:e,parse:t,ConstantNode:r,FunctionNode:i,OperatorNode:s,ParenthesisNode:a}=n;function o(l,u){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;if(!u)return l;if(Xt(l)){if(c.has(l.name)){var h=Array.from(c).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(h,"}"))}var f=u.get(l.name);if(bt(f)){var d=new Set(c);return d.add(l.name),o(f,u,d)}else return typeof f=="number"?t(String(f)):f!==void 0?new r(f):l}else if(qt(l)){var p=l.args.map(function(y){return o(y,u,c)});return new s(l.op,l.fn,p,l.implicit)}else{if(Ai(l))return new a(o(l.content,u,c));if(qi(l)){var m=l.args.map(function(y){return o(y,u,c)});return new i(l.name,m)}}return l.map(y=>o(y,u,c))}return e("resolve",{Node:o,"Node, Map | null | undefined":o,"Node, Object":(l,u)=>o(l,Us(u)),"Array | Matrix":e.referToSelf(l=>u=>u.map(c=>l(c))),"Array | Matrix, null | undefined":e.referToSelf(l=>u=>u.map(c=>l(c))),"Array, Object":e.referTo("Array,Map",l=>(u,c)=>l(u,Us(c))),"Matrix, Object":e.referTo("Matrix,Map",l=>(u,c)=>l(u,Us(c))),"Array | Matrix, Map":e.referToSelf(l=>(u,c)=>u.map(h=>l(h,c)))})}),SN="symbolicEqual",KL=["parse","simplify","typed","OperatorNode"],_d=R(SN,KL,n=>{var{parse:e,simplify:t,typed:r,OperatorNode:i}=n;function s(a,o){var l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},u=new i("-","subtract",[a,o]),c=t(u,{},l);return ct(c)&&!c.value}return r(SN,{"Node, Node":s,"Node, Node, Object":s})}),NN="derivative",e8=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],Od=R(NN,e8,n=>{var{typed:e,config:t,parse:r,simplify:i,equal:s,isZero:a,numeric:o,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:h,SymbolNode:f}=n;function d(b,w){var x=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{simplify:!0},N=new Map,D=w.name;function C(E){var F=N.get(E);if(F!==void 0)return F;var O=v(C,E,D);return N.set(E,O),O}var A=S(b,C);return x.simplify?i(A):A}function p(b){var w=r(b);if(!w.isSymbolNode)throw new TypeError("Invalid variable. "+"Cannot parse ".concat(JSON.stringify(b)," into a variable in function derivative"));return w}var m=e(NN,{"Node, SymbolNode":d,"Node, SymbolNode, Object":d,"Node, string":(b,w)=>d(b,p(w)),"Node, string, Object":(b,w,x)=>d(b,p(w),x)});m._simplify=!0,m.toTex=function(b){return y.apply(null,b.args)};var y=e("_derivTex",{"Node, SymbolNode":function(w,x){return ct(w)&&Dt(w.value)==="string"?y(r(w.value).toString(),x.toString(),1):y(w.toTex(),x.toString(),1)},"Node, ConstantNode":function(w,x){if(Dt(x.value)==="string")return y(w,r(x.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(w,x,N){return y(w.toString(),x.name,N.value)},"string, string, number":function(w,x,N){var D;return N===1?D="{d\\over d"+x+"}":D="{d^{"+N+"}\\over d"+x+"^{"+N+"}}",D+"\\left[".concat(w,"\\right]")}}),v=e("_isConst",{"function, ConstantNode, string":function(){return!0},"function, SymbolNode, string":function(w,x,N){return x.name!==N},"function, ParenthesisNode, string":function(w,x,N){return w(x.content,N)},"function, FunctionAssignmentNode, string":function(w,x,N){return x.params.includes(N)?w(x.expr,N):!0},"function, FunctionNode | OperatorNode, string":function(w,x,N){return x.args.every(D=>w(D,N))}}),S=e("_derivative",{"ConstantNode, function":function(){return g(0)},"SymbolNode, function":function(w,x){return x(w)?g(0):g(1)},"ParenthesisNode, function":function(w,x){return new h(S(w.content,x))},"FunctionAssignmentNode, function":function(w,x){return x(w)?g(0):S(w.expr,x)},"FunctionNode, function":function(w,x){if(x(w))return g(0);var N=w.args[0],D,C=!1,A=!1,E;switch(w.name){case"cbrt":C=!0,E=new c("*","multiply",[g(3),new c("^","pow",[N,new c("/","divide",[g(2),g(3)])])]);break;case"sqrt":case"nthRoot":if(w.args.length===1)C=!0,E=new c("*","multiply",[g(2),new u("sqrt",[N])]);else if(w.args.length===2)return D=new c("/","divide",[g(1),w.args[1]]),S(new c("^","pow",[N,D]),x);break;case"log10":D=g(10);case"log":if(!D&&w.args.length===1)E=N.clone(),C=!0;else if(w.args.length===1&&D||w.args.length===2&&x(w.args[1]))E=new c("*","multiply",[N.clone(),new u("log",[D||w.args[1]])]),C=!0;else if(w.args.length===2)return S(new c("/","divide",[new u("log",[N]),new u("log",[w.args[1]])]),x);break;case"pow":if(w.args.length===2)return S(new c("^","pow",[N,w.args[1]]),x);break;case"exp":E=new u("exp",[N.clone()]);break;case"sin":E=new u("cos",[N.clone()]);break;case"cos":E=new c("-","unaryMinus",[new u("sin",[N.clone()])]);break;case"tan":E=new c("^","pow",[new u("sec",[N.clone()]),g(2)]);break;case"sec":E=new c("*","multiply",[w,new u("tan",[N.clone()])]);break;case"csc":A=!0,E=new c("*","multiply",[w,new u("cot",[N.clone()])]);break;case"cot":A=!0,E=new c("^","pow",[new u("csc",[N.clone()]),g(2)]);break;case"asin":C=!0,E=new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])]);break;case"acos":C=!0,A=!0,E=new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])]);break;case"atan":C=!0,E=new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)]);break;case"asec":C=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acsc":C=!0,A=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acot":C=!0,A=!0,E=new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)]);break;case"sinh":E=new u("cosh",[N.clone()]);break;case"cosh":E=new u("sinh",[N.clone()]);break;case"tanh":E=new c("^","pow",[new u("sech",[N.clone()]),g(2)]);break;case"sech":A=!0,E=new c("*","multiply",[w,new u("tanh",[N.clone()])]);break;case"csch":A=!0,E=new c("*","multiply",[w,new u("coth",[N.clone()])]);break;case"coth":A=!0,E=new c("^","pow",[new u("csch",[N.clone()]),g(2)]);break;case"asinh":C=!0,E=new u("sqrt",[new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)])]);break;case"acosh":C=!0,E=new u("sqrt",[new c("-","subtract",[new c("^","pow",[N.clone(),g(2)]),g(1)])]);break;case"atanh":C=!0,E=new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])]);break;case"asech":C=!0,A=!0,E=new c("*","multiply",[N.clone(),new u("sqrt",[new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])])])]);break;case"acsch":C=!0,A=!0,E=new c("*","multiply",[new u("abs",[N.clone()]),new u("sqrt",[new c("+","add",[new c("^","pow",[N.clone(),g(2)]),g(1)])])]);break;case"acoth":C=!0,A=!0,E=new c("-","subtract",[g(1),new c("^","pow",[N.clone(),g(2)])]);break;case"abs":E=new c("/","divide",[new u(new f("abs"),[N.clone()]),N.clone()]);break;case"gamma":default:throw new Error('Cannot process function "'+w.name+'" in derivative: the function is not supported, undefined, or the number of arguments passed to it are not supported')}var F,O;C?(F="/",O="divide"):(F="*",O="multiply");var k=S(N,x);return A&&(k=new c("-","unaryMinus",[k])),new c(F,O,[k,E])},"OperatorNode, function":function(w,x){if(x(w))return g(0);if(w.op==="+")return new c(w.op,w.fn,w.args.map(function(T){return S(T,x)}));if(w.op==="-"){if(w.isUnary())return new c(w.op,w.fn,[S(w.args[0],x)]);if(w.isBinary())return new c(w.op,w.fn,[S(w.args[0],x),S(w.args[1],x)])}if(w.op==="*"){var N=w.args.filter(function(T){return x(T)});if(N.length>0){var D=w.args.filter(function(T){return!x(T)}),C=D.length===1?D[0]:new c("*","multiply",D),A=N.concat(S(C,x));return new c("*","multiply",A)}return new c("+","add",w.args.map(function(T){return new c("*","multiply",w.args.map(function(I){return I===T?S(I,x):I.clone()}))}))}if(w.op==="/"&&w.isBinary()){var E=w.args[0],F=w.args[1];return x(F)?new c("/","divide",[S(E,x),F]):x(E)?new c("*","multiply",[new c("-","unaryMinus",[E]),new c("/","divide",[S(F,x),new c("^","pow",[F.clone(),g(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[S(E,x),F.clone()]),new c("*","multiply",[E.clone(),S(F,x)])]),new c("^","pow",[F.clone(),g(2)])])}if(w.op==="^"&&w.isBinary()){var O=w.args[0],k=w.args[1];if(x(O))return ct(O)&&(a(O.value)||s(O.value,1))?g(0):new c("*","multiply",[w,new c("*","multiply",[new u("log",[O.clone()]),S(k.clone(),x)])]);if(x(k)){if(ct(k)){if(a(k.value))return g(0);if(s(k.value,1))return S(O,x)}var B=new c("^","pow",[O.clone(),new c("-","subtract",[k,g(1)])]);return new c("*","multiply",[k.clone(),new c("*","multiply",[S(O,x),B])])}return new c("*","multiply",[new c("^","pow",[O.clone(),k.clone()]),new c("+","add",[new c("*","multiply",[S(O,x),new c("/","divide",[k.clone(),O.clone()])]),new c("*","multiply",[S(k,x),new u("log",[O.clone()])])])])}throw new Error('Cannot process operator "'+w.op+'" in derivative: the operator is not supported, undefined, or the number of arguments passed to it are not supported')}});function g(b,w){return new l(o(b,wn(String(b),t)))}return m}),CN="rationalize",t8=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyConstant","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],Bd=R(CN,t8,n=>{var{config:e,typed:t,equal:r,isZero:i,add:s,subtract:a,multiply:o,divide:l,pow:u,parse:c,simplifyConstant:h,simplifyCore:f,simplify:d,fraction:p,bignumber:m,mathWithTransform:y,matrix:v,AccessorNode:S,ArrayNode:g,ConstantNode:b,FunctionNode:w,IndexNode:x,ObjectNode:N,OperatorNode:D,SymbolNode:C,ParenthesisNode:A}=n;function E(T){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,L=O(),Y=F(T,I,!0,L.firstRules),ee=Y.variables.length,_={exactFractions:!1},V={exactFractions:!0};if(T=Y.expression,ee>=1){T=k(T);var z,de,ae=!0,oe=!1;T=d(T,L.firstRules,{},_);for(var $;de=ae?L.distrDivRules:L.sucDivRules,T=d(T,de,{},V),ae=!ae,$=T.toString(),$!==z;)oe=!0,z=$;oe&&(T=d(T,L.firstRulesAgain,{},_)),T=d(T,L.finalRules,{},_)}var H=[],J={};return T.type==="OperatorNode"&&T.isBinary()&&T.op==="/"?(ee===1&&(T.args[0]=B(T.args[0],H),T.args[1]=B(T.args[1])),U&&(J.numerator=T.args[0],J.denominator=T.args[1])):(ee===1&&(T=B(T,H)),U&&(J.numerator=T,J.denominator=null)),U?(J.coefficients=H,J.variables=Y.variables,J.expression=T,J):T}return t(CN,{Node:E,"Node, boolean":(T,I)=>E(T,{},I),"Node, Object":E,"Node, Object, boolean":E});function F(T,I,U,L){var Y=[],ee=d(T,L,I,{exactFractions:!1});U=!!U;var _="+-*"+(U?"/":"");z(ee);var V={};return V.expression=ee,V.variables=Y,V;function z(de){var ae=de.type;if(ae==="FunctionNode")throw new Error("There is an unsolved function call");if(ae==="OperatorNode")if(de.op==="^"){if(de.args[1].type!=="ConstantNode"||!ke(parseFloat(de.args[1].value)))throw new Error("There is a non-integer exponent");z(de.args[0])}else{if(!_.includes(de.op))throw new Error("Operator "+de.op+" invalid in polynomial expression");for(var oe=0;oe<de.args.length;oe++)z(de.args[oe])}else if(ae==="SymbolNode"){var $=de.name,H=Y.indexOf($);H===-1&&Y.push($)}else if(ae==="ParenthesisNode")z(de.content);else if(ae!=="ConstantNode")throw new Error("type "+ae+" is not allowed in polynomial expression")}}function O(){var T=[f,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},h,{l:"n*(n1^-1)",r:"n/n1"},{l:"n*n1^-n2",r:"n/n1^n2"},{l:"n1^-1",r:"1/n1"},{l:"n*(n1/n2)",r:"(n*n1)/n2"},{l:"1*n",r:"n"}],I=[{l:"(-n1)/(-n2)",r:"n1/n2"},{l:"(-n1)*(-n2)",r:"n1*n2"},{l:"n1--n2",r:"n1+n2"},{l:"n1-n2",r:"n1+(-n2)"},{l:"(n1+n2)*n3",r:"(n1*n3 + n2*n3)"},{l:"n1*(n2+n3)",r:"(n1*n2+n1*n3)"},{l:"c1*n + c2*n",r:"(c1+c2)*n"},{l:"c1*n + n",r:"(c1+1)*n"},{l:"c1*n - c2*n",r:"(c1-c2)*n"},{l:"c1*n - n",r:"(c1-1)*n"},{l:"v/c",r:"(1/c)*v"},{l:"v/-c",r:"-(1/c)*v"},{l:"-v*-c",r:"c*v"},{l:"-v*c",r:"-c*v"},{l:"v*-c",r:"-c*v"},{l:"v*c",r:"c*v"},{l:"-(-n1*n2)",r:"(n1*n2)"},{l:"-(n1*n2)",r:"(-n1*n2)"},{l:"-(-n1+n2)",r:"(n1-n2)"},{l:"-(n1+n2)",r:"(-n1-n2)"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"},{l:"-(-n1/n2)",r:"(n1/n2)"},{l:"-(n1/n2)",r:"(-n1/n2)"}],U=[{l:"(n1/n2 + n3/n4)",r:"((n1*n4 + n3*n2)/(n2*n4))"},{l:"(n1/n2 + n3)",r:"((n1 + n3*n2)/n2)"},{l:"(n1 + n2/n3)",r:"((n1*n3 + n2)/n3)"}],L=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],Y={};return Y.firstRules=T.concat(I,L),Y.distrDivRules=U,Y.sucDivRules=L,Y.firstRulesAgain=T.concat(I),Y.finalRules=[f,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},h,{l:"n*-n^n1",r:"-n^(n1+1)"},{l:"n*n^n1",r:"n^(n1+1)"},{l:"n^n1*-n^n2",r:"-n^(n1+n2)"},{l:"n^n1*n^n2",r:"n^(n1+n2)"},{l:"n^n1*-n",r:"-n^(n1+1)"},{l:"n^n1*n",r:"n^(n1+1)"},{l:"n^n1/-n",r:"-n^(n1-1)"},{l:"n^n1/n",r:"n^(n1-1)"},{l:"n/-n^n1",r:"-n^(1-n1)"},{l:"n/n^n1",r:"n^(1-n1)"},{l:"n^n1/-n^n2",r:"n^(n1-n2)"},{l:"n^n1/n^n2",r:"n^(n1-n2)"},{l:"n1+(-n2*n3)",r:"n1-n2*n3"},{l:"v*(-c)",r:"-c*v"},{l:"n1+-n2",r:"n1-n2"},{l:"v*c",r:"c*v"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"}],Y}function k(T,I,U){var L=T.type,Y=arguments.length>1;if(L==="OperatorNode"&&T.isBinary()){var ee=!1,_;if(T.op==="^"&&(T.args[0].type==="ParenthesisNode"||T.args[0].type==="OperatorNode")&&T.args[1].type==="ConstantNode"&&(_=parseFloat(T.args[1].value),ee=_>=2&&ke(_)),ee){if(_>2){var V=T.args[0],z=new D("^","pow",[T.args[0].cloneDeep(),new b(_-1)]);T=new D("*","multiply",[V,z])}else T=new D("*","multiply",[T.args[0],T.args[0].cloneDeep()]);Y&&(U==="content"?I.content=T:I.args[U]=T)}}if(L==="ParenthesisNode")k(T.content,T,"content");else if(L!=="ConstantNode"&&L!=="SymbolNode")for(var de=0;de<T.args.length;de++)k(T.args[de],T,de);if(!Y)return T}function B(T,I){I===void 0&&(I=[]),I[0]=0;var U={};U.cte=1,U.oper="+",U.fire="";var L=0,Y="";$(T,null,U),L=I.length-1;for(var ee=!0,_,V=L;V>=0;V--)if(I[V]!==0){var z=new b(ee?I[V]:Math.abs(I[V])),de=I[V]<0?"-":"+";if(V>0){var ae=new C(Y);if(V>1){var oe=new b(V);ae=new D("^","pow",[ae,oe])}I[V]===-1&&ee?z=new D("-","unaryMinus",[ae]):Math.abs(I[V])===1?z=ae:z=new D("*","multiply",[z,ae])}ee?_=z:de==="+"?_=new D("+","add",[_,z]):_=new D("-","subtract",[_,z]),ee=!1}if(ee)return new b(0);return _;function $(H,J,K){var te=H.type;if(te==="FunctionNode")throw new Error("There is an unsolved function call");if(te==="OperatorNode"){if(!"+-*^".includes(H.op))throw new Error("Operator "+H.op+" invalid");if(J!==null){if((H.fn==="unaryMinus"||H.fn==="pow")&&J.fn!=="add"&&J.fn!=="subtract"&&J.fn!=="multiply")throw new Error("Invalid "+H.op+" placing");if((H.fn==="subtract"||H.fn==="add"||H.fn==="multiply")&&J.fn!=="add"&&J.fn!=="subtract")throw new Error("Invalid "+H.op+" placing");if((H.fn==="subtract"||H.fn==="add"||H.fn==="unaryMinus")&&K.noFil!==0)throw new Error("Invalid "+H.op+" placing")}(H.op==="^"||H.op==="*")&&(K.fire=H.op);for(var fe=0;fe<H.args.length;fe++)H.fn==="unaryMinus"&&(K.oper="-"),(H.op==="+"||H.fn==="subtract")&&(K.fire="",K.cte=1,K.oper=fe===0?"+":H.op),K.noFil=fe,$(H.args[fe],H,K)}else if(te==="SymbolNode"){if(H.name!==Y&&Y!=="")throw new Error("There is more than one variable");if(Y=H.name,J===null){I[1]=1;return}if(J.op==="^"&&K.noFil!==0)throw new Error("In power the variable should be the first parameter");if(J.op==="*"&&K.noFil!==1)throw new Error("In multiply the variable should be the second parameter");(K.fire===""||K.fire==="*")&&(L<1&&(I[1]=0),I[1]+=K.cte*(K.oper==="+"?1:-1),L=Math.max(1,L))}else if(te==="ConstantNode"){var le=parseFloat(H.value);if(J===null){I[0]=le;return}if(J.op==="^"){if(K.noFil!==1)throw new Error("Constant cannot be powered");if(!ke(le)||le<=0)throw new Error("Non-integer exponent is not allowed");for(var Se=L+1;Se<le;Se++)I[Se]=0;le>L&&(I[le]=0),I[le]+=K.cte*(K.oper==="+"?1:-1),L=Math.max(le,L);return}K.cte=le,K.fire===""&&(I[0]+=K.cte*(K.oper==="+"?1:-1))}else throw new Error("Type "+te+" is not allowed")}}}),DN="zpk2tf",r8=["typed","add","multiply","Complex","number"],kd=R(DN,r8,n=>{var{typed:e,add:t,multiply:r,Complex:i,number:s}=n;return e(DN,{"Array,Array,number":function(u,c,h){return a(u,c,h)},"Array,Array":function(u,c){return a(u,c,1)},"Matrix,Matrix,number":function(u,c,h){return a(u.valueOf(),c.valueOf(),h)},"Matrix,Matrix":function(u,c){return a(u.valueOf(),c.valueOf(),1)}});function a(l,u,c){l.some(S=>S.type==="BigNumber")&&(l=l.map(S=>s(S))),u.some(S=>S.type==="BigNumber")&&(u=u.map(S=>s(S)));for(var h=[i(1,0)],f=[i(1,0)],d=0;d<l.length;d++){var p=l[d];typeof p=="number"&&(p=i(p,0)),h=o(h,[i(1,0),i(-p.re,-p.im)])}for(var m=0;m<u.length;m++){var y=u[m];typeof y=="number"&&(y=i(y,0)),f=o(f,[i(1,0),i(-y.re,-y.im)])}for(var v=0;v<h.length;v++)h[v]=r(h[v],c);return[h,f]}function o(l,u){for(var c=[],h=0;h<l.length+u.length-1;h++){c[h]=i(0,0);for(var f=0;f<l.length;f++)h-f>=0&&h-f<u.length&&(c[h]=t(c[h],r(l[f],u[h-f])))}return c}}),AN="freqz",i8=["typed","add","multiply","Complex","divide","matrix"],Pd=R(AN,i8,n=>{var{typed:e,add:t,multiply:r,Complex:i,divide:s,matrix:a}=n;return e(AN,{"Array, Array":function(c,h){var f=l(512);return o(c,h,f)},"Array, Array, Array":function(c,h,f){return o(c,h,f)},"Array, Array, number":function(c,h,f){if(f<0)throw new Error("w must be a positive number");var d=l(f);return o(c,h,d)},"Matrix, Matrix":function(c,h){var f=l(512),{w:d,h:p}=o(c.valueOf(),h.valueOf(),f);return{w:a(d),h:a(p)}},"Matrix, Matrix, Matrix":function(c,h,f){var{h:d}=o(c.valueOf(),h.valueOf(),f.valueOf());return{h:a(d),w:a(f)}},"Matrix, Matrix, number":function(c,h,f){if(f<0)throw new Error("w must be a positive number");var d=l(f),{h:p}=o(c.valueOf(),h.valueOf(),d);return{h:a(p),w:a(d)}}});function o(u,c,h){for(var f=[],d=[],p=0;p<h.length;p++){for(var m=i(0,0),y=i(0,0),v=0;v<u.length;v++)m=t(m,r(u[v],i(Math.cos(-v*h[p]),Math.sin(-v*h[p]))));for(var S=0;S<c.length;S++)y=t(y,r(c[S],i(Math.cos(-S*h[p]),Math.sin(-S*h[p]))));f.push(m),d.push(y)}for(var g=[],b=0;b<f.length;b++)g.push(s(f[b],d[b]));return{h:g,w:h}}function l(u){for(var c=[],h=0;h<u;h++)c.push(h/u*Math.PI);return c}}),n8="reviver",s8=["classes"],zd=R(n8,s8,n=>{var{classes:e}=n;return function(r,i){var s=e[i&&i.mathjs];return s&&typeof s.fromJSON=="function"?s.fromJSON(i):i}}),a8="replacer",o8=[],Rd=R(a8,o8,()=>function(e,t){return typeof t=="number"&&(!isFinite(t)||isNaN(t))?{mathjs:"number",value:String(t)}:typeof t=="bigint"?{mathjs:"bigint",value:String(t)}:t}),u8="14.9.1",Ld=R("true",[],()=>!0),Id=R("false",[],()=>!1),$d=R("null",[],()=>null),qd=ei("Infinity",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1/0):1/0}),Hd=ei("NaN",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(NaN):NaN}),Ud=ei("pi",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?sv(t):PT}),Vd=ei("tau",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?K3(t):zT}),Wd=ei("e",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?Z3(t):RT}),jd=ei("phi",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?Q3(t):LT}),Gd=ei("LN2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(2).ln():Math.LN2}),Xd=ei("LN10",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(10).ln():Math.LN10}),Yd=ei("LOG2E",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1).div(new t(2).ln()):Math.LOG2E}),Jd=ei("LOG10E",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(1).div(new t(10).ln()):Math.LOG10E}),Zd=ei("SQRT1_2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t("0.5").sqrt():Math.SQRT1_2}),Qd=ei("SQRT2",["config","?BigNumber"],n=>{var{config:e,BigNumber:t}=n;return e.number==="BigNumber"?new t(2).sqrt():Math.SQRT2}),Kd=ei("i",["Complex"],n=>{var{Complex:e}=n;return e.I}),Sv=R("PI",["pi"],n=>{var{pi:e}=n;return e}),Nv=R("E",["e"],n=>{var{e}=n;return e}),ep=R("version",[],()=>u8);function ei(n,e,t){return R(n,e,t,{recreateOnConfigChange:!0})}var tp=Ze("speedOfLight","299792458","m s^-1"),rp=Ze("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),ip=Ze("planckConstant","6.62607015e-34","J s"),np=Ze("reducedPlanckConstant","1.0545718176461565e-34","J s"),sp=Ze("magneticConstant","1.25663706212e-6","N A^-2"),ap=Ze("electricConstant","8.8541878128e-12","F m^-1"),op=Ze("vacuumImpedance","376.730313667","ohm"),up=Ze("coulomb","8.987551792261171e9","N m^2 C^-2"),lp=Ze("coulombConstant","8.987551792261171e9","N m^2 C^-2"),cp=Ze("elementaryCharge","1.602176634e-19","C"),hp=Ze("bohrMagneton","9.2740100783e-24","J T^-1"),fp=Ze("conductanceQuantum","7.748091729863649e-5","S"),dp=Ze("inverseConductanceQuantum","12906.403729652257","ohm"),pp=Ze("magneticFluxQuantum","2.0678338484619295e-15","Wb"),mp=Ze("nuclearMagneton","5.0507837461e-27","J T^-1"),gp=Ze("klitzing","25812.807459304513","ohm"),vp=Ze("bohrRadius","5.29177210903e-11","m"),yp=Ze("classicalElectronRadius","2.8179403262e-15","m"),bp=Ze("electronMass","9.1093837015e-31","kg"),xp=Ze("fermiCoupling","1.1663787e-5","GeV^-2"),wp=Qp("fineStructure",.0072973525693),Sp=Ze("hartreeEnergy","4.3597447222071e-18","J"),Np=Ze("protonMass","1.67262192369e-27","kg"),Cp=Ze("deuteronMass","3.3435830926e-27","kg"),Dp=Ze("neutronMass","1.6749271613e-27","kg"),Ap=Ze("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),Ep=Ze("rydberg","10973731.568160","m^-1"),Mp=Ze("thomsonCrossSection","6.6524587321e-29","m^2"),Tp=Qp("weakMixingAngle",.2229),Fp=Qp("efimovFactor",22.7),_p=Ze("atomicMass","1.66053906660e-27","kg"),Op=Ze("avogadro","6.02214076e23","mol^-1"),Bp=Ze("boltzmann","1.380649e-23","J K^-1"),kp=Ze("faraday","96485.33212331001","C mol^-1"),Pp=Ze("firstRadiation","3.7417718521927573e-16","W m^2"),zp=Ze("loschmidt","2.686780111798444e25","m^-3"),Rp=Ze("gasConstant","8.31446261815324","J K^-1 mol^-1"),Lp=Ze("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),Ip=Ze("molarVolume","0.022413969545014137","m^3 mol^-1"),$p=Qp("sackurTetrode",-1.16487052358),qp=Ze("secondRadiation","0.014387768775039337","m K"),Hp=Ze("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),Up=Ze("wienDisplacement","2.897771955e-3","m K"),Vp=Ze("molarMass","0.99999999965e-3","kg mol^-1"),Wp=Ze("molarMassC12","11.9999999958e-3","kg mol^-1"),jp=Ze("gravity","9.80665","m s^-2"),Gp=Ze("planckLength","1.616255e-35","m"),Xp=Ze("planckMass","2.176435e-8","kg"),Yp=Ze("planckTime","5.391245e-44","s"),Jp=Ze("planckCharge","1.87554603778e-18","C"),Zp=Ze("planckTemperature","1.416785e+32","K");function Ze(n,e,t){var r=["config","Unit","BigNumber"];return R(n,r,i=>{var{config:s,Unit:a,BigNumber:o}=i,l=s.number==="BigNumber"?new o(e):parseFloat(e),u=new a(l,t);return u.fixPrefix=!0,u})}function Qp(n,e){var t=["config","BigNumber"];return R(n,t,r=>{var{config:i,BigNumber:s}=r;return i.number==="BigNumber"?new s(e):e})}function EN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function l8(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?EN(Object(t),!0).forEach(function(r){Yt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):EN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var c8="mapSlices",h8=["typed","isInteger"],Kp=R(c8,h8,n=>{var{typed:e,isInteger:t}=n,r=la({typed:e,isInteger:t});return e("mapSlices",{"...any":function(s){var a=s[1];Je(a)?s[1]=a-1:Xe(a)&&(s[1]=a.minus(1));try{return r.apply(null,s)}catch(o){throw kr(o)}}})},l8({isTransformFunction:!0},la.meta)),f8="column",d8=["typed","Index","matrix","range"],em=R(f8,d8,n=>{var{typed:e,Index:t,matrix:r,range:i}=n,s=to({typed:e,Index:t,matrix:r,range:i});return e("column",{"...any":function(o){var l=o.length-1,u=o[l];Je(u)&&(o[l]=u-1);try{return s.apply(null,o)}catch(c){throw kr(c)}}})},{isTransformFunction:!0});function Cv(n,e,t){var r=n.filter(function(l){return Xt(l)&&!(l.name in e)&&!t.has(l.name)})[0];if(!r)throw new Error('No undefined variable found in inline expression "'+n+'"');var i=r.name,s=new Map,a=new wy(t,s,new Set([i])),o=n.compile();return function(u){return s.set(i,u),o.evaluate(a)}}var p8="transformCallback",m8=["typed"],Dv=R(p8,m8,n=>{var{typed:e}=n;return function(r,i){return e.isTypedFunction(r)?t(r,i):MN(r,r.length,i)};function t(r,i){var s=Object.fromEntries(Object.entries(r.signatures).map(a=>{var[o,l]=a,u=o.split(",").length;return e.isTypedFunction(l)?[o,t(l,i)]:[o,MN(l,u,i)]}));return typeof r.name=="string"?e(r.name,s):e(s)}});function MN(n,e,t){return e===t?n:e===t+1?function(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=i.slice(0,t),o=TN(i[t]);return n(...a,o)}:e>t+1?function(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=i.slice(0,t),o=TN(i[t]),l=i.slice(t+1);return n(...a,o,...l)}:n}function TN(n){return n.map(e=>e+1)}var g8="filter",v8=["typed"],tm=R(g8,v8,n=>{var{typed:e}=n;function t(i,s,a){var o=ro({typed:e}),l=Dv({typed:e});if(i.length===0)return o();var u=i[0];if(i.length===1)return o(u);var c=i.length-1,h=i[c];return u&&(u=r(u,a)),h&&(Xt(h)||rs(h)?h=r(h,a):h=Cv(h,s,a)),o(u,l(h,c))}t.rawArgs=!0;function r(i,s){return i.compile().evaluate(s)}return t},{isTransformFunction:!0}),y8="forEach",b8=["typed"],rm=R(y8,b8,n=>{var{typed:e}=n,t=io({typed:e}),r=Dv({typed:e});function i(a,o,l){if(a.length===0)return t();var u=a[0];if(a.length===1)return t(u);var c=a.length-1,h=a[c];return u&&(u=s(u,l)),h&&(Xt(h)||rs(h)?h=s(h,l):h=Cv(h,o,l)),t(u,r(h,c))}i.rawArgs=!0;function s(a,o){return a.compile().evaluate(o)}return i},{isTransformFunction:!0}),x8="index",w8=["Index","getMatrixDataType"],im=R(x8,w8,n=>{var{Index:e,getMatrixDataType:t}=n;return function(){for(var i=[],s=0,a=arguments.length;s<a;s++){var o=arguments[s];if(Ia(o))o.start--,o.end-=o.step>0?0:2;else if(o&&o.isSet===!0)o=o.map(function(u){return u-1});else if(St(o)||Re(o))t(o)!=="boolean"&&(o=o.map(function(u){return u-1}));else if(Je(o)||ts(o))o--;else if(Xe(o))o=o.toNumber()-1;else if(typeof o!="string")throw new TypeError("Dimension must be an Array, Matrix, number, bigint, string, or Range");i[s]=o}var l=new e;return e.apply(l,i),l}},{isTransformFunction:!0}),S8="map",N8=["typed"],nm=R(S8,N8,n=>{var{typed:e}=n,t=no({typed:e}),r=Dv({typed:e});function i(s,a,o){if(s.length===0)return t();if(s.length===1)return t(s[0]);var l=s.length-1,u=s.slice(0,l),c=s[l];return u=u.map(f=>h(f,o)),c&&(Xt(c)||rs(c)?c=h(c,o):c=Cv(c,a,o)),t(...u,r(c,l));function h(f,d){return f.compile().evaluate(d)}}return i.rawArgs=!0,i},{isTransformFunction:!0});function C8(n){return Je(n)?n-1:Xe(n)?n.minus(1):n}function D8(n){return Je(n)||Xe(n)}function Bn(n){if(n.length===2&&Or(n[0])){n=n.slice();var e=n[1];D8(e)&&(n[1]=C8(e))}return n}var A8="max",E8=["typed","config","numeric","larger","isNaN"],sm=R(A8,E8,n=>{var{typed:e,config:t,numeric:r,larger:i,isNaN:s}=n,a=po({typed:e,config:t,numeric:r,larger:i,isNaN:s});return e("max",{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),M8="mean",T8=["typed","add","divide"],am=R(M8,T8,n=>{var{typed:e,add:t,divide:r}=n,i=wo({typed:e,add:t,divide:r});return e("mean",{"...any":function(a){a=Bn(a);try{return i.apply(null,a)}catch(o){throw kr(o)}}})},{isTransformFunction:!0}),F8="min",_8=["typed","config","numeric","smaller","isNaN"],om=R(F8,_8,n=>{var{typed:e,config:t,numeric:r,smaller:i,isNaN:s}=n,a=mo({typed:e,config:t,numeric:r,smaller:i,isNaN:s});return e("min",{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),O8="range",B8=["typed","config","?matrix","?bignumber","equal","smaller","smallerEq","larger","largerEq","add","isZero","isPositive"],um=R(O8,B8,n=>{var{typed:e,config:t,matrix:r,bignumber:i,equal:s,smaller:a,smallerEq:o,larger:l,largerEq:u,add:c,isZero:h,isPositive:f}=n,d=ao({typed:e,config:t,matrix:r,bignumber:i,equal:s,smaller:a,smallerEq:o,larger:l,largerEq:u,add:c,isZero:h,isPositive:f});return e("range",{"...any":function(m){var y=m.length-1,v=m[y];return typeof v!="boolean"&&m.push(!0),d.apply(null,m)}})},{isTransformFunction:!0}),k8="row",P8=["typed","Index","matrix","range"],lm=R(k8,P8,n=>{var{typed:e,Index:t,matrix:r,range:i}=n,s=oo({typed:e,Index:t,matrix:r,range:i});return e("row",{"...any":function(o){var l=o.length-1,u=o[l];Je(u)&&(o[l]=u-1);try{return s.apply(null,o)}catch(c){throw kr(c)}}})},{isTransformFunction:!0}),z8="subset",R8=["typed","matrix","zeros","add"],cm=R(z8,R8,n=>{var{typed:e,matrix:t,zeros:r,add:i}=n,s=uo({typed:e,matrix:t,zeros:r,add:i});return e("subset",{"...any":function(o){try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),L8="concat",I8=["typed","matrix","isInteger"],hm=R(L8,I8,n=>{var{typed:e,matrix:t,isInteger:r}=n,i=eo({typed:e,matrix:t,isInteger:r});return e("concat",{"...any":function(a){var o=a.length-1,l=a[o];Je(l)?a[o]=l-1:Xe(l)&&(a[o]=l.minus(1));try{return i.apply(null,a)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),FN="diff",$8=["typed","matrix","subtract","number","bignumber"],fm=R(FN,$8,n=>{var{typed:e,matrix:t,subtract:r,number:i,bignumber:s}=n,a=so({typed:e,matrix:t,subtract:r,number:i,bignumber:s});return e(FN,{"...any":function(l){l=Bn(l);try{return a.apply(null,l)}catch(u){throw kr(u)}}})},{isTransformFunction:!0}),q8="std",H8=["typed","map","sqrt","variance"],dm=R(q8,H8,n=>{var{typed:e,map:t,sqrt:r,variance:i}=n,s=Co({typed:e,map:t,sqrt:r,variance:i});return e("std",{"...any":function(o){o=Bn(o);try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),_N="sum",U8=["typed","config","add","numeric"],pm=R(_N,U8,n=>{var{typed:e,config:t,add:r,numeric:i}=n,s=bo({typed:e,config:t,add:r,numeric:i});return e(_N,{"...any":function(o){o=Bn(o);try{return s.apply(null,o)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),V8="quantileSeq",W8=["typed","bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger","mapSlices"],mm=R(V8,W8,n=>{var{typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d}=n,p=No({typed:e,bignumber:t,add:r,subtract:i,divide:s,multiply:a,partitionSelect:o,compare:l,isInteger:u,smaller:c,smallerEq:h,larger:f,mapSlices:d});return e("quantileSeq",{"Array | Matrix, number | BigNumber":p,"Array | Matrix, number | BigNumber, number":(y,v,S)=>p(y,v,m(S)),"Array | Matrix, number | BigNumber, boolean":p,"Array | Matrix, number | BigNumber, boolean, number":(y,v,S,g)=>p(y,v,S,m(g)),"Array | Matrix, Array | Matrix":p,"Array | Matrix, Array | Matrix, number":(y,v,S)=>p(y,v,m(S)),"Array | Matrix, Array | Matrix, boolean":p,"Array | Matrix, Array | Matrix, boolean, number":(y,v,S,g)=>p(y,v,S,m(g))});function m(y){return Bn([[],y])[1]}},{isTransformFunction:!0}),ON="cumsum",j8=["typed","add","unaryPlus"],gm=R(ON,j8,n=>{var{typed:e,add:t,unaryPlus:r}=n,i=xo({typed:e,add:t,unaryPlus:r});return e(ON,{"...any":function(a){if(a.length===2&&Or(a[0])){var o=a[1];Je(o)?a[1]=o-1:Xe(o)&&(a[1]=o.minus(1))}try{return i.apply(null,a)}catch(l){throw kr(l)}}})},{isTransformFunction:!0}),BN="variance",G8=["typed","add","subtract","multiply","divide","mapSlices","isNaN"],vm=R(BN,G8,n=>{var{typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o}=n,l=So({typed:e,add:t,subtract:r,multiply:i,divide:s,mapSlices:a,isNaN:o});return e(BN,{"...any":function(c){c=Bn(c);try{return l.apply(null,c)}catch(h){throw kr(h)}}})},{isTransformFunction:!0}),kN="print",X8=["typed","matrix","zeros","add"],ym=R(kN,X8,n=>{var{typed:e,matrix:t,zeros:r,add:i}=n,s=co({typed:e,matrix:t,zeros:r,add:i});return e(kN,{"string, Object | Array":function(l,u){return s(a(l),u)},"string, Object | Array, number | Object":function(l,u,c){return s(a(l),u,c)}});function a(o){return o.replace(Xx,l=>{var u=l.slice(1).split("."),c=u.map(function(h){return!isNaN(h)&&h.length>0?parseInt(h)-1:h});return"$"+c.join(".")})}},{isTransformFunction:!0}),Y8="and",J8=["typed","matrix","zeros","add","equalScalar","not","concat"],bm=R(Y8,J8,n=>{var{typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a}=n,o=fo({typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a});function l(u,c,h){var f=u[0].compile().evaluate(h);if(!Or(f)&&!o(f,!0))return!1;var d=u[1].compile().evaluate(h);return o(f,d)}return l.rawArgs=!0,l},{isTransformFunction:!0}),Z8="or",Q8=["typed","matrix","equalScalar","DenseMatrix","concat"],xm=R(Z8,Q8,n=>{var{typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s}=n,a=Ka({typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)&&a(h,!1))return!0;var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0}),K8="nullish",eI=["typed","matrix","size","flatten","deepEqual"],wm=R(K8,eI,n=>{var{typed:e,matrix:t,size:r,flatten:i,deepEqual:s}=n,a=Qa({typed:e,matrix:t,size:r,flatten:i,deepEqual:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)&&h!=null&&h!==void 0)return h;var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0}),tI="bitAnd",rI=["typed","matrix","zeros","add","equalScalar","not","concat"],Sm=R(tI,rI,n=>{var{typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a}=n,o=Ja({typed:e,matrix:t,equalScalar:r,zeros:i,not:s,concat:a});function l(u,c,h){var f=u[0].compile().evaluate(h);if(!Or(f)){if(isNaN(f))return NaN;if(f===0||f===!1)return 0}var d=u[1].compile().evaluate(h);return o(f,d)}return l.rawArgs=!0,l},{isTransformFunction:!0}),iI="bitOr",nI=["typed","matrix","equalScalar","DenseMatrix","concat"],Nm=R(iI,nI,n=>{var{typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s}=n,a=Za({typed:e,matrix:t,equalScalar:r,DenseMatrix:i,concat:s});function o(l,u,c){var h=l[0].compile().evaluate(c);if(!Or(h)){if(isNaN(h))return NaN;if(h===-1)return-1;if(h===!0)return 1}var f=l[1].compile().evaluate(c);return a(h,f)}return o.rawArgs=!0,o},{isTransformFunction:!0});const sI=Object.freeze(Object.defineProperty({__proto__:null,createAbs:cl,createAccessorNode:nf,createAcos:ph,createAcosh:mh,createAcot:gh,createAcoth:vh,createAcsc:yh,createAcsch:bh,createAdd:Yh,createAddScalar:fl,createAnd:fo,createAndTransform:bm,createArg:Il,createArrayNode:af,createAsec:xh,createAsech:wh,createAsin:Sh,createAsinh:Nh,createAssignmentNode:lf,createAtan:Ch,createAtan2:Dh,createAtanh:Ah,createAtomicMass:_p,createAvogadro:Op,createBellNumbers:Sd,createBigNumberClass:wu,createBigint:Zu,createBignumber:el,createBin:gc,createBitAnd:Ja,createBitAndTransform:Sm,createBitNot:Rl,createBitOr:Za,createBitOrTransform:Nm,createBitXor:Ll,createBlockNode:hf,createBohrMagneton:hp,createBohrRadius:vp,createBoltzmann:Bp,createBoolean:Ku,createCatalan:Nd,createCbrt:pl,createCeil:ml,createChain:jf,createChainClass:Vf,createClassicalElectronRadius:yp,createClone:Bu,createColumn:to,createColumnTransform:em,createCombinations:ld,createCombinationsWithRep:cd,createCompare:Ic,createCompareNatural:qc,createCompareText:Hc,createCompile:kf,createComplex:tl,createComplexClass:Su,createComposition:Cd,createConcat:eo,createConcatTransform:hm,createConditionalNode:df,createConductanceQuantum:fp,createConj:$l,createConstantNode:mf,createCorr:ud,createCos:Eh,createCosh:Mh,createCot:Th,createCoth:Fh,createCoulomb:up,createCoulombConstant:lp,createCount:Wl,createCreateUnit:dh,createCross:jl,createCsc:_h,createCsch:Oh,createCtranspose:ac,createCube:gl,createCumSum:xo,createCumSumTransform:gm,createDeepEqual:eh,createDenseMatrixClass:Ou,createDerivative:Od,createDet:Gf,createDeuteronMass:Cp,createDiag:Gl,createDiff:so,createDiffTransform:fm,createDistance:id,createDivide:rd,createDivideScalar:Nc,createDot:Qh,createDotDivide:Fc,createDotMultiply:Pl,createDotPow:Tc,createE:Wd,createEfimovFactor:Fp,createEigs:Jf,createElectricConstant:ap,createElectronMass:bp,createElementaryCharge:cp,createEqual:Vc,createEqualScalar:Xu,createEqualText:Wc,createErf:hc,createEvaluate:Pf,createExp:vl,createExpm:Zf,createExpm1:yl,createFactorial:dd,createFalse:Id,createFaraday:kp,createFermiCoupling:xp,createFft:uc,createFibonacciHeapClass:oh,createFilter:ro,createFilterTransform:tm,createFineStructure:wp,createFirstRadiation:Pp,createFix:bl,createFlatten:Xl,createFloor:Ga,createForEach:io,createForEachTransform:rm,createFormat:mc,createFraction:rl,createFractionClass:Nu,createFreqz:Pd,createFunctionAssignmentNode:vf,createFunctionNode:Of,createGamma:hd,createGasConstant:Rp,createGcd:wl,createGetMatrixDataType:Yl,createGravitationConstant:rp,createGravity:jp,createHartreeEnergy:Sp,createHasNumericValue:Hu,createHelp:Wf,createHelpClass:Uf,createHex:yc,createHypot:Jh,createI:Kd,createIdentity:Jl,createIfft:lc,createIm:ql,createImmutableDenseMatrixClass:sh,createIndex:ef,createIndexClass:ah,createIndexNode:bf,createIndexTransform:im,createInfinity:qd,createIntersect:nd,createInv:Xf,createInverseConductanceQuantum:dp,createInvmod:kl,createIsInteger:zu,createIsNaN:Wu,createIsNegative:$u,createIsNumeric:qu,createIsPositive:Uu,createIsPrime:wc,createIsZero:Vu,createKldivergence:pd,createKlitzing:gp,createKron:Zl,createLN10:Xd,createLN2:Gd,createLOG10E:Jd,createLOG2E:Yd,createLarger:Zc,createLargerEq:Kc,createLcm:Nl,createLeafCount:Dd,createLeftShift:Pc,createLgamma:fd,createLog:Ac,createLog10:Cl,createLog1p:Ec,createLog2:Dl,createLoschmidt:zp,createLsolve:_c,createLsolveAll:Bc,createLup:Lf,createLusolve:qf,createLyap:td,createMad:od,createMagneticConstant:sp,createMagneticFluxQuantum:pp,createMap:no,createMapSlices:la,createMapSlicesTransform:Kp,createMapTransform:nm,createMatrix:il,createMatrixClass:Du,createMatrixFromColumns:al,createMatrixFromFunction:nl,createMatrixFromRows:sl,createMax:po,createMaxTransform:sm,createMean:wo,createMeanTransform:am,createMedian:ad,createMin:mo,createMinTransform:om,createMod:Xa,createMode:dc,createMolarMass:Vp,createMolarMassC12:Wp,createMolarPlanckConstant:Lp,createMolarVolume:Ip,createMultinomial:md,createMultiply:El,createMultiplyScalar:Al,createNaN:Hd,createNeutronMass:Dp,createNode:tf,createNorm:Zh,createNot:Ul,createNthRoot:Ml,createNthRoots:Mc,createNuclearMagneton:mp,createNull:$d,createNullish:Qa,createNullishTransform:wm,createNumber:Ju,createNumeric:Sc,createObjectNode:wf,createOct:vc,createOnes:Ql,createOperatorNode:Nf,createOr:Ka,createOrTransform:xm,createParenthesisNode:Df,createParse:Bf,createParser:Rf,createParserClass:zf,createPartitionSelect:ih,createPermutations:gd,createPhi:jd,createPi:Ud,createPickRandom:yd,createPinv:Yf,createPlanckCharge:Jp,createPlanckConstant:ip,createPlanckLength:Gp,createPlanckMass:Xp,createPlanckTemperature:Zp,createPlanckTime:Yp,createPolynomialRoot:Hf,createPow:Cc,createPrint:co,createPrintTransform:ym,createProd:pc,createProtonMass:Np,createQr:If,createQuantileSeq:No,createQuantileSeqTransform:mm,createQuantumOfCirculation:Ap,createRandom:bd,createRandomInt:xd,createRange:ao,createRangeClass:Cu,createRangeNode:Ef,createRangeTransform:um,createRationalize:Bd,createRe:Hl,createReducedPlanckConstant:np,createRelationalNode:Tf,createReplacer:Rd,createReshape:Kl,createResize:ec,createResolve:Fd,createResultSet:fu,createReviver:zd,createRightArithShift:zc,createRightLogShift:Rc,createRotate:tc,createRotationMatrix:rc,createRound:Dc,createRow:oo,createRowTransform:lm,createRydberg:Ep,createSQRT1_2:Zd,createSQRT2:Qd,createSackurTetrode:$p,createSchur:ed,createSec:Bh,createSech:kh,createSecondRadiation:qp,createSetCartesian:Ih,createSetDifference:$h,createSetDistinct:qh,createSetIntersect:Hh,createSetIsSubset:Uh,createSetMultiplicity:Vh,createSetPowerset:Wh,createSetSize:jh,createSetSymDifference:Gh,createSetUnion:Xh,createSign:Tl,createSimplify:Ed,createSimplifyConstant:Md,createSimplifyCore:Td,createSin:Ph,createSinh:zh,createSize:ic,createSlu:$f,createSmaller:Gc,createSmallerEq:Yc,createSolveODE:cc,createSort:nh,createSpaClass:uh,createSparse:fh,createSparseMatrixClass:Yu,createSpeedOfLight:tp,createSplitUnit:ol,createSqrt:Fl,createSqrtm:Qf,createSquare:_l,createSqueeze:nc,createStd:Co,createStdTransform:dm,createStefanBoltzmann:Hp,createStirlingS2:wd,createString:Qu,createSubset:uo,createSubsetTransform:cm,createSubtract:Ol,createSubtractScalar:dl,createSum:bo,createSumTransform:pm,createSylvester:Kf,createSymbolNode:Ff,createSymbolicEqual:_d,createTan:Rh,createTanh:Lh,createTau:Vd,createThomsonCrossSection:Mp,createTo:bc,createToBest:xc,createTrace:Kh,createTranspose:sc,createTrue:Ld,createTypeOf:ju,createTyped:uu,createUnaryMinus:ul,createUnaryPlus:ll,createUnequal:rh,createUnitClass:ch,createUnitFunction:hh,createUppercaseE:Nv,createUppercasePi:Sv,createUsolve:Oc,createUsolveAll:kc,createVacuumImpedance:op,createVariance:So,createVarianceTransform:vm,createVersion:ep,createWeakMixingAngle:Tp,createWienDisplacement:Up,createXgcd:Bl,createXor:Vl,createZeros:oc,createZeta:fc,createZpk2tf:kd},Symbol.toStringTag,{value:"Module"}));var Ce=wu({config:pe}),Ct=Su({}),Av=Wd({BigNumber:Ce,config:pe}),PN=Id({}),zN=wp({BigNumber:Ce,config:pe}),kn=Nu({}),Ev=Kd({Complex:Ct}),RN=qd({BigNumber:Ce,config:pe}),LN=Xd({BigNumber:Ce,config:pe}),IN=Jd({BigNumber:Ce,config:pe}),Do=Du({}),$N=Hd({BigNumber:Ce,config:pe}),qN=$d({}),HN=jd({BigNumber:Ce,config:pe}),UN=Cu({}),Mv=fu({}),VN=Zd({BigNumber:Ce,config:pe}),WN=$p({BigNumber:Ce,config:pe}),Tv=Vd({BigNumber:Ce,config:pe}),jN=Ld({}),GN=ep({}),tt=Ou({Matrix:Do}),XN=Fp({BigNumber:Ce,config:pe}),YN=Gd({BigNumber:Ce,config:pe}),Cm=Ud({BigNumber:Ce,config:pe}),Fv=Rd({}),JN=Qd({BigNumber:Ce,config:pe}),j=uu({BigNumber:Ce,Complex:Ct,DenseMatrix:tt,Fraction:kn}),ZN=Tp({BigNumber:Ce,config:pe}),Cr=cl({typed:j}),QN=ph({Complex:Ct,config:pe,typed:j}),KN=gh({BigNumber:Ce,typed:j}),eC=yh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),Jt=fl({typed:j}),tC=Il({typed:j}),rC=wh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),iC=Nh({typed:j}),_v=Ch({typed:j}),nC=Ah({Complex:Ct,config:pe,typed:j}),sC=Zu({typed:j}),aC=Rl({typed:j}),oC=Ku({typed:j}),uC=Bu({typed:j}),Ao=ld({typed:j}),Eo=tl({Complex:Ct,typed:j}),Pn=$l({typed:j}),Dm=Eh({typed:j}),lC=Th({BigNumber:Ce,typed:j}),cC=_h({BigNumber:Ce,typed:j}),hC=gl({typed:j}),nt=Xu({config:pe,typed:j}),fC=hc({typed:j}),Ov=vl({typed:j}),dC=yl({Complex:Ct,typed:j}),pC=ro({typed:j}),zn=Xl({typed:j}),mC=io({typed:j}),ma=mc({typed:j}),Am=Yl({typed:j}),gC=yc({format:ma,typed:j}),Em=ql({typed:j}),Pr=zu({typed:j}),on=$u({config:pe,typed:j}),Rn=Uu({config:pe,typed:j}),ti=Vu({equalScalar:nt,typed:j}),vC=Yd({BigNumber:Ce,config:pe}),yC=fd({Complex:Ct,typed:j}),bC=Cl({Complex:Ct,config:pe,typed:j}),Mm=Dl({Complex:Ct,config:pe,typed:j}),Ln=no({typed:j}),Ht=Al({typed:j}),Mo=Ul({typed:j}),ji=Ju({typed:j}),xC=vc({format:ma,typed:j}),wC=yd({config:pe,typed:j}),SC=co({typed:j}),NC=bd({config:pe,typed:j}),Tm=Hl({typed:j}),CC=Bh({BigNumber:Ce,typed:j}),Bv=Tl({BigNumber:Ce,Fraction:kn,complex:Eo,typed:j}),To=Ph({typed:j}),Zt=Yu({Matrix:Do,equalScalar:nt,typed:j}),DC=ol({typed:j}),AC=_l({typed:j}),EC=Qu({typed:j}),ri=dl({typed:j}),MC=Rh({typed:j}),kv=xc({typed:j}),Fm=ju({typed:j}),TC=mh({Complex:Ct,config:pe,typed:j}),FC=bh({BigNumber:Ce,typed:j}),_C=xh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),zr=el({BigNumber:Ce,typed:j}),OC=cd({typed:j}),BC=Mh({typed:j}),kC=Oh({BigNumber:Ce,typed:j}),Gi=Wu({typed:j}),PC=wc({typed:j}),fs=la({isInteger:Pr,typed:j}),aI=fs,we=il({DenseMatrix:tt,Matrix:Do,SparseMatrix:Zt,typed:j}),zC=nl({isZero:ti,matrix:we,typed:j}),RC=Ql({BigNumber:Ce,config:pe,matrix:we,typed:j}),LC=xd({config:pe,log2:Mm,typed:j}),Pv=Kl({isInteger:Pr,matrix:we,typed:j}),IC=kh({BigNumber:Ce,typed:j}),$C=zh({typed:j}),qC=fh({SparseMatrix:Zt,typed:j}),vi=Fl({Complex:Ct,config:pe,typed:j}),HC=nc({typed:j}),UC=Lh({typed:j}),ga=sc({matrix:we,typed:j}),zv=Bl({BigNumber:Ce,config:pe,matrix:we,typed:j}),lr=oc({BigNumber:Ce,config:pe,matrix:we,typed:j}),VC=vh({BigNumber:Ce,Complex:Ct,config:pe,typed:j}),WC=Sh({Complex:Ct,config:pe,typed:j}),jC=gc({format:ma,typed:j}),dt=eo({isInteger:Pr,matrix:we,typed:j}),GC=Fh({BigNumber:Ce,typed:j}),_m=ac({conj:Pn,transpose:ga,typed:j}),Rv=Gl({DenseMatrix:tt,SparseMatrix:Zt,matrix:we,typed:j}),XC=Pl({concat:dt,equalScalar:nt,matrix:we,multiplyScalar:Ht,typed:j}),Rr=Vc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,equalScalar:nt,matrix:we,typed:j}),va=rl({Fraction:kn,typed:j}),un=Jl({BigNumber:Ce,DenseMatrix:tt,SparseMatrix:Zt,config:pe,matrix:we,typed:j}),In=qu({typed:j}),YC=Zl({matrix:we,multiplyScalar:Ht,typed:j}),Fo=Kc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,matrix:we,typed:j}),JC=Pc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ZC=dc({isNaN:Gi,isNumeric:In,typed:j}),QC=Ml({BigNumber:Ce,concat:dt,equalScalar:nt,matrix:we,typed:j}),ii=Sc({bignumber:zr,fraction:va,number:ji}),Lv=pc({config:pe,multiplyScalar:Ht,numeric:ii,typed:j}),KC=ec({config:pe,matrix:we}),eD=zc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ds=Dc({BigNumber:Ce,DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,typed:j,zeros:lr}),Qt=ic({matrix:we,config:pe,typed:j}),Dr=Gc({DenseMatrix:tt,SparseMatrix:Zt,bignumber:zr,concat:dt,config:pe,matrix:we,typed:j}),tD=bc({concat:dt,matrix:we,typed:j}),Oi=ul({typed:j}),rD=rh({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,equalScalar:nt,matrix:we,typed:j}),iD=Vl({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,matrix:we,typed:j}),ht=Yh({DenseMatrix:tt,SparseMatrix:Zt,addScalar:Jt,concat:dt,equalScalar:nt,matrix:we,typed:j}),nD=Dh({BigNumber:Ce,DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),sD=Ja({concat:dt,equalScalar:nt,matrix:we,typed:j}),aD=Za({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),oD=Ll({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,matrix:we,typed:j}),Iv=pl({BigNumber:Ce,Complex:Ct,Fraction:kn,config:pe,isNegative:on,matrix:we,typed:j,unaryMinus:Oi}),$n=Ic({BigNumber:Ce,DenseMatrix:tt,Fraction:kn,concat:dt,config:pe,equalScalar:nt,matrix:we,typed:j}),$v=Hc({concat:dt,matrix:we,typed:j}),uD=Wl({prod:Lv,size:Qt,typed:j}),ya=eh({equal:Rr,typed:j}),Rt=Nc({numeric:ii,typed:j}),ba=Fc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,divideScalar:Rt,equalScalar:nt,matrix:we,typed:j}),lD=Wc({compareText:$v,isZero:ti,typed:j}),qv=Ga({DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),cD=wl({BigNumber:Ce,DenseMatrix:tt,concat:dt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),hD=Hu({isNumeric:In,typed:j}),fD=Jh({abs:Cr,addScalar:Jt,divideScalar:Rt,isPositive:Rn,multiplyScalar:Ht,smaller:Dr,sqrt:vi,typed:j}),Hv=sh({DenseMatrix:tt,smaller:Dr}),mr=ah({ImmutableDenseMatrix:Hv,getMatrixDataType:Am}),Ar=Zc({DenseMatrix:tt,SparseMatrix:Zt,bignumber:zr,concat:dt,config:pe,matrix:we,typed:j}),Om=Ac({Complex:Ct,config:pe,divideScalar:Rt,typeOf:Fm,typed:j}),Uv=_c({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),Bm=al({flatten:zn,matrix:we,size:Qt,typed:j}),km=po({config:pe,isNaN:Gi,larger:Ar,numeric:ii,typed:j}),dD=mo({config:pe,isNaN:Gi,numeric:ii,smaller:Dr,typed:j}),Vv=Xa({DenseMatrix:tt,concat:dt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),pD=Mc({Complex:Ct,config:pe,divideScalar:Rt,typed:j}),mD=Qa({deepEqual:ya,flatten:zn,matrix:we,size:Qt,typed:j}),gD=Ka({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),_o=ih({compare:$n,isNaN:Gi,isNumeric:In,typed:j}),Pm=If({addScalar:Jt,complex:Eo,conj:Pn,divideScalar:Rt,equal:Rr,identity:un,isZero:ti,matrix:we,multiplyScalar:Ht,sign:Bv,sqrt:vi,subtractScalar:ri,typed:j,unaryMinus:Oi,zeros:lr}),vD=Rc({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j,zeros:lr}),ps=Yc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,config:pe,matrix:we,typed:j}),Gr=uo({add:ht,matrix:we,typed:j,zeros:lr}),Wt=Ol({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,subtractScalar:ri,typed:j,unaryMinus:Oi}),yD=Kh({add:ht,matrix:we,typed:j}),zm=Oc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),bD=Nd({addScalar:Jt,combinations:Ao,divideScalar:Rt,isInteger:Pr,isNegative:on,multiplyScalar:Ht,typed:j}),Bi=qc({compare:$n,typed:j}),xD=Cd({addScalar:Jt,combinations:Ao,isInteger:Pr,isNegative:on,isPositive:Rn,larger:Ar,typed:j}),wD=so({matrix:we,number:ji,subtract:Wt,typed:j}),SD=id({abs:Cr,addScalar:Jt,deepEqual:ya,divideScalar:Rt,multiplyScalar:Ht,sqrt:vi,subtractScalar:ri,typed:j}),Oo=Qh({addScalar:Jt,conj:Pn,multiplyScalar:Ht,size:Qt,typed:j}),Wv=oh({larger:Ar,smaller:Dr}),jv=ef({Index:mr,typed:j}),ND=kl({BigNumber:Ce,add:ht,config:pe,equal:Rr,isInteger:Pr,mod:Vv,smaller:Dr,typed:j,xgcd:zv}),CD=Nl({concat:dt,equalScalar:nt,matrix:we,typed:j}),DD=Ec({Complex:Ct,config:pe,divideScalar:Rt,log:Om,typed:j}),AD=Bc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),ED=sl({flatten:zn,matrix:we,size:Qt,typed:j}),xt=El({addScalar:Jt,dot:Oo,equalScalar:nt,matrix:we,multiplyScalar:Ht,typed:j}),ms=ao({bignumber:zr,matrix:we,add:ht,config:pe,equal:Rr,isPositive:Rn,isZero:ti,larger:Ar,largerEq:Fo,smaller:Dr,smallerEq:ps,typed:j}),MD=oo({Index:mr,matrix:we,range:ms,typed:j}),TD=Ih({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),FD=qh({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),_D=Uh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),OD=Wh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),Gv=$f({SparseMatrix:Zt,abs:Cr,add:ht,divideScalar:Rt,larger:Ar,largerEq:Fo,multiply:xt,subtract:Wt,transpose:ga,typed:j}),BD=nh({compare:$n,compareNatural:Bi,matrix:we,typed:j}),Rm=ll({config:pe,numeric:ii,typed:j}),Xv=kc({DenseMatrix:tt,divideScalar:Rt,equalScalar:nt,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j}),kD=kd({Complex:Ct,add:ht,multiply:xt,number:ji,typed:j}),PD=fo({concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),Lm=ml({DenseMatrix:tt,config:pe,equalScalar:nt,matrix:we,round:ds,typed:j,zeros:lr}),Yv=to({Index:mr,matrix:we,range:ms,typed:j}),zD=jl({matrix:we,multiply:xt,subtract:Wt,typed:j}),Jv=Gf({divideScalar:Rt,isZero:ti,matrix:we,multiply:xt,subtractScalar:ri,typed:j,unaryMinus:Oi}),Zv=bl({Complex:Ct,DenseMatrix:tt,ceil:Lm,equalScalar:nt,floor:qv,matrix:we,typed:j,zeros:lr}),qn=Xf({abs:Cr,addScalar:Jt,det:Jv,divideScalar:Rt,identity:un,matrix:we,multiply:xt,typed:j,unaryMinus:Oi}),RD=Yf({Complex:Ct,add:ht,ctranspose:_m,deepEqual:ya,divideScalar:Rt,dot:Oo,dotDivide:ba,equal:Rr,inv:qn,matrix:we,multiply:xt,typed:j}),yi=Cc({Complex:Ct,config:pe,fraction:va,identity:un,inv:qn,matrix:we,multiply:xt,number:ji,typed:j}),Qv=$h({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),LD=Vh({Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),Kv=Gh({Index:mr,concat:dt,setDifference:Qv,size:Qt,subset:Gr,typed:j}),e0=uh({FibonacciHeap:Wv,addScalar:Jt,equalScalar:nt}),ID=Qf({abs:Cr,add:ht,identity:un,inv:qn,map:Ln,max:km,multiply:xt,size:Qt,sqrt:vi,subtract:Wt,typed:j}),Im=bo({add:ht,config:pe,numeric:ii,typed:j}),qe=ch({BigNumber:Ce,Complex:Ct,Fraction:kn,abs:Cr,addScalar:Jt,config:pe,divideScalar:Rt,equal:Rr,fix:Zv,format:ma,isNumeric:In,multiplyScalar:Ht,number:ji,pow:yi,round:ds,subtractScalar:ri,toBest:kv}),$D=op({BigNumber:Ce,Unit:qe,config:pe}),qD=Up({BigNumber:Ce,Unit:qe,config:pe}),HD=_p({BigNumber:Ce,Unit:qe,config:pe}),UD=hp({BigNumber:Ce,Unit:qe,config:pe}),VD=Bp({BigNumber:Ce,Unit:qe,config:pe}),WD=fp({BigNumber:Ce,Unit:qe,config:pe}),jD=up({BigNumber:Ce,Unit:qe,config:pe}),GD=dh({Unit:qe,typed:j}),XD=Cp({BigNumber:Ce,Unit:qe,config:pe}),YD=Tc({DenseMatrix:tt,SparseMatrix:Zt,concat:dt,equalScalar:nt,matrix:we,pow:yi,typed:j}),JD=ap({BigNumber:Ce,Unit:qe,config:pe}),ZD=cp({BigNumber:Ce,Unit:qe,config:pe}),QD=Zf({abs:Cr,add:ht,identity:un,inv:qn,multiply:xt,typed:j}),KD=kp({BigNumber:Ce,Unit:qe,config:pe}),t0=uc({addScalar:Jt,ceil:Lm,conj:Pn,divideScalar:Rt,dotDivide:ba,exp:Ov,i:Ev,log2:Mm,matrix:we,multiplyScalar:Ht,pow:yi,tau:Tv,typed:j}),$m=hd({BigNumber:Ce,Complex:Ct,config:pe,multiplyScalar:Ht,pow:yi,typed:j}),eA=rp({BigNumber:Ce,Unit:qe,config:pe}),tA=Sp({BigNumber:Ce,Unit:qe,config:pe}),rA=lc({conj:Pn,dotDivide:ba,fft:t0,typed:j}),iA=dp({BigNumber:Ce,Unit:qe,config:pe}),nA=gp({BigNumber:Ce,Unit:qe,config:pe}),sA=zp({BigNumber:Ce,Unit:qe,config:pe}),aA=sp({BigNumber:Ce,Unit:qe,config:pe}),oA=Vp({BigNumber:Ce,Unit:qe,config:pe}),uA=Lp({BigNumber:Ce,Unit:qe,config:pe}),lA=Dp({BigNumber:Ce,Unit:qe,config:pe}),cA=mp({BigNumber:Ce,Unit:qe,config:pe}),hA=Jp({BigNumber:Ce,Unit:qe,config:pe}),fA=Gp({BigNumber:Ce,Unit:qe,config:pe}),dA=Zp({BigNumber:Ce,Unit:qe,config:pe}),pA=Np({BigNumber:Ce,Unit:qe,config:pe}),mA=Ap({BigNumber:Ce,Unit:qe,config:pe}),gA=np({BigNumber:Ce,Unit:qe,config:pe}),vA=Ep({BigNumber:Ce,Unit:qe,config:pe}),yA=qp({BigNumber:Ce,Unit:qe,config:pe}),bA=jh({compareNatural:Bi,typed:j}),xA=tp({BigNumber:Ce,Unit:qe,config:pe}),wA=Hp({BigNumber:Ce,Unit:qe,config:pe}),SA=Mp({BigNumber:Ce,Unit:qe,config:pe}),NA=Op({BigNumber:Ce,Unit:qe,config:pe}),CA=vp({BigNumber:Ce,Unit:qe,config:pe}),DA=lp({BigNumber:Ce,Unit:qe,config:pe}),cr=rd({divideScalar:Rt,equalScalar:nt,inv:qn,matrix:we,multiply:xt,typed:j}),AA=bp({BigNumber:Ce,Unit:qe,config:pe}),xa=dd({gamma:$m,typed:j}),EA=Pp({BigNumber:Ce,Unit:qe,config:pe}),MA=jp({BigNumber:Ce,Unit:qe,config:pe}),TA=nd({abs:Cr,add:ht,addScalar:Jt,config:pe,divideScalar:Rt,equalScalar:nt,flatten:zn,isNumeric:In,isZero:ti,matrix:we,multiply:xt,multiplyScalar:Ht,smaller:Dr,subtract:Wt,typed:j}),r0=Lf({DenseMatrix:tt,Spa:e0,SparseMatrix:Zt,abs:Cr,addScalar:Jt,divideScalar:Rt,equalScalar:nt,larger:Ar,matrix:we,multiplyScalar:Ht,subtractScalar:ri,typed:j,unaryMinus:Oi}),FA=pp({BigNumber:Ce,Unit:qe,config:pe}),_A=Wp({BigNumber:Ce,Unit:qe,config:pe}),OA=md({add:ht,divide:cr,factorial:xa,isInteger:Pr,isPositive:Rn,multiply:xt,typed:j}),BA=gd({factorial:xa,typed:j}),kA=Xp({BigNumber:Ce,Unit:qe,config:pe}),PA=Hf({add:ht,cbrt:Iv,divide:cr,equalScalar:nt,im:Em,isZero:ti,multiply:xt,re:Tm,sqrt:vi,subtract:Wt,typeOf:Fm,typed:j,unaryMinus:Oi}),i0=Hh({DenseMatrix:tt,Index:mr,compareNatural:Bi,size:Qt,subset:Gr,typed:j}),zA=cc({abs:Cr,add:ht,bignumber:zr,divide:cr,isNegative:on,isPositive:Rn,larger:Ar,map:Ln,matrix:we,max:km,multiply:xt,smaller:Dr,subtract:Wt,typed:j,unaryMinus:Oi}),n0=wd({bignumber:zr,addScalar:Jt,combinations:Ao,divideScalar:Rt,factorial:xa,isInteger:Pr,isNegative:on,larger:Ar,multiplyScalar:Ht,number:ji,pow:yi,subtractScalar:ri,typed:j}),RA=hh({Unit:qe,typed:j}),LA=Sd({addScalar:Jt,isInteger:Pr,isNegative:on,stirlingS2:n0,typed:j}),IA=xo({add:ht,typed:j,unaryPlus:Rm}),s0=Jf({abs:Cr,add:ht,addScalar:Jt,atan:_v,bignumber:zr,column:Yv,complex:Eo,config:pe,cos:Dm,diag:Rv,divideScalar:Rt,dot:Oo,equal:Rr,flatten:zn,im:Em,inv:qn,larger:Ar,matrix:we,matrixFromColumns:Bm,multiply:xt,multiplyScalar:Ht,number:ji,qr:Pm,re:Tm,reshape:Pv,sin:To,size:Qt,smaller:Dr,sqrt:vi,subtract:Wt,typed:j,usolve:zm,usolveAll:Xv}),$A=xp({BigNumber:Ce,Unit:qe,config:pe}),qA=Rp({BigNumber:Ce,Unit:qe,config:pe}),HA=pd({divide:cr,dotDivide:ba,isNumeric:In,log:Om,map:Ln,matrix:we,multiply:xt,sum:Im,typed:j}),a0=qf({DenseMatrix:tt,lsolve:Uv,lup:r0,matrix:we,slu:Gv,typed:j,usolve:zm}),o0=wo({add:ht,divide:cr,typed:j}),UA=Ip({BigNumber:Ce,Unit:qe,config:pe}),VA=ip({BigNumber:Ce,Unit:qe,config:pe}),WA=No({bignumber:zr,add:ht,compare:$n,divide:cr,isInteger:Pr,larger:Ar,mapSlices:fs,multiply:xt,partitionSelect:_o,smaller:Dr,smallerEq:ps,subtract:Wt,typed:j}),jA=Xh({Index:mr,concat:dt,setIntersect:i0,setSymDifference:Kv,size:Qt,subset:Gr,typed:j}),qm=So({add:ht,divide:cr,isNaN:Gi,mapSlices:fs,multiply:xt,subtract:Wt,typed:j}),GA=yp({BigNumber:Ce,Unit:qe,config:pe}),u0=ad({add:ht,compare:$n,divide:cr,partitionSelect:_o,typed:j}),XA=ud({add:ht,divide:cr,matrix:we,mean:o0,multiply:xt,pow:yi,sqrt:vi,subtract:Wt,sum:Im,typed:j}),YA=Pd({Complex:Ct,add:ht,divide:cr,matrix:we,multiply:xt,typed:j}),JA=od({abs:Cr,map:Ln,median:u0,subtract:Wt,typed:j}),ZA=Co({map:Ln,sqrt:vi,typed:j,variance:qm}),QA=fc({BigNumber:Ce,Complex:Ct,add:ht,config:pe,divide:cr,equal:Rr,factorial:xa,gamma:$m,isNegative:on,multiply:xt,pi:Cm,pow:yi,sin:To,smallerEq:ps,subtract:Wt,typed:j}),Hm=Zh({abs:Cr,add:ht,conj:Pn,ctranspose:_m,eigs:s0,equalScalar:nt,larger:Ar,matrix:we,multiply:xt,pow:yi,smaller:Dr,sqrt:vi,typed:j}),l0=rc({BigNumber:Ce,DenseMatrix:tt,SparseMatrix:Zt,addScalar:Jt,config:pe,cos:Dm,matrix:we,multiplyScalar:Ht,norm:Hm,sin:To,typed:j,unaryMinus:Oi}),KA=Yp({BigNumber:Ce,Unit:qe,config:pe}),c0=ed({identity:un,matrix:we,multiply:xt,norm:Hm,qr:Pm,subtract:Wt,typed:j}),e2=tc({multiply:xt,rotationMatrix:l0,typed:j}),h0=Kf({abs:Cr,add:ht,concat:dt,identity:un,index:jv,lusolve:a0,matrix:we,matrixFromColumns:Bm,multiply:xt,range:ms,schur:c0,subset:Gr,subtract:Wt,transpose:ga,typed:j}),t2=td({matrix:we,multiply:xt,sylvester:h0,transpose:ga,typed:j}),wa={},Bo={},r2={},gr=tf({mathWithTransform:Bo}),gs=wf({Node:gr}),Xi=Nf({Node:gr}),Hn=Df({Node:gr}),f0=Tf({Node:gr}),vs=af({Node:gr}),d0=hf({Node:gr,ResultSet:Mv}),p0=df({Node:gr}),ln=mf({Node:gr}),m0=Ef({Node:gr}),i2=zd({classes:r2}),Um=Vf({math:wa,typed:j}),g0=vf({Node:gr,typed:j}),n2=jf({Chain:Um,typed:j}),ys=nf({Node:gr,subset:Gr}),v0=lf({matrix:we,Node:gr,subset:Gr}),bs=bf({Node:gr,size:Qt}),cn=Ff({Unit:qe,Node:gr,math:wa}),hn=Of({Node:gr,SymbolNode:cn,math:wa}),bi=Bf({AccessorNode:ys,ArrayNode:vs,AssignmentNode:v0,BlockNode:d0,ConditionalNode:p0,ConstantNode:ln,FunctionAssignmentNode:g0,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,RangeNode:m0,RelationalNode:f0,SymbolNode:cn,config:pe,numeric:ii,typed:j}),y0=Fd({ConstantNode:ln,FunctionNode:hn,OperatorNode:Xi,ParenthesisNode:Hn,parse:bi,typed:j}),Vm=Md({bignumber:zr,fraction:va,AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,SymbolNode:cn,config:pe,mathWithTransform:Bo,matrix:we,typed:j}),s2=kf({parse:bi,typed:j}),Wm=Td({AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,add:ht,divide:cr,equal:Rr,isZero:ti,multiply:xt,parse:bi,pow:yi,subtract:Wt,typed:j}),jm=Pf({parse:bi,typed:j}),b0=Uf({evaluate:jm}),x0=zf({evaluate:jm,parse:bi}),ko=Ed({AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,equal:Rr,parse:bi,replacer:Fv,resolve:y0,simplifyConstant:Vm,simplifyCore:Wm,typed:j}),a2=_d({OperatorNode:Xi,parse:bi,simplify:ko,typed:j}),o2=Dd({parse:bi,typed:j}),u2=Rf({Parser:x0,typed:j}),l2=Bd({bignumber:zr,fraction:va,AccessorNode:ys,ArrayNode:vs,ConstantNode:ln,FunctionNode:hn,IndexNode:bs,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,add:ht,config:pe,divide:cr,equal:Rr,isZero:ti,mathWithTransform:Bo,matrix:we,multiply:xt,parse:bi,pow:yi,simplify:ko,simplifyConstant:Vm,simplifyCore:Wm,subtract:Wt,typed:j}),c2=Od({ConstantNode:ln,FunctionNode:hn,OperatorNode:Xi,ParenthesisNode:Hn,SymbolNode:cn,config:pe,equal:Rr,isZero:ti,numeric:ii,parse:bi,simplify:ko,typed:j}),h2=Wf({Help:b0,mathWithTransform:Bo,typed:j});wt(wa,{e:Av,false:PN,fineStructure:zN,i:Ev,Infinity:RN,LN10:LN,LOG10E:IN,NaN:$N,null:qN,phi:HN,SQRT1_2:VN,sackurTetrode:WN,tau:Tv,true:jN,E:Av,version:GN,efimovFactor:XN,LN2:YN,pi:Cm,replacer:Fv,reviver:i2,SQRT2:JN,typed:j,PI:Cm,weakMixingAngle:ZN,abs:Cr,acos:QN,acot:KN,acsc:eC,addScalar:Jt,arg:tC,asech:rC,asinh:iC,atan:_v,atanh:nC,bigint:sC,bitNot:aC,boolean:oC,clone:uC,combinations:Ao,complex:Eo,conj:Pn,cos:Dm,cot:lC,csc:cC,cube:hC,equalScalar:nt,erf:fC,exp:Ov,expm1:dC,filter:pC,flatten:zn,forEach:mC,format:ma,getMatrixDataType:Am,hex:gC,im:Em,isInteger:Pr,isNegative:on,isPositive:Rn,isZero:ti,LOG2E:vC,lgamma:yC,log10:bC,log2:Mm,map:Ln,multiplyScalar:Ht,not:Mo,number:ji,oct:xC,pickRandom:wC,print:SC,random:NC,re:Tm,sec:CC,sign:Bv,sin:To,splitUnit:DC,square:AC,string:EC,subtractScalar:ri,tan:MC,toBest:kv,typeOf:Fm,acosh:TC,acsch:FC,asec:_C,bignumber:zr,chain:n2,combinationsWithRep:OC,cosh:BC,csch:kC,isNaN:Gi,isPrime:PC,mapSlices:fs,matrix:we,matrixFromFunction:zC,ones:RC,randomInt:LC,reshape:Pv,sech:IC,sinh:$C,sparse:qC,sqrt:vi,squeeze:HC,tanh:UC,transpose:ga,xgcd:zv,zeros:lr,acoth:VC,asin:WC,bin:jC,concat:dt,coth:GC,ctranspose:_m,diag:Rv,dotMultiply:XC,equal:Rr,fraction:va,identity:un,isNumeric:In,kron:YC,largerEq:Fo,leftShift:JC,mode:ZC,nthRoot:QC,numeric:ii,prod:Lv,resize:KC,rightArithShift:eD,round:ds,size:Qt,smaller:Dr,to:tD,unaryMinus:Oi,unequal:rD,xor:iD,add:ht,atan2:nD,bitAnd:sD,bitOr:aD,bitXor:oD,cbrt:Iv,compare:$n,compareText:$v,count:uD,deepEqual:ya,divideScalar:Rt,dotDivide:ba,equalText:lD,floor:qv,gcd:cD,hasNumericValue:hD,hypot:fD,larger:Ar,log:Om,lsolve:Uv,matrixFromColumns:Bm,max:km,min:dD,mod:Vv,nthRoots:pD,nullish:mD,or:gD,partitionSelect:_o,qr:Pm,rightLogShift:vD,smallerEq:ps,subset:Gr,subtract:Wt,trace:yD,usolve:zm,catalan:bD,compareNatural:Bi,composition:xD,diff:wD,distance:SD,dot:Oo,index:jv,invmod:ND,lcm:CD,log1p:DD,lsolveAll:AD,matrixFromRows:ED,multiply:xt,range:ms,row:MD,setCartesian:TD,setDistinct:FD,setIsSubset:_D,setPowerset:OD,slu:Gv,sort:BD,unaryPlus:Rm,usolveAll:Xv,zpk2tf:kD,and:PD,ceil:Lm,column:Yv,cross:zD,det:Jv,fix:Zv,inv:qn,pinv:RD,pow:yi,setDifference:Qv,setMultiplicity:LD,setSymDifference:Kv,sqrtm:ID,sum:Im,vacuumImpedance:$D,wienDisplacement:qD,atomicMass:HD,bohrMagneton:UD,boltzmann:VD,conductanceQuantum:WD,coulomb:jD,createUnit:GD,deuteronMass:XD,dotPow:YD,electricConstant:JD,elementaryCharge:ZD,expm:QD,faraday:KD,fft:t0,gamma:$m,gravitationConstant:eA,hartreeEnergy:tA,ifft:rA,inverseConductanceQuantum:iA,klitzing:nA,loschmidt:sA,magneticConstant:aA,molarMass:oA,molarPlanckConstant:uA,neutronMass:lA,nuclearMagneton:cA,planckCharge:hA,planckLength:fA,planckTemperature:dA,protonMass:pA,quantumOfCirculation:mA,reducedPlanckConstant:gA,rydberg:vA,secondRadiation:yA,setSize:bA,speedOfLight:xA,stefanBoltzmann:wA,thomsonCrossSection:SA,avogadro:NA,bohrRadius:CA,coulombConstant:DA,divide:cr,electronMass:AA,factorial:xa,firstRadiation:EA,gravity:MA,intersect:TA,lup:r0,magneticFluxQuantum:FA,molarMassC12:_A,multinomial:OA,parse:bi,permutations:BA,planckMass:kA,polynomialRoot:PA,resolve:y0,setIntersect:i0,simplifyConstant:Vm,solveODE:zA,stirlingS2:n0,unit:RA,bellNumbers:LA,compile:s2,cumsum:IA,eigs:s0,fermiCoupling:$A,gasConstant:qA,kldivergence:HA,lusolve:a0,mean:o0,molarVolume:UA,planckConstant:VA,quantileSeq:WA,setUnion:jA,simplifyCore:Wm,variance:qm,classicalElectronRadius:GA,evaluate:jm,median:u0,simplify:ko,symbolicEqual:a2,corr:XA,freqz:YA,leafCount:o2,mad:JA,parser:u2,rationalize:l2,std:ZA,zeta:QA,derivative:c2,norm:Hm,rotationMatrix:l0,help:h2,planckTime:KA,schur:c0,rotate:e2,sylvester:h0,lyap:t2,config:pe}),wt(Bo,wa,{mapSlices:Kp({isInteger:Pr,typed:j}),filter:tm({typed:j}),forEach:rm({typed:j}),map:nm({typed:j}),or:xm({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),and:bm({add:ht,concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),concat:hm({isInteger:Pr,matrix:we,typed:j}),index:im({Index:mr,getMatrixDataType:Am}),print:ym({add:ht,matrix:we,typed:j,zeros:lr}),sum:pm({add:ht,config:pe,numeric:ii,typed:j}),bitAnd:Sm({add:ht,concat:dt,equalScalar:nt,matrix:we,not:Mo,typed:j,zeros:lr}),min:om({config:pe,isNaN:Gi,numeric:ii,smaller:Dr,typed:j}),nullish:wm({deepEqual:ya,flatten:zn,matrix:we,size:Qt,typed:j}),subset:cm({add:ht,matrix:we,typed:j,zeros:lr}),bitOr:Nm({DenseMatrix:tt,concat:dt,equalScalar:nt,matrix:we,typed:j}),cumsum:gm({add:ht,typed:j,unaryPlus:Rm}),diff:fm({bignumber:zr,matrix:we,number:ji,subtract:Wt,typed:j}),max:sm({config:pe,isNaN:Gi,larger:Ar,numeric:ii,typed:j}),range:um({bignumber:zr,matrix:we,add:ht,config:pe,equal:Rr,isPositive:Rn,isZero:ti,larger:Ar,largerEq:Fo,smaller:Dr,smallerEq:ps,typed:j}),row:lm({Index:mr,matrix:we,range:ms,typed:j}),column:em({Index:mr,matrix:we,range:ms,typed:j}),mean:am({add:ht,divide:cr,typed:j}),quantileSeq:mm({add:ht,bignumber:zr,compare:$n,divide:cr,isInteger:Pr,larger:Ar,mapSlices:fs,multiply:xt,partitionSelect:_o,smaller:Dr,smallerEq:ps,subtract:Wt,typed:j}),variance:vm({add:ht,divide:cr,isNaN:Gi,mapSlices:fs,multiply:xt,subtract:Wt,typed:j}),std:dm({map:Ln,sqrt:vi,typed:j,variance:qm})}),wt(r2,{BigNumber:Ce,Complex:Ct,Fraction:kn,Matrix:Do,Node:gr,ObjectNode:gs,OperatorNode:Xi,ParenthesisNode:Hn,Range:UN,RelationalNode:f0,ResultSet:Mv,ArrayNode:vs,BlockNode:d0,ConditionalNode:p0,ConstantNode:ln,DenseMatrix:tt,RangeNode:m0,Chain:Um,FunctionAssignmentNode:g0,SparseMatrix:Zt,ImmutableDenseMatrix:Hv,Index:mr,AccessorNode:ys,AssignmentNode:v0,FibonacciHeap:Wv,IndexNode:bs,Spa:e0,Unit:qe,SymbolNode:cn,FunctionNode:hn,Help:b0,Parser:x0}),Um.createProxy(wa);var De={createBigNumberClass:wu},Et={createComplexClass:Su},Gm={createMatrixClass:Du},it={MatrixDependencies:Gm,createDenseMatrixClass:Ou},xs={createFractionClass:Nu},G={BigNumberDependencies:De,ComplexDependencies:Et,DenseMatrixDependencies:it,FractionDependencies:xs,createTyped:uu},Lr={typedDependencies:G,createAbs:cl},Er={createNode:tf},ot={typedDependencies:G,createEqualScalar:Xu},tr={MatrixDependencies:Gm,equalScalarDependencies:ot,typedDependencies:G,createSparseMatrixClass:Yu},rr={typedDependencies:G,createAddScalar:fl},Xr={typedDependencies:G,createIsInteger:zu},Ne={DenseMatrixDependencies:it,MatrixDependencies:Gm,SparseMatrixDependencies:tr,typedDependencies:G,createMatrix:il},mt={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createConcat:eo},ft={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,addScalarDependencies:rr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createAdd:Yh},vr={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createZeros:oc},ni={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createSubset:uo},Sa={NodeDependencies:Er,subsetDependencies:ni,createAccessorNode:nf},oI={ComplexDependencies:Et,typedDependencies:G,createAcos:ph},uI={ComplexDependencies:Et,typedDependencies:G,createAcosh:mh},lI={BigNumberDependencies:De,typedDependencies:G,createAcot:gh},cI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAcoth:vh},hI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAcsc:yh},fI={BigNumberDependencies:De,typedDependencies:G,createAcsch:bh},Xm={typedDependencies:G,createNot:Ul},dI={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createAnd:fo},pI={addDependencies:ft,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createAndTransform:bm},mI={typedDependencies:G,createArg:Il},Na={NodeDependencies:Er,createArrayNode:af},gI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAsec:xh},vI={BigNumberDependencies:De,ComplexDependencies:Et,typedDependencies:G,createAsech:wh},yI={ComplexDependencies:Et,typedDependencies:G,createAsin:Sh},bI={typedDependencies:G,createAsinh:Nh},f2={matrixDependencies:Ne,NodeDependencies:Er,subsetDependencies:ni,createAssignmentNode:lf},d2={typedDependencies:G,createAtan:Ch},xI={BigNumberDependencies:De,DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createAtan2:Dh},wI={ComplexDependencies:Et,typedDependencies:G,createAtanh:Ah},Yr={BigNumberDependencies:De,typedDependencies:G,createBignumber:el},Po={FractionDependencies:xs,typedDependencies:G,createFraction:rl},fn={typedDependencies:G,createNumber:Ju},xi={bignumberDependencies:Yr,fractionDependencies:Po,numberDependencies:fn,createNumeric:Sc},$t={numericDependencies:xi,typedDependencies:G,createDivideScalar:Nc},Jr={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createEqual:Vc},Ca={BigNumberDependencies:De,DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRound:Dc},w0={DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createCeil:ml},p2={DenseMatrixDependencies:it,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createFloor:Ga},m2={ComplexDependencies:Et,DenseMatrixDependencies:it,ceilDependencies:w0,equalScalarDependencies:ot,floorDependencies:p2,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createFix:bl},zo={typedDependencies:G,createFormat:mc},ws={typedDependencies:G,createIsNumeric:qu},jt={typedDependencies:G,createMultiplyScalar:Al},Un={BigNumberDependencies:De,DenseMatrixDependencies:it,SparseMatrixDependencies:tr,matrixDependencies:Ne,typedDependencies:G,createIdentity:Jl},wi={equalScalarDependencies:ot,typedDependencies:G,createIsZero:Vu},Ss={typedDependencies:G,createConj:$l},ir={matrixDependencies:Ne,typedDependencies:G,createSize:ic},Ym={addScalarDependencies:rr,conjDependencies:Ss,multiplyScalarDependencies:jt,sizeDependencies:ir,typedDependencies:G,createDot:Qh},Nt={addScalarDependencies:rr,dotDependencies:Ym,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createMultiply:El},Si={typedDependencies:G,createSubtractScalar:dl},Yi={typedDependencies:G,createUnaryMinus:ul},g2={divideScalarDependencies:$t,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createDet:Gf},Ns={absDependencies:Lr,addScalarDependencies:rr,detDependencies:g2,divideScalarDependencies:$t,identityDependencies:Un,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,unaryMinusDependencies:Yi,createInv:Xf},ki={ComplexDependencies:Et,fractionDependencies:Po,identityDependencies:Un,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,numberDependencies:fn,typedDependencies:G,createPow:Cc},v2={typedDependencies:G,createToBest:xc},Ve={BigNumberDependencies:De,ComplexDependencies:Et,FractionDependencies:xs,absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,equalDependencies:Jr,fixDependencies:m2,formatDependencies:zo,isNumericDependencies:ws,multiplyScalarDependencies:jt,numberDependencies:fn,powDependencies:ki,roundDependencies:Ca,subtractScalarDependencies:Si,toBestDependencies:v2,createUnitClass:ch},SI={BigNumberDependencies:De,UnitDependencies:Ve,createAtomicMass:_p},NI={BigNumberDependencies:De,UnitDependencies:Ve,createAvogadro:Op},Vn={typedDependencies:G,createIsNegative:$u},Jm={typedDependencies:G,createCombinations:ld},S0={BigNumberDependencies:De,ComplexDependencies:Et,multiplyScalarDependencies:jt,powDependencies:ki,typedDependencies:G,createGamma:hd},Ro={gammaDependencies:S0,typedDependencies:G,createFactorial:dd},Ir={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,bignumberDependencies:Yr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createLarger:Zc},y2={bignumberDependencies:Yr,addScalarDependencies:rr,combinationsDependencies:Jm,divideScalarDependencies:$t,factorialDependencies:Ro,isIntegerDependencies:Xr,isNegativeDependencies:Vn,largerDependencies:Ir,multiplyScalarDependencies:jt,numberDependencies:fn,powDependencies:ki,subtractScalarDependencies:Si,typedDependencies:G,createStirlingS2:wd},CI={addScalarDependencies:rr,isIntegerDependencies:Xr,isNegativeDependencies:Vn,stirlingS2Dependencies:y2,typedDependencies:G,createBellNumbers:Sd},DI={typedDependencies:G,createBigint:Zu},AI={formatDependencies:zo,typedDependencies:G,createBin:gc},EI={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitAnd:Ja},MI={addDependencies:ft,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,notDependencies:Xm,typedDependencies:G,zerosDependencies:vr,createBitAndTransform:Sm},TI={typedDependencies:G,createBitNot:Rl},FI={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitOr:Za},_I={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createBitOrTransform:Nm},OI={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createBitXor:Ll},b2={createResultSet:fu},x2={NodeDependencies:Er,ResultSetDependencies:b2,createBlockNode:hf},BI={BigNumberDependencies:De,UnitDependencies:Ve,createBohrMagneton:hp},kI={BigNumberDependencies:De,UnitDependencies:Ve,createBohrRadius:vp},PI={BigNumberDependencies:De,UnitDependencies:Ve,createBoltzmann:Bp},zI={typedDependencies:G,createBoolean:Ku},RI={addScalarDependencies:rr,combinationsDependencies:Jm,divideScalarDependencies:$t,isIntegerDependencies:Xr,isNegativeDependencies:Vn,multiplyScalarDependencies:jt,typedDependencies:G,createCatalan:Nd},w2={BigNumberDependencies:De,ComplexDependencies:Et,FractionDependencies:xs,isNegativeDependencies:Vn,matrixDependencies:Ne,typedDependencies:G,unaryMinusDependencies:Yi,createCbrt:pl},S2={typedDependencies:G,createChainClass:Vf},LI={ChainDependencies:S2,typedDependencies:G,createChain:jf},II={BigNumberDependencies:De,UnitDependencies:Ve,createClassicalElectronRadius:yp},$I={typedDependencies:G,createClone:Bu},$r={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,bignumberDependencies:Yr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createSmaller:Gc},N2={DenseMatrixDependencies:it,smallerDependencies:$r,createImmutableDenseMatrixClass:sh},N0={typedDependencies:G,createGetMatrixDataType:Yl},Mr={ImmutableDenseMatrixDependencies:N2,getMatrixDataTypeDependencies:N0,createIndexClass:ah},Cs={typedDependencies:G,createIsPositive:Uu},Zm={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createLargerEq:Kc},Da={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createSmallerEq:Yc},Aa={bignumberDependencies:Yr,matrixDependencies:Ne,addDependencies:ft,equalDependencies:Jr,isPositiveDependencies:Cs,isZeroDependencies:wi,largerDependencies:Ir,largerEqDependencies:Zm,smallerDependencies:$r,smallerEqDependencies:Da,typedDependencies:G,createRange:ao},C2={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createColumn:to},qI={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createColumnTransform:em},HI={typedDependencies:G,createCombinationsWithRep:cd},Ds={BigNumberDependencies:De,DenseMatrixDependencies:it,FractionDependencies:xs,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createCompare:Ic},Ji={compareDependencies:Ds,typedDependencies:G,createCompareNatural:qc},D2={concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createCompareText:Hc},A2={NodeDependencies:Er,createConditionalNode:df},Wn={NodeDependencies:Er,createConstantNode:mf},E2={NodeDependencies:Er,typedDependencies:G,createFunctionAssignmentNode:vf},jn={UnitDependencies:Ve,NodeDependencies:Er,createSymbolNode:Ff},Gn={NodeDependencies:Er,SymbolNodeDependencies:jn,createFunctionNode:Of},Ea={NodeDependencies:Er,sizeDependencies:ir,createIndexNode:bf},Ma={NodeDependencies:Er,createObjectNode:wf},dn={NodeDependencies:Er,createOperatorNode:Nf},As={NodeDependencies:Er,createParenthesisNode:Df},M2={NodeDependencies:Er,createRangeNode:Ef},T2={NodeDependencies:Er,createRelationalNode:Tf},Pi={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,AssignmentNodeDependencies:f2,BlockNodeDependencies:x2,ConditionalNodeDependencies:A2,ConstantNodeDependencies:Wn,FunctionAssignmentNodeDependencies:E2,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,RangeNodeDependencies:M2,RelationalNodeDependencies:T2,SymbolNodeDependencies:jn,numericDependencies:xi,typedDependencies:G,createParse:Bf},UI={parseDependencies:Pi,typedDependencies:G,createCompile:kf},Qm={ComplexDependencies:Et,typedDependencies:G,createComplex:tl},VI={addScalarDependencies:rr,combinationsDependencies:Jm,isIntegerDependencies:Xr,isNegativeDependencies:Vn,isPositiveDependencies:Cs,largerDependencies:Ir,typedDependencies:G,createComposition:Cd},WI={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createConcatTransform:hm},jI={BigNumberDependencies:De,UnitDependencies:Ve,createConductanceQuantum:fp},yr={divideScalarDependencies:$t,equalScalarDependencies:ot,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createDivide:rd},F2={addDependencies:ft,divideDependencies:yr,typedDependencies:G,createMean:wo},zi={ComplexDependencies:Et,typedDependencies:G,createSqrt:Fl},Gt={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createSubtract:Ol},C0={addDependencies:ft,numericDependencies:xi,typedDependencies:G,createSum:bo},GI={addDependencies:ft,divideDependencies:yr,matrixDependencies:Ne,meanDependencies:F2,multiplyDependencies:Nt,powDependencies:ki,sqrtDependencies:zi,subtractDependencies:Gt,sumDependencies:C0,typedDependencies:G,createCorr:ud},D0={typedDependencies:G,createCos:Eh},XI={typedDependencies:G,createCosh:Mh},YI={BigNumberDependencies:De,typedDependencies:G,createCot:Th},JI={BigNumberDependencies:De,typedDependencies:G,createCoth:Fh},ZI={BigNumberDependencies:De,UnitDependencies:Ve,createCoulomb:up},QI={BigNumberDependencies:De,UnitDependencies:Ve,createCoulombConstant:lp},_2={multiplyScalarDependencies:jt,numericDependencies:xi,typedDependencies:G,createProd:pc},KI={prodDependencies:_2,sizeDependencies:ir,typedDependencies:G,createCount:Wl},e$={UnitDependencies:Ve,typedDependencies:G,createCreateUnit:dh},t$={matrixDependencies:Ne,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createCross:jl},r$={BigNumberDependencies:De,typedDependencies:G,createCsc:_h},i$={BigNumberDependencies:De,typedDependencies:G,createCsch:Oh},Lo={matrixDependencies:Ne,typedDependencies:G,createTranspose:sc},A0={conjDependencies:Ss,transposeDependencies:Lo,typedDependencies:G,createCtranspose:ac},n$={typedDependencies:G,createCube:gl},E0={numericDependencies:xi,typedDependencies:G,createUnaryPlus:ll},s$={addDependencies:ft,typedDependencies:G,unaryPlusDependencies:E0,createCumSum:xo},a$={addDependencies:ft,typedDependencies:G,unaryPlusDependencies:E0,createCumSumTransform:gm},Io={equalDependencies:Jr,typedDependencies:G,createDeepEqual:eh},O2={createReplacer:Rd},B2={ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,parseDependencies:Pi,typedDependencies:G,createResolve:Fd},M0={bignumberDependencies:Yr,fractionDependencies:Po,AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,SymbolNodeDependencies:jn,matrixDependencies:Ne,typedDependencies:G,createSimplifyConstant:Md},T0={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,isZeroDependencies:wi,multiplyDependencies:Nt,parseDependencies:Pi,powDependencies:ki,subtractDependencies:Gt,typedDependencies:G,createSimplifyCore:Td},Km={AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,equalDependencies:Jr,parseDependencies:Pi,replacerDependencies:O2,resolveDependencies:B2,simplifyConstantDependencies:M0,simplifyCoreDependencies:T0,typedDependencies:G,createSimplify:Ed},o$={ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,equalDependencies:Jr,isZeroDependencies:wi,numericDependencies:xi,parseDependencies:Pi,simplifyDependencies:Km,typedDependencies:G,createDerivative:Od},u$={BigNumberDependencies:De,UnitDependencies:Ve,createDeuteronMass:Cp},k2={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,matrixDependencies:Ne,typedDependencies:G,createDiag:Gl},l$={matrixDependencies:Ne,numberDependencies:fn,subtractDependencies:Gt,typedDependencies:G,createDiff:so},c$={bignumberDependencies:Yr,matrixDependencies:Ne,numberDependencies:fn,subtractDependencies:Gt,typedDependencies:G,createDiffTransform:fm},h$={absDependencies:Lr,addScalarDependencies:rr,deepEqualDependencies:Io,divideScalarDependencies:$t,multiplyScalarDependencies:jt,sqrtDependencies:zi,subtractScalarDependencies:Si,typedDependencies:G,createDistance:id},$o={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createDotDivide:Fc},f$={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createDotMultiply:Pl},d$={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,powDependencies:ki,typedDependencies:G,createDotPow:Tc},P2={BigNumberDependencies:De,createE:Wd},p$={BigNumberDependencies:De,createEfimovFactor:Fp},Es={typedDependencies:G,createFlatten:Xl},F0={typedDependencies:G,createIm:ql},_0={flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createMatrixFromColumns:al},z2={BigNumberDependencies:De,FractionDependencies:xs,complexDependencies:Qm,typedDependencies:G,createSign:Tl},O0={addScalarDependencies:rr,complexDependencies:Qm,conjDependencies:Ss,divideScalarDependencies:$t,equalDependencies:Jr,identityDependencies:Un,isZeroDependencies:wi,matrixDependencies:Ne,multiplyScalarDependencies:jt,signDependencies:z2,sqrtDependencies:zi,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,zerosDependencies:vr,createQr:If},B0={typedDependencies:G,createRe:Hl},R2={isIntegerDependencies:Xr,matrixDependencies:Ne,typedDependencies:G,createReshape:Kl},eg={typedDependencies:G,createSin:Ph},k0={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createUsolve:Oc},L2={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createUsolveAll:kc},I2={absDependencies:Lr,addDependencies:ft,addScalarDependencies:rr,atanDependencies:d2,bignumberDependencies:Yr,columnDependencies:C2,complexDependencies:Qm,cosDependencies:D0,diagDependencies:k2,divideScalarDependencies:$t,dotDependencies:Ym,equalDependencies:Jr,flattenDependencies:Es,imDependencies:F0,invDependencies:Ns,largerDependencies:Ir,matrixDependencies:Ne,matrixFromColumnsDependencies:_0,multiplyDependencies:Nt,multiplyScalarDependencies:jt,numberDependencies:fn,qrDependencies:O0,reDependencies:B0,reshapeDependencies:R2,sinDependencies:eg,sizeDependencies:ir,smallerDependencies:$r,sqrtDependencies:zi,subtractDependencies:Gt,typedDependencies:G,usolveDependencies:k0,usolveAllDependencies:L2,createEigs:Jf},m$={BigNumberDependencies:De,UnitDependencies:Ve,createElectricConstant:ap},g$={BigNumberDependencies:De,UnitDependencies:Ve,createElectronMass:bp},v$={BigNumberDependencies:De,UnitDependencies:Ve,createElementaryCharge:cp},y$={compareTextDependencies:D2,isZeroDependencies:wi,typedDependencies:G,createEqualText:Wc},b$={typedDependencies:G,createErf:hc},P0={parseDependencies:Pi,typedDependencies:G,createEvaluate:Pf},$2={typedDependencies:G,createExp:vl},x$={absDependencies:Lr,addDependencies:ft,identityDependencies:Un,invDependencies:Ns,multiplyDependencies:Nt,typedDependencies:G,createExpm:Zf},w$={ComplexDependencies:Et,typedDependencies:G,createExpm1:yl},S$={createFalse:Id},N$={BigNumberDependencies:De,UnitDependencies:Ve,createFaraday:kp},C$={BigNumberDependencies:De,UnitDependencies:Ve,createFermiCoupling:xp},q2={ComplexDependencies:Et,createI:Kd},z0={ComplexDependencies:Et,typedDependencies:G,createLog2:Dl},H2={BigNumberDependencies:De,createTau:Vd},U2={addScalarDependencies:rr,ceilDependencies:w0,conjDependencies:Ss,divideScalarDependencies:$t,dotDivideDependencies:$o,expDependencies:$2,iDependencies:q2,log2Dependencies:z0,matrixDependencies:Ne,multiplyScalarDependencies:jt,powDependencies:ki,tauDependencies:H2,typedDependencies:G,createFft:uc},V2={largerDependencies:Ir,smallerDependencies:$r,createFibonacciHeapClass:oh},D$={typedDependencies:G,createFilter:ro},A$={typedDependencies:G,createFilterTransform:tm},E$={BigNumberDependencies:De,createFineStructure:wp},M$={BigNumberDependencies:De,UnitDependencies:Ve,createFirstRadiation:Pp},T$={typedDependencies:G,createForEach:io},F$={typedDependencies:G,createForEachTransform:rm},_$={ComplexDependencies:Et,addDependencies:ft,divideDependencies:yr,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createFreqz:Pd},O$={BigNumberDependencies:De,UnitDependencies:Ve,createGasConstant:Rp},B$={BigNumberDependencies:De,DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createGcd:wl},k$={BigNumberDependencies:De,UnitDependencies:Ve,createGravitationConstant:rp},P$={BigNumberDependencies:De,UnitDependencies:Ve,createGravity:jp},z$={BigNumberDependencies:De,UnitDependencies:Ve,createHartreeEnergy:Sp},R$={isNumericDependencies:ws,typedDependencies:G,createHasNumericValue:Hu},W2={evaluateDependencies:P0,createHelpClass:Uf},L$={HelpDependencies:W2,typedDependencies:G,createHelp:Wf},I$={formatDependencies:zo,typedDependencies:G,createHex:yc},$$={absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,isPositiveDependencies:Cs,multiplyScalarDependencies:jt,smallerDependencies:$r,sqrtDependencies:zi,typedDependencies:G,createHypot:Jh},q$={conjDependencies:Ss,dotDivideDependencies:$o,fftDependencies:U2,typedDependencies:G,createIfft:lc},j2={IndexDependencies:Mr,typedDependencies:G,createIndex:ef},H$={IndexDependencies:Mr,getMatrixDataTypeDependencies:N0,createIndexTransform:im},U$={BigNumberDependencies:De,createInfinity:qd},V$={absDependencies:Lr,addDependencies:ft,addScalarDependencies:rr,divideScalarDependencies:$t,equalScalarDependencies:ot,flattenDependencies:Es,isNumericDependencies:ws,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,multiplyScalarDependencies:jt,smallerDependencies:$r,subtractDependencies:Gt,typedDependencies:G,createIntersect:nd},W$={BigNumberDependencies:De,UnitDependencies:Ve,createInverseConductanceQuantum:dp},G2={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,roundDependencies:Ca,typedDependencies:G,zerosDependencies:vr,createMod:Xa},X2={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createXgcd:Bl},j$={BigNumberDependencies:De,addDependencies:ft,equalDependencies:Jr,isIntegerDependencies:Xr,modDependencies:G2,smallerDependencies:$r,typedDependencies:G,xgcdDependencies:X2,createInvmod:kl},pn={typedDependencies:G,createIsNaN:Wu},G$={typedDependencies:G,createIsPrime:wc},R0={typedDependencies:G,createTypeOf:ju},L0={ComplexDependencies:Et,divideScalarDependencies:$t,typeOfDependencies:R0,typedDependencies:G,createLog:Ac},Ms={typedDependencies:G,createMap:no},X$={divideDependencies:yr,dotDivideDependencies:$o,isNumericDependencies:ws,logDependencies:L0,mapDependencies:Ms,matrixDependencies:Ne,multiplyDependencies:Nt,sumDependencies:C0,typedDependencies:G,createKldivergence:pd},Y$={BigNumberDependencies:De,UnitDependencies:Ve,createKlitzing:gp},J$={matrixDependencies:Ne,multiplyScalarDependencies:jt,typedDependencies:G,createKron:Zl},Z$={BigNumberDependencies:De,createLN10:Xd},Q$={BigNumberDependencies:De,createLN2:Gd},K$={BigNumberDependencies:De,createLOG10E:Jd},e6={BigNumberDependencies:De,createLOG2E:Yd},t6={concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createLcm:Nl},r6={parseDependencies:Pi,typedDependencies:G,createLeafCount:Dd},i6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createLeftShift:Pc},n6={ComplexDependencies:Et,typedDependencies:G,createLgamma:fd},s6={ComplexDependencies:Et,typedDependencies:G,createLog10:Cl},a6={ComplexDependencies:Et,divideScalarDependencies:$t,logDependencies:L0,typedDependencies:G,createLog1p:Ec},o6={BigNumberDependencies:De,UnitDependencies:Ve,createLoschmidt:zp},Y2={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createLsolve:_c},u6={DenseMatrixDependencies:it,divideScalarDependencies:$t,equalScalarDependencies:ot,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,createLsolveAll:Bc},J2={FibonacciHeapDependencies:V2,addScalarDependencies:rr,equalScalarDependencies:ot,createSpaClass:uh},Z2={DenseMatrixDependencies:it,SpaDependencies:J2,SparseMatrixDependencies:tr,absDependencies:Lr,addScalarDependencies:rr,divideScalarDependencies:$t,equalScalarDependencies:ot,largerDependencies:Ir,matrixDependencies:Ne,multiplyScalarDependencies:jt,subtractScalarDependencies:Si,typedDependencies:G,unaryMinusDependencies:Yi,createLup:Lf},Q2={SparseMatrixDependencies:tr,absDependencies:Lr,addDependencies:ft,divideScalarDependencies:$t,largerDependencies:Ir,largerEqDependencies:Zm,multiplyDependencies:Nt,subtractDependencies:Gt,transposeDependencies:Lo,typedDependencies:G,createSlu:$f},K2={DenseMatrixDependencies:it,lsolveDependencies:Y2,lupDependencies:Z2,matrixDependencies:Ne,sluDependencies:Q2,typedDependencies:G,usolveDependencies:k0,createLusolve:qf},I0={absDependencies:Lr,addDependencies:ft,conjDependencies:Ss,ctransposeDependencies:A0,eigsDependencies:I2,equalScalarDependencies:ot,largerDependencies:Ir,matrixDependencies:Ne,multiplyDependencies:Nt,powDependencies:ki,smallerDependencies:$r,sqrtDependencies:zi,typedDependencies:G,createNorm:Zh},eE={identityDependencies:Un,matrixDependencies:Ne,multiplyDependencies:Nt,normDependencies:I0,qrDependencies:O0,subtractDependencies:Gt,typedDependencies:G,createSchur:ed},tE={absDependencies:Lr,addDependencies:ft,concatDependencies:mt,identityDependencies:Un,indexDependencies:j2,lusolveDependencies:K2,matrixDependencies:Ne,matrixFromColumnsDependencies:_0,multiplyDependencies:Nt,rangeDependencies:Aa,schurDependencies:eE,subsetDependencies:ni,subtractDependencies:Gt,transposeDependencies:Lo,typedDependencies:G,createSylvester:Kf},l6={matrixDependencies:Ne,multiplyDependencies:Nt,sylvesterDependencies:tE,transposeDependencies:Lo,typedDependencies:G,createLyap:td},tg={compareDependencies:Ds,isNaNDependencies:pn,isNumericDependencies:ws,typedDependencies:G,createPartitionSelect:ih},rE={addDependencies:ft,compareDependencies:Ds,divideDependencies:yr,partitionSelectDependencies:tg,typedDependencies:G,createMedian:ad},c6={absDependencies:Lr,mapDependencies:Ms,medianDependencies:rE,subtractDependencies:Gt,typedDependencies:G,createMad:od},h6={BigNumberDependencies:De,UnitDependencies:Ve,createMagneticConstant:sp},f6={BigNumberDependencies:De,UnitDependencies:Ve,createMagneticFluxQuantum:pp},qo={isIntegerDependencies:Xr,typedDependencies:G,createMapSlices:la},d6={isIntegerDependencies:Xr,typedDependencies:G,createMapSlicesTransform:Kp},p6={typedDependencies:G,createMapTransform:nm},m6={isZeroDependencies:wi,matrixDependencies:Ne,typedDependencies:G,createMatrixFromFunction:nl},g6={flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createMatrixFromRows:sl},$0={isNaNDependencies:pn,largerDependencies:Ir,numericDependencies:xi,typedDependencies:G,createMax:po},v6={isNaNDependencies:pn,largerDependencies:Ir,numericDependencies:xi,typedDependencies:G,createMaxTransform:sm},y6={addDependencies:ft,divideDependencies:yr,typedDependencies:G,createMeanTransform:am},b6={isNaNDependencies:pn,numericDependencies:xi,smallerDependencies:$r,typedDependencies:G,createMin:mo},x6={isNaNDependencies:pn,numericDependencies:xi,smallerDependencies:$r,typedDependencies:G,createMinTransform:om},w6={isNaNDependencies:pn,isNumericDependencies:ws,typedDependencies:G,createMode:dc},S6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarMass:Vp},N6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarMassC12:Wp},C6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarPlanckConstant:Lp},D6={BigNumberDependencies:De,UnitDependencies:Ve,createMolarVolume:Ip},A6={addDependencies:ft,divideDependencies:yr,factorialDependencies:Ro,isIntegerDependencies:Xr,isPositiveDependencies:Cs,multiplyDependencies:Nt,typedDependencies:G,createMultinomial:md},E6={BigNumberDependencies:De,createNaN:Hd},M6={BigNumberDependencies:De,UnitDependencies:Ve,createNeutronMass:Dp},T6={BigNumberDependencies:De,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createNthRoot:Ml},F6={ComplexDependencies:Et,divideScalarDependencies:$t,typedDependencies:G,createNthRoots:Mc},_6={BigNumberDependencies:De,UnitDependencies:Ve,createNuclearMagneton:mp},O6={createNull:$d},B6={deepEqualDependencies:Io,flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createNullish:Qa},k6={deepEqualDependencies:Io,flattenDependencies:Es,matrixDependencies:Ne,sizeDependencies:ir,typedDependencies:G,createNullishTransform:wm},P6={formatDependencies:zo,typedDependencies:G,createOct:vc},z6={BigNumberDependencies:De,matrixDependencies:Ne,typedDependencies:G,createOnes:Ql},R6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createOr:Ka},L6={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createOrTransform:xm},iE={evaluateDependencies:P0,parseDependencies:Pi,createParserClass:zf},I6={ParserDependencies:iE,typedDependencies:G,createParser:Rf},$6={factorialDependencies:Ro,typedDependencies:G,createPermutations:gd},q6={BigNumberDependencies:De,createPhi:jd},q0={BigNumberDependencies:De,createPi:Ud},H6={typedDependencies:G,createPickRandom:yd},U6={ComplexDependencies:Et,addDependencies:ft,ctransposeDependencies:A0,deepEqualDependencies:Io,divideScalarDependencies:$t,dotDependencies:Ym,dotDivideDependencies:$o,equalDependencies:Jr,invDependencies:Ns,matrixDependencies:Ne,multiplyDependencies:Nt,typedDependencies:G,createPinv:Yf},V6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckCharge:Jp},W6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckConstant:ip},j6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckLength:Gp},G6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckMass:Xp},X6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckTemperature:Zp},Y6={BigNumberDependencies:De,UnitDependencies:Ve,createPlanckTime:Yp},J6={addDependencies:ft,cbrtDependencies:w2,divideDependencies:yr,equalScalarDependencies:ot,imDependencies:F0,isZeroDependencies:wi,multiplyDependencies:Nt,reDependencies:B0,sqrtDependencies:zi,subtractDependencies:Gt,typeOfDependencies:R0,typedDependencies:G,unaryMinusDependencies:Yi,createPolynomialRoot:Hf},Z6={typedDependencies:G,createPrint:co},Q6={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createPrintTransform:ym},K6={BigNumberDependencies:De,UnitDependencies:Ve,createProtonMass:Np},e7={bignumberDependencies:Yr,addDependencies:ft,compareDependencies:Ds,divideDependencies:yr,isIntegerDependencies:Xr,largerDependencies:Ir,mapSlicesDependencies:qo,multiplyDependencies:Nt,partitionSelectDependencies:tg,smallerDependencies:$r,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createQuantileSeq:No},t7={addDependencies:ft,bignumberDependencies:Yr,compareDependencies:Ds,divideDependencies:yr,isIntegerDependencies:Xr,largerDependencies:Ir,mapSlicesDependencies:qo,multiplyDependencies:Nt,partitionSelectDependencies:tg,smallerDependencies:$r,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createQuantileSeqTransform:mm},r7={BigNumberDependencies:De,UnitDependencies:Ve,createQuantumOfCirculation:Ap},i7={typedDependencies:G,createRandom:bd},n7={log2Dependencies:z0,typedDependencies:G,createRandomInt:xd},s7={createRangeClass:Cu},a7={bignumberDependencies:Yr,matrixDependencies:Ne,addDependencies:ft,equalDependencies:Jr,isPositiveDependencies:Cs,isZeroDependencies:wi,largerDependencies:Ir,largerEqDependencies:Zm,smallerDependencies:$r,smallerEqDependencies:Da,typedDependencies:G,createRangeTransform:um},o7={bignumberDependencies:Yr,fractionDependencies:Po,AccessorNodeDependencies:Sa,ArrayNodeDependencies:Na,ConstantNodeDependencies:Wn,FunctionNodeDependencies:Gn,IndexNodeDependencies:Ea,ObjectNodeDependencies:Ma,OperatorNodeDependencies:dn,ParenthesisNodeDependencies:As,SymbolNodeDependencies:jn,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,isZeroDependencies:wi,matrixDependencies:Ne,multiplyDependencies:Nt,parseDependencies:Pi,powDependencies:ki,simplifyDependencies:Km,simplifyConstantDependencies:M0,simplifyCoreDependencies:T0,subtractDependencies:Gt,typedDependencies:G,createRationalize:Bd},u7={BigNumberDependencies:De,UnitDependencies:Ve,createReducedPlanckConstant:np},l7={matrixDependencies:Ne,createResize:ec},c7={createReviver:zd},h7={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRightArithShift:zc},f7={DenseMatrixDependencies:it,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createRightLogShift:Rc},nE={BigNumberDependencies:De,DenseMatrixDependencies:it,SparseMatrixDependencies:tr,addScalarDependencies:rr,cosDependencies:D0,matrixDependencies:Ne,multiplyScalarDependencies:jt,normDependencies:I0,sinDependencies:eg,typedDependencies:G,unaryMinusDependencies:Yi,createRotationMatrix:rc},d7={multiplyDependencies:Nt,rotationMatrixDependencies:nE,typedDependencies:G,createRotate:tc},p7={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createRow:oo},m7={IndexDependencies:Mr,matrixDependencies:Ne,rangeDependencies:Aa,typedDependencies:G,createRowTransform:lm},g7={BigNumberDependencies:De,UnitDependencies:Ve,createRydberg:Ep},v7={BigNumberDependencies:De,createSQRT1_2:Zd},y7={BigNumberDependencies:De,createSQRT2:Qd},b7={BigNumberDependencies:De,createSackurTetrode:$p},x7={BigNumberDependencies:De,typedDependencies:G,createSec:Bh},w7={BigNumberDependencies:De,typedDependencies:G,createSech:kh},S7={BigNumberDependencies:De,UnitDependencies:Ve,createSecondRadiation:qp},N7={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetCartesian:Ih},sE={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetDifference:$h},C7={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetDistinct:qh},aE={DenseMatrixDependencies:it,IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetIntersect:Hh},D7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetIsSubset:Uh},A7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetMultiplicity:Vh},E7={IndexDependencies:Mr,compareNaturalDependencies:Ji,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetPowerset:Wh},M7={compareNaturalDependencies:Ji,typedDependencies:G,createSetSize:jh},oE={IndexDependencies:Mr,concatDependencies:mt,setDifferenceDependencies:sE,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetSymDifference:Gh},T7={IndexDependencies:Mr,concatDependencies:mt,setIntersectDependencies:aE,setSymDifferenceDependencies:oE,sizeDependencies:ir,subsetDependencies:ni,typedDependencies:G,createSetUnion:Xh},F7={typedDependencies:G,createSinh:zh},_7={absDependencies:Lr,addDependencies:ft,bignumberDependencies:Yr,divideDependencies:yr,isNegativeDependencies:Vn,isPositiveDependencies:Cs,largerDependencies:Ir,mapDependencies:Ms,matrixDependencies:Ne,maxDependencies:$0,multiplyDependencies:Nt,smallerDependencies:$r,subtractDependencies:Gt,typedDependencies:G,unaryMinusDependencies:Yi,createSolveODE:cc},O7={compareDependencies:Ds,compareNaturalDependencies:Ji,matrixDependencies:Ne,typedDependencies:G,createSort:nh},B7={SparseMatrixDependencies:tr,typedDependencies:G,createSparse:fh},k7={BigNumberDependencies:De,UnitDependencies:Ve,createSpeedOfLight:tp},P7={typedDependencies:G,createSplitUnit:ol},z7={absDependencies:Lr,addDependencies:ft,identityDependencies:Un,invDependencies:Ns,mapDependencies:Ms,maxDependencies:$0,multiplyDependencies:Nt,sizeDependencies:ir,sqrtDependencies:zi,subtractDependencies:Gt,typedDependencies:G,createSqrtm:Qf},R7={typedDependencies:G,createSquare:_l},L7={typedDependencies:G,createSqueeze:nc},H0={addDependencies:ft,divideDependencies:yr,isNaNDependencies:pn,mapSlicesDependencies:qo,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createVariance:So},I7={mapDependencies:Ms,sqrtDependencies:zi,typedDependencies:G,varianceDependencies:H0,createStd:Co},$7={mapDependencies:Ms,sqrtDependencies:zi,typedDependencies:G,varianceDependencies:H0,createStdTransform:dm},q7={BigNumberDependencies:De,UnitDependencies:Ve,createStefanBoltzmann:Hp},H7={typedDependencies:G,createString:Qu},U7={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,zerosDependencies:vr,createSubsetTransform:cm},V7={addDependencies:ft,numericDependencies:xi,typedDependencies:G,createSumTransform:pm},W7={OperatorNodeDependencies:dn,parseDependencies:Pi,simplifyDependencies:Km,typedDependencies:G,createSymbolicEqual:_d},j7={typedDependencies:G,createTan:Rh},G7={typedDependencies:G,createTanh:Lh},X7={BigNumberDependencies:De,UnitDependencies:Ve,createThomsonCrossSection:Mp},Y7={concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createTo:bc},J7={addDependencies:ft,matrixDependencies:Ne,typedDependencies:G,createTrace:Kh},Z7={createTrue:Ld},Q7={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,equalScalarDependencies:ot,matrixDependencies:Ne,typedDependencies:G,createUnequal:rh},K7={UnitDependencies:Ve,typedDependencies:G,createUnitFunction:hh},eq={eDependencies:P2,createUppercaseE:Nv},tq={piDependencies:q0,createUppercasePi:Sv},rq={BigNumberDependencies:De,UnitDependencies:Ve,createVacuumImpedance:op},iq={addDependencies:ft,divideDependencies:yr,isNaNDependencies:pn,mapSlicesDependencies:qo,multiplyDependencies:Nt,subtractDependencies:Gt,typedDependencies:G,createVarianceTransform:vm},nq={createVersion:ep},sq={BigNumberDependencies:De,createWeakMixingAngle:Tp},aq={BigNumberDependencies:De,UnitDependencies:Ve,createWienDisplacement:Up},oq={DenseMatrixDependencies:it,SparseMatrixDependencies:tr,concatDependencies:mt,matrixDependencies:Ne,typedDependencies:G,createXor:Vl},uq={BigNumberDependencies:De,ComplexDependencies:Et,addDependencies:ft,divideDependencies:yr,equalDependencies:Jr,factorialDependencies:Ro,gammaDependencies:S0,isNegativeDependencies:Vn,multiplyDependencies:Nt,piDependencies:q0,powDependencies:ki,sinDependencies:eg,smallerEqDependencies:Da,subtractDependencies:Gt,typedDependencies:G,createZeta:fc},lq={ComplexDependencies:Et,addDependencies:ft,multiplyDependencies:Nt,numberDependencies:fn,typedDependencies:G,createZpk2tf:kd},cq=sI,U0={exports:{}};function V0(){}V0.prototype={on:function(n,e,t){var r=this.e||(this.e={});return(r[n]||(r[n]=[])).push({fn:e,ctx:t}),this},once:function(n,e,t){var r=this;function i(){r.off(n,i),e.apply(t,arguments)}return i._=e,this.on(n,i,t)},emit:function(n){var e=[].slice.call(arguments,1),t=((this.e||(this.e={}))[n]||[]).slice(),r=0,i=t.length;for(r;r<i;r++)t[r].fn.apply(t[r].ctx,e);return this},off:function(n,e){var t=this.e||(this.e={}),r=t[n],i=[];if(r&&e)for(var s=0,a=r.length;s<a;s++)r[s].fn!==e&&r[s].fn._!==e&&i.push(r[s]);return i.length?t[n]=i:delete t[n],this}},U0.exports=V0,U0.exports.TinyEmitter=V0;var hq=U0.exports;const fq=$c(hq);function dq(n){var e=new fq;return n.on=e.on.bind(e),n.off=e.off.bind(e),n.once=e.once.bind(e),n.emit=e.emit.bind(e),n}function pq(n,e,t,r){function i(v,S){var g=arguments.length;if(g!==1&&g!==2)throw new Vi("import",g,1,2);S||(S={});function b(D,C,A){if(Array.isArray(C))C.forEach(O=>b(D,O));else if(yn(C)||h(C))for(var E in C)Te(C,E)&&b(D,C[E],E);else if(qa(C)||A!==void 0){var F=qa(C)?m(C)?C.fn+".transform":C.fn:A;if(Te(D,F)&&D[F]!==C&&!S.silent)throw new Error('Cannot import "'+F+'" twice');D[F]=C}else if(!S.silent)throw new TypeError("Factory, Object, or Array expected")}var w={};b(w,v);for(var x in w)if(Te(w,x)){var N=w[x];if(qa(N))u(N,S);else if(c(N))s(x,N,S);else if(!S.silent)throw new TypeError("Factory, Object, or Array expected")}}function s(v,S,g){var b;if(g.wrap&&typeof S=="function"&&(S=l(S)),f(S)&&(S=n(v,{[S.signature]:S})),n.isTypedFunction(t[v])&&n.isTypedFunction(S)){g.override?S=n(v,S.signatures):S=n(t[v],S),t[v]=S,delete r[v],a(v,S),t.emit("import",v,function(){return S});return}var w=t[v]!==void 0,x=(b=t.Unit)===null||b===void 0?void 0:b.isValuelessUnit(v);if(!w&&!x||g.override){t[v]=S,delete r[v],a(v,S),t.emit("import",v,function(){return S});return}if(!g.silent)throw new Error('Cannot import "'+v+'": already exists')}function a(v,S){S&&typeof S.transform=="function"?(t.expression.transform[v]=S.transform,d(v)&&(t.expression.mathWithTransform[v]=S.transform)):(delete t.expression.transform[v],d(v)&&(t.expression.mathWithTransform[v]=S))}function o(v){delete t.expression.transform[v],d(v)?t.expression.mathWithTransform[v]=t[v]:delete t.expression.mathWithTransform[v]}function l(v){var S=function(){for(var b=[],w=0,x=arguments.length;w<x;w++){var N=arguments[w];b[w]=N&&N.valueOf()}return v.apply(t,b)};return v.transform&&(S.transform=v.transform),S}function u(v,S){var g,b,w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v.fn;if(w.includes("."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(w));var x=m(v)?t.expression.transform:t,N=w in t.expression.transform,D=Te(x,w)?x[w]:void 0,C=function(){var k={};v.dependencies.map(Oy).forEach(T=>{if(T.includes("."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(T));T==="math"?k.math=t:T==="mathWithTransform"?k.mathWithTransform=t.expression.mathWithTransform:T==="classes"?k.classes=t:k[T]=t[T]});var B=v(k);if(B&&typeof B.transform=="function")throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with export const path = "expression.transform"');if(D===void 0||S.override)return B;if(n.isTypedFunction(D)&&n.isTypedFunction(B))return n(D,B);if(S.silent)return D;throw new Error('Cannot import "'+w+'": already exists')},A=(g=(b=v.meta)===null||b===void 0?void 0:b.formerly)!==null&&g!==void 0?g:"",E=m(v)||p(v),F=t.expression.mathWithTransform;!v.meta||v.meta.lazy!==!1?(is(x,w,C),A&&is(x,A,C),D&&N?(o(w),A&&o(A)):E&&(is(F,w,()=>x[w]),A&&is(F,A,()=>x[w]))):(x[w]=C(),A&&(x[A]=x[w]),D&&N?(o(w),A&&o(A)):E&&(is(F,w,()=>x[w]),A&&is(F,A,()=>x[w]))),r[w]=v,t.emit("import",w,C)}function c(v){return typeof v=="function"||typeof v=="number"||typeof v=="string"||typeof v=="boolean"||v===null||br(v)||ci(v)||Xe(v)||vn(v)||Re(v)||Array.isArray(v)}function h(v){return typeof v=="object"&&v[Symbol.toStringTag]==="Module"}function f(v){return typeof v=="function"&&typeof v.signature=="string"}function d(v){return!Te(y,v)}function p(v){return!v.fn.includes(".")&&!Te(y,v.fn)&&(!v.meta||!v.meta.isClass)}function m(v){return v!==void 0&&v.meta!==void 0&&v.meta.isTransformFunction===!0||!1}var y={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return i}function uE(n,e){var t=wt({},tu,e);if(typeof Object.create!="function")throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=dq({isNumber:Je,isComplex:ci,isBigNumber:Xe,isBigInt:ts,isFraction:vn,isUnit:br,isString:nr,isArray:St,isMatrix:Re,isCollection:Or,isDenseMatrix:Vs,isSparseMatrix:Ki,isRange:Ia,isIndex:Ws,isBoolean:hg,isResultSet:fg,isHelp:nu,isFunction:su,isDate:dg,isRegExp:pg,isObject:yn,isMap:bn,isPartitionedMap:Ny,isObjectWrappingMap:Cy,isNull:mg,isUndefined:gg,isAccessorNode:en,isArrayNode:Vr,isAssignmentNode:vg,isBlockNode:yg,isConditionalNode:bg,isConstantNode:ct,isFunctionAssignmentNode:rs,isFunctionNode:qi,isIndexNode:xn,isNode:bt,isObjectNode:js,isOperatorNode:qt,isParenthesisNode:Ai,isRangeNode:wg,isRelationalNode:Sg,isSymbolNode:Xt,isChain:au});r.config=IE(t,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var i=[],s=[];function a(c){if(qa(c))return c(r);var h=c[Object.keys(c)[0]];if(qa(h))return h(r);if(!RE(c))throw console.warn("Factory object with properties `type`, `name`, and `factory` expected",c),new Error("Factory object with properties `type`, `name`, and `factory` expected");var f=i.indexOf(c),d;return f===-1?(c.math===!0?d=c.factory(r.type,t,a,r.typed,r):d=c.factory(r.type,t,a,r.typed),i.push(c),s.push(d)):d=s[f],d}var o={};function l(){for(var c=arguments.length,h=new Array(c),f=0;f<c;f++)h[f]=arguments[f];return r.typed.apply(r.typed,h)}l.isTypedFunction=$a.isTypedFunction;var u=pq(l,a,r,o);return r.import=u,r.on("config",()=>{Object.values(o).forEach(c=>{c&&c.meta&&c.meta.recreateOnConfigChange&&u(c,{override:!0})})}),r.create=uE.bind(null,n),r.factory=R,r.import(Object.values(zE(n))),r.ArgumentsError=Vi,r.DimensionError=Ke,r.IndexError=Kr,r}const W0=Object.freeze(Object.defineProperty({__proto__:null,AccessorNode:ys,AccessorNodeDependencies:Sa,ArgumentsError:Vi,ArrayNode:vs,ArrayNodeDependencies:Na,AssignmentNode:v0,AssignmentNodeDependencies:f2,BigNumber:Ce,BigNumberDependencies:De,BlockNode:d0,BlockNodeDependencies:x2,Chain:Um,ChainDependencies:S2,Complex:Ct,ComplexDependencies:Et,ConditionalNode:p0,ConditionalNodeDependencies:A2,ConstantNode:ln,ConstantNodeDependencies:Wn,DenseMatrix:tt,DenseMatrixDependencies:it,DimensionError:Ke,EDependencies:eq,FibonacciHeap:Wv,FibonacciHeapDependencies:V2,Fraction:kn,FractionDependencies:xs,FunctionAssignmentNode:g0,FunctionAssignmentNodeDependencies:E2,FunctionNode:hn,FunctionNodeDependencies:Gn,Help:b0,HelpDependencies:W2,ImmutableDenseMatrix:Hv,ImmutableDenseMatrixDependencies:N2,Index:mr,IndexDependencies:Mr,IndexError:Kr,IndexNode:bs,IndexNodeDependencies:Ea,InfinityDependencies:U$,LN10:LN,LN10Dependencies:Z$,LN2:YN,LN2Dependencies:Q$,LOG10E:IN,LOG10EDependencies:K$,LOG2E:vC,LOG2EDependencies:e6,Matrix:Do,MatrixDependencies:Gm,NaNDependencies:E6,Node:gr,NodeDependencies:Er,ObjectNode:gs,ObjectNodeDependencies:Ma,OperatorNode:Xi,OperatorNodeDependencies:dn,PIDependencies:tq,ParenthesisNode:Hn,ParenthesisNodeDependencies:As,Parser:x0,ParserDependencies:iE,Range:UN,RangeDependencies:s7,RangeNode:m0,RangeNodeDependencies:M2,RelationalNode:f0,RelationalNodeDependencies:T2,ResultSet:Mv,ResultSetDependencies:b2,SQRT1_2:VN,SQRT1_2Dependencies:v7,SQRT2:JN,SQRT2Dependencies:y7,Spa:e0,SpaDependencies:J2,SparseMatrix:Zt,SparseMatrixDependencies:tr,SymbolNode:cn,SymbolNodeDependencies:jn,Unit:qe,UnitDependencies:Ve,_Infinity:RN,_NaN:$N,_false:PN,_null:qN,_true:jN,abs:Cr,absDependencies:Lr,acos:QN,acosDependencies:oI,acosh:TC,acoshDependencies:uI,acot:KN,acotDependencies:lI,acoth:VC,acothDependencies:cI,acsc:eC,acscDependencies:hI,acsch:FC,acschDependencies:fI,add:ht,addDependencies:ft,addScalar:Jt,addScalarDependencies:rr,all:cq,and:PD,andDependencies:dI,andTransformDependencies:pI,apply:aI,arg:tC,argDependencies:mI,asec:_C,asecDependencies:gI,asech:rC,asechDependencies:vI,asin:WC,asinDependencies:yI,asinh:iC,asinhDependencies:bI,atan:_v,atan2:nD,atan2Dependencies:xI,atanDependencies:d2,atanh:nC,atanhDependencies:wI,atomicMass:HD,atomicMassDependencies:SI,avogadro:NA,avogadroDependencies:NI,bellNumbers:LA,bellNumbersDependencies:CI,bigint:sC,bigintDependencies:DI,bignumber:zr,bignumberDependencies:Yr,bin:jC,binDependencies:AI,bitAnd:sD,bitAndDependencies:EI,bitAndTransformDependencies:MI,bitNot:aC,bitNotDependencies:TI,bitOr:aD,bitOrDependencies:FI,bitOrTransformDependencies:_I,bitXor:oD,bitXorDependencies:OI,bohrMagneton:UD,bohrMagnetonDependencies:BI,bohrRadius:CA,bohrRadiusDependencies:kI,boltzmann:VD,boltzmannDependencies:PI,boolean:oC,booleanDependencies:zI,catalan:bD,catalanDependencies:RI,cbrt:Iv,cbrtDependencies:w2,ceil:Lm,ceilDependencies:w0,chain:n2,chainDependencies:LI,classicalElectronRadius:GA,classicalElectronRadiusDependencies:II,clone:uC,cloneDependencies:$I,column:Yv,columnDependencies:C2,columnTransformDependencies:qI,combinations:Ao,combinationsDependencies:Jm,combinationsWithRep:OC,combinationsWithRepDependencies:HI,compare:$n,compareDependencies:Ds,compareNatural:Bi,compareNaturalDependencies:Ji,compareText:$v,compareTextDependencies:D2,compile:s2,compileDependencies:UI,complex:Eo,complexDependencies:Qm,composition:xD,compositionDependencies:VI,concat:dt,concatDependencies:mt,concatTransformDependencies:WI,conductanceQuantum:WD,conductanceQuantumDependencies:jI,config:pe,conj:Pn,conjDependencies:Ss,corr:XA,corrDependencies:GI,cos:Dm,cosDependencies:D0,cosh:BC,coshDependencies:XI,cot:lC,cotDependencies:YI,coth:GC,cothDependencies:JI,coulomb:jD,coulombConstant:DA,coulombConstantDependencies:QI,coulombDependencies:ZI,count:uD,countDependencies:KI,create:uE,createAbs:cl,createAccessorNode:nf,createAcos:ph,createAcosh:mh,createAcot:gh,createAcoth:vh,createAcsc:yh,createAcsch:bh,createAdd:Yh,createAddScalar:fl,createAnd:fo,createAndTransform:bm,createArg:Il,createArrayNode:af,createAsec:xh,createAsech:wh,createAsin:Sh,createAsinh:Nh,createAssignmentNode:lf,createAtan:Ch,createAtan2:Dh,createAtanh:Ah,createAtomicMass:_p,createAvogadro:Op,createBellNumbers:Sd,createBigNumberClass:wu,createBigint:Zu,createBignumber:el,createBin:gc,createBitAnd:Ja,createBitAndTransform:Sm,createBitNot:Rl,createBitOr:Za,createBitOrTransform:Nm,createBitXor:Ll,createBlockNode:hf,createBohrMagneton:hp,createBohrRadius:vp,createBoltzmann:Bp,createBoolean:Ku,createCatalan:Nd,createCbrt:pl,createCeil:ml,createChain:jf,createChainClass:Vf,createClassicalElectronRadius:yp,createClone:Bu,createColumn:to,createColumnTransform:em,createCombinations:ld,createCombinationsWithRep:cd,createCompare:Ic,createCompareNatural:qc,createCompareText:Hc,createCompile:kf,createComplex:tl,createComplexClass:Su,createComposition:Cd,createConcat:eo,createConcatTransform:hm,createConditionalNode:df,createConductanceQuantum:fp,createConj:$l,createConstantNode:mf,createCorr:ud,createCos:Eh,createCosh:Mh,createCot:Th,createCoth:Fh,createCoulomb:up,createCoulombConstant:lp,createCount:Wl,createCreateUnit:dh,createCross:jl,createCsc:_h,createCsch:Oh,createCtranspose:ac,createCube:gl,createCumSum:xo,createCumSumTransform:gm,createDeepEqual:eh,createDenseMatrixClass:Ou,createDerivative:Od,createDet:Gf,createDeuteronMass:Cp,createDiag:Gl,createDiff:so,createDiffTransform:fm,createDistance:id,createDivide:rd,createDivideScalar:Nc,createDot:Qh,createDotDivide:Fc,createDotMultiply:Pl,createDotPow:Tc,createE:Wd,createEfimovFactor:Fp,createEigs:Jf,createElectricConstant:ap,createElectronMass:bp,createElementaryCharge:cp,createEqual:Vc,createEqualScalar:Xu,createEqualText:Wc,createErf:hc,createEvaluate:Pf,createExp:vl,createExpm:Zf,createExpm1:yl,createFactorial:dd,createFalse:Id,createFaraday:kp,createFermiCoupling:xp,createFft:uc,createFibonacciHeapClass:oh,createFilter:ro,createFilterTransform:tm,createFineStructure:wp,createFirstRadiation:Pp,createFix:bl,createFlatten:Xl,createFloor:Ga,createForEach:io,createForEachTransform:rm,createFormat:mc,createFraction:rl,createFractionClass:Nu,createFreqz:Pd,createFunctionAssignmentNode:vf,createFunctionNode:Of,createGamma:hd,createGasConstant:Rp,createGcd:wl,createGetMatrixDataType:Yl,createGravitationConstant:rp,createGravity:jp,createHartreeEnergy:Sp,createHasNumericValue:Hu,createHelp:Wf,createHelpClass:Uf,createHex:yc,createHypot:Jh,createI:Kd,createIdentity:Jl,createIfft:lc,createIm:ql,createImmutableDenseMatrixClass:sh,createIndex:ef,createIndexClass:ah,createIndexNode:bf,createIndexTransform:im,createInfinity:qd,createIntersect:nd,createInv:Xf,createInverseConductanceQuantum:dp,createInvmod:kl,createIsInteger:zu,createIsNaN:Wu,createIsNegative:$u,createIsNumeric:qu,createIsPositive:Uu,createIsPrime:wc,createIsZero:Vu,createKldivergence:pd,createKlitzing:gp,createKron:Zl,createLN10:Xd,createLN2:Gd,createLOG10E:Jd,createLOG2E:Yd,createLarger:Zc,createLargerEq:Kc,createLcm:Nl,createLeafCount:Dd,createLeftShift:Pc,createLgamma:fd,createLog:Ac,createLog10:Cl,createLog1p:Ec,createLog2:Dl,createLoschmidt:zp,createLsolve:_c,createLsolveAll:Bc,createLup:Lf,createLusolve:qf,createLyap:td,createMad:od,createMagneticConstant:sp,createMagneticFluxQuantum:pp,createMap:no,createMapSlices:la,createMapSlicesTransform:Kp,createMapTransform:nm,createMatrix:il,createMatrixClass:Du,createMatrixFromColumns:al,createMatrixFromFunction:nl,createMatrixFromRows:sl,createMax:po,createMaxTransform:sm,createMean:wo,createMeanTransform:am,createMedian:ad,createMin:mo,createMinTransform:om,createMod:Xa,createMode:dc,createMolarMass:Vp,createMolarMassC12:Wp,createMolarPlanckConstant:Lp,createMolarVolume:Ip,createMultinomial:md,createMultiply:El,createMultiplyScalar:Al,createNaN:Hd,createNeutronMass:Dp,createNode:tf,createNorm:Zh,createNot:Ul,createNthRoot:Ml,createNthRoots:Mc,createNuclearMagneton:mp,createNull:$d,createNullish:Qa,createNullishTransform:wm,createNumber:Ju,createNumeric:Sc,createObjectNode:wf,createOct:vc,createOnes:Ql,createOperatorNode:Nf,createOr:Ka,createOrTransform:xm,createParenthesisNode:Df,createParse:Bf,createParser:Rf,createParserClass:zf,createPartitionSelect:ih,createPermutations:gd,createPhi:jd,createPi:Ud,createPickRandom:yd,createPinv:Yf,createPlanckCharge:Jp,createPlanckConstant:ip,createPlanckLength:Gp,createPlanckMass:Xp,createPlanckTemperature:Zp,createPlanckTime:Yp,createPolynomialRoot:Hf,createPow:Cc,createPrint:co,createPrintTransform:ym,createProd:pc,createProtonMass:Np,createQr:If,createQuantileSeq:No,createQuantileSeqTransform:mm,createQuantumOfCirculation:Ap,createRandom:bd,createRandomInt:xd,createRange:ao,createRangeClass:Cu,createRangeNode:Ef,createRangeTransform:um,createRationalize:Bd,createRe:Hl,createReducedPlanckConstant:np,createRelationalNode:Tf,createReplacer:Rd,createReshape:Kl,createResize:ec,createResolve:Fd,createResultSet:fu,createReviver:zd,createRightArithShift:zc,createRightLogShift:Rc,createRotate:tc,createRotationMatrix:rc,createRound:Dc,createRow:oo,createRowTransform:lm,createRydberg:Ep,createSQRT1_2:Zd,createSQRT2:Qd,createSackurTetrode:$p,createSchur:ed,createSec:Bh,createSech:kh,createSecondRadiation:qp,createSetCartesian:Ih,createSetDifference:$h,createSetDistinct:qh,createSetIntersect:Hh,createSetIsSubset:Uh,createSetMultiplicity:Vh,createSetPowerset:Wh,createSetSize:jh,createSetSymDifference:Gh,createSetUnion:Xh,createSign:Tl,createSimplify:Ed,createSimplifyConstant:Md,createSimplifyCore:Td,createSin:Ph,createSinh:zh,createSize:ic,createSlu:$f,createSmaller:Gc,createSmallerEq:Yc,createSolveODE:cc,createSort:nh,createSpaClass:uh,createSparse:fh,createSparseMatrixClass:Yu,createSpeedOfLight:tp,createSplitUnit:ol,createSqrt:Fl,createSqrtm:Qf,createSquare:_l,createSqueeze:nc,createStd:Co,createStdTransform:dm,createStefanBoltzmann:Hp,createStirlingS2:wd,createString:Qu,createSubset:uo,createSubsetTransform:cm,createSubtract:Ol,createSubtractScalar:dl,createSum:bo,createSumTransform:pm,createSylvester:Kf,createSymbolNode:Ff,createSymbolicEqual:_d,createTan:Rh,createTanh:Lh,createTau:Vd,createThomsonCrossSection:Mp,createTo:bc,createToBest:xc,createTrace:Kh,createTranspose:sc,createTrue:Ld,createTypeOf:ju,createTyped:uu,createUnaryMinus:ul,createUnaryPlus:ll,createUnequal:rh,createUnit:GD,createUnitClass:ch,createUnitDependencies:e$,createUnitFunction:hh,createUppercaseE:Nv,createUppercasePi:Sv,createUsolve:Oc,createUsolveAll:kc,createVacuumImpedance:op,createVariance:So,createVarianceTransform:vm,createVersion:ep,createWeakMixingAngle:Tp,createWienDisplacement:Up,createXgcd:Bl,createXor:Vl,createZeros:oc,createZeta:fc,createZpk2tf:kd,cross:zD,crossDependencies:t$,csc:cC,cscDependencies:r$,csch:kC,cschDependencies:i$,ctranspose:_m,ctransposeDependencies:A0,cube:hC,cubeDependencies:n$,cumsum:IA,cumsumDependencies:s$,cumsumTransformDependencies:a$,deepEqual:ya,deepEqualDependencies:Io,derivative:c2,derivativeDependencies:o$,det:Jv,detDependencies:g2,deuteronMass:XD,deuteronMassDependencies:u$,diag:Rv,diagDependencies:k2,diff:wD,diffDependencies:l$,diffTransformDependencies:c$,distance:SD,distanceDependencies:h$,divide:cr,divideDependencies:yr,divideScalar:Rt,divideScalarDependencies:$t,docs:OS,dot:Oo,dotDependencies:Ym,dotDivide:ba,dotDivideDependencies:$o,dotMultiply:XC,dotMultiplyDependencies:f$,dotPow:YD,dotPowDependencies:d$,e:Av,eDependencies:P2,efimovFactor:XN,efimovFactorDependencies:p$,eigs:s0,eigsDependencies:I2,electricConstant:JD,electricConstantDependencies:m$,electronMass:AA,electronMassDependencies:g$,elementaryCharge:ZD,elementaryChargeDependencies:v$,equal:Rr,equalDependencies:Jr,equalScalar:nt,equalScalarDependencies:ot,equalText:lD,equalTextDependencies:y$,erf:fC,erfDependencies:b$,evaluate:jm,evaluateDependencies:P0,exp:Ov,expDependencies:$2,expm:QD,expm1:dC,expm1Dependencies:w$,expmDependencies:x$,factorial:xa,factorialDependencies:Ro,factory:R,falseDependencies:S$,faraday:KD,faradayDependencies:N$,fermiCoupling:$A,fermiCouplingDependencies:C$,fft:t0,fftDependencies:U2,filter:pC,filterDependencies:D$,filterTransformDependencies:A$,fineStructure:zN,fineStructureDependencies:E$,firstRadiation:EA,firstRadiationDependencies:M$,fix:Zv,fixDependencies:m2,flatten:zn,flattenDependencies:Es,floor:qv,floorDependencies:p2,forEach:mC,forEachDependencies:T$,forEachTransformDependencies:F$,format:ma,formatDependencies:zo,fraction:va,fractionDependencies:Po,freqz:YA,freqzDependencies:_$,gamma:$m,gammaDependencies:S0,gasConstant:qA,gasConstantDependencies:O$,gcd:cD,gcdDependencies:B$,getMatrixDataType:Am,getMatrixDataTypeDependencies:N0,gravitationConstant:eA,gravitationConstantDependencies:k$,gravity:MA,gravityDependencies:P$,hartreeEnergy:tA,hartreeEnergyDependencies:z$,hasNumericValue:hD,hasNumericValueDependencies:R$,help:h2,helpDependencies:L$,hex:gC,hexDependencies:I$,hypot:fD,hypotDependencies:$$,i:Ev,iDependencies:q2,identity:un,identityDependencies:Un,ifft:rA,ifftDependencies:q$,im:Em,imDependencies:F0,index:jv,indexDependencies:j2,indexTransformDependencies:H$,intersect:TA,intersectDependencies:V$,inv:qn,invDependencies:Ns,inverseConductanceQuantum:iA,inverseConductanceQuantumDependencies:W$,invmod:ND,invmodDependencies:j$,isAccessorNode:en,isArray:St,isArrayNode:Vr,isAssignmentNode:vg,isBigInt:ts,isBigNumber:Xe,isBlockNode:yg,isBoolean:hg,isChain:au,isCollection:Or,isComplex:ci,isConditionalNode:bg,isConstantNode:ct,isDate:dg,isDenseMatrix:Vs,isFraction:vn,isFunction:su,isFunctionAssignmentNode:rs,isFunctionNode:qi,isHelp:nu,isIndex:Ws,isIndexNode:xn,isInteger:Pr,isIntegerDependencies:Xr,isMap:bn,isMatrix:Re,isNaN:Gi,isNaNDependencies:pn,isNegative:on,isNegativeDependencies:Vn,isNode:bt,isNull:mg,isNumber:Je,isNumeric:In,isNumericDependencies:ws,isObject:yn,isObjectNode:js,isObjectWrappingMap:Cy,isOperatorNode:qt,isParenthesisNode:Ai,isPartitionedMap:Ny,isPositive:Rn,isPositiveDependencies:Cs,isPrime:PC,isPrimeDependencies:G$,isRange:Ia,isRangeNode:wg,isRegExp:pg,isRelationalNode:Sg,isResultSet:fg,isSparseMatrix:Ki,isString:nr,isSymbolNode:Xt,isUndefined:gg,isUnit:br,isZero:ti,isZeroDependencies:wi,kldivergence:HA,kldivergenceDependencies:X$,klitzing:nA,klitzingDependencies:Y$,kron:YC,kronDependencies:J$,larger:Ar,largerDependencies:Ir,largerEq:Fo,largerEqDependencies:Zm,lcm:CD,lcmDependencies:t6,leafCount:o2,leafCountDependencies:r6,leftShift:JC,leftShiftDependencies:i6,lgamma:yC,lgammaDependencies:n6,log:Om,log10:bC,log10Dependencies:s6,log1p:DD,log1pDependencies:a6,log2:Mm,log2Dependencies:z0,logDependencies:L0,loschmidt:sA,loschmidtDependencies:o6,lsolve:Uv,lsolveAll:AD,lsolveAllDependencies:u6,lsolveDependencies:Y2,lup:r0,lupDependencies:Z2,lusolve:a0,lusolveDependencies:K2,lyap:t2,lyapDependencies:l6,mad:JA,madDependencies:c6,magneticConstant:aA,magneticConstantDependencies:h6,magneticFluxQuantum:FA,magneticFluxQuantumDependencies:f6,map:Ln,mapDependencies:Ms,mapSlices:fs,mapSlicesDependencies:qo,mapSlicesTransformDependencies:d6,mapTransformDependencies:p6,matrix:we,matrixDependencies:Ne,matrixFromColumns:Bm,matrixFromColumnsDependencies:_0,matrixFromFunction:zC,matrixFromFunctionDependencies:m6,matrixFromRows:ED,matrixFromRowsDependencies:g6,max:km,maxDependencies:$0,maxTransformDependencies:v6,mean:o0,meanDependencies:F2,meanTransformDependencies:y6,median:u0,medianDependencies:rE,min:dD,minDependencies:b6,minTransformDependencies:x6,mod:Vv,modDependencies:G2,mode:ZC,modeDependencies:w6,molarMass:oA,molarMassC12:_A,molarMassC12Dependencies:N6,molarMassDependencies:S6,molarPlanckConstant:uA,molarPlanckConstantDependencies:C6,molarVolume:UA,molarVolumeDependencies:D6,multinomial:OA,multinomialDependencies:A6,multiply:xt,multiplyDependencies:Nt,multiplyScalar:Ht,multiplyScalarDependencies:jt,neutronMass:lA,neutronMassDependencies:M6,norm:Hm,normDependencies:I0,not:Mo,notDependencies:Xm,nthRoot:QC,nthRootDependencies:T6,nthRoots:pD,nthRootsDependencies:F6,nuclearMagneton:cA,nuclearMagnetonDependencies:_6,nullDependencies:O6,nullish:mD,nullishDependencies:B6,nullishTransformDependencies:k6,number:ji,numberDependencies:fn,numeric:ii,numericDependencies:xi,oct:xC,octDependencies:P6,ones:RC,onesDependencies:z6,or:gD,orDependencies:R6,orTransformDependencies:L6,parse:bi,parseDependencies:Pi,parser:u2,parserDependencies:I6,partitionSelect:_o,partitionSelectDependencies:tg,permutations:BA,permutationsDependencies:$6,phi:HN,phiDependencies:q6,pi:Cm,piDependencies:q0,pickRandom:wC,pickRandomDependencies:H6,pinv:RD,pinvDependencies:U6,planckCharge:hA,planckChargeDependencies:V6,planckConstant:VA,planckConstantDependencies:W6,planckLength:fA,planckLengthDependencies:j6,planckMass:kA,planckMassDependencies:G6,planckTemperature:dA,planckTemperatureDependencies:X6,planckTime:KA,planckTimeDependencies:Y6,polynomialRoot:PA,polynomialRootDependencies:J6,pow:yi,powDependencies:ki,print:SC,printDependencies:Z6,printTransformDependencies:Q6,prod:Lv,prodDependencies:_2,protonMass:pA,protonMassDependencies:K6,qr:Pm,qrDependencies:O0,quantileSeq:WA,quantileSeqDependencies:e7,quantileSeqTransformDependencies:t7,quantumOfCirculation:mA,quantumOfCirculationDependencies:r7,random:NC,randomDependencies:i7,randomInt:LC,randomIntDependencies:n7,range:ms,rangeDependencies:Aa,rangeTransformDependencies:a7,rationalize:l2,rationalizeDependencies:o7,re:Tm,reDependencies:B0,reducedPlanckConstant:gA,reducedPlanckConstantDependencies:u7,replacer:Fv,replacerDependencies:O2,reshape:Pv,reshapeDependencies:R2,resize:KC,resizeDependencies:l7,resolve:y0,resolveDependencies:B2,reviver:i2,reviverDependencies:c7,rightArithShift:eD,rightArithShiftDependencies:h7,rightLogShift:vD,rightLogShiftDependencies:f7,rotate:e2,rotateDependencies:d7,rotationMatrix:l0,rotationMatrixDependencies:nE,round:ds,roundDependencies:Ca,row:MD,rowDependencies:p7,rowTransformDependencies:m7,rydberg:vA,rydbergDependencies:g7,sackurTetrode:WN,sackurTetrodeDependencies:b7,schur:c0,schurDependencies:eE,sec:CC,secDependencies:x7,sech:IC,sechDependencies:w7,secondRadiation:yA,secondRadiationDependencies:S7,setCartesian:TD,setCartesianDependencies:N7,setDifference:Qv,setDifferenceDependencies:sE,setDistinct:FD,setDistinctDependencies:C7,setIntersect:i0,setIntersectDependencies:aE,setIsSubset:_D,setIsSubsetDependencies:D7,setMultiplicity:LD,setMultiplicityDependencies:A7,setPowerset:OD,setPowersetDependencies:E7,setSize:bA,setSizeDependencies:M7,setSymDifference:Kv,setSymDifferenceDependencies:oE,setUnion:jA,setUnionDependencies:T7,sign:Bv,signDependencies:z2,simplify:ko,simplifyConstant:Vm,simplifyConstantDependencies:M0,simplifyCore:Wm,simplifyCoreDependencies:T0,simplifyDependencies:Km,sin:To,sinDependencies:eg,sinh:$C,sinhDependencies:F7,size:Qt,sizeDependencies:ir,slu:Gv,sluDependencies:Q2,smaller:Dr,smallerDependencies:$r,smallerEq:ps,smallerEqDependencies:Da,solveODE:zA,solveODEDependencies:_7,sort:BD,sortDependencies:O7,sparse:qC,sparseDependencies:B7,speedOfLight:xA,speedOfLightDependencies:k7,splitUnit:DC,splitUnitDependencies:P7,sqrt:vi,sqrtDependencies:zi,sqrtm:ID,sqrtmDependencies:z7,square:AC,squareDependencies:R7,squeeze:HC,squeezeDependencies:L7,std:ZA,stdDependencies:I7,stdTransformDependencies:$7,stefanBoltzmann:wA,stefanBoltzmannDependencies:q7,stirlingS2:n0,stirlingS2Dependencies:y2,string:EC,stringDependencies:H7,subset:Gr,subsetDependencies:ni,subsetTransformDependencies:U7,subtract:Wt,subtractDependencies:Gt,subtractScalar:ri,subtractScalarDependencies:Si,sum:Im,sumDependencies:C0,sumTransformDependencies:V7,sylvester:h0,sylvesterDependencies:tE,symbolicEqual:a2,symbolicEqualDependencies:W7,tan:MC,tanDependencies:j7,tanh:UC,tanhDependencies:G7,tau:Tv,tauDependencies:H2,thomsonCrossSection:SA,thomsonCrossSectionDependencies:X7,to:tD,toBest:kv,toBestDependencies:v2,toDependencies:Y7,trace:yD,traceDependencies:J7,transpose:ga,transposeDependencies:Lo,trueDependencies:Z7,typeOf:Fm,typeOfDependencies:R0,typed:j,typedDependencies:G,unaryMinus:Oi,unaryMinusDependencies:Yi,unaryPlus:Rm,unaryPlusDependencies:E0,unequal:rD,unequalDependencies:Q7,unit:RA,unitDependencies:K7,usolve:zm,usolveAll:Xv,usolveAllDependencies:L2,usolveDependencies:k0,vacuumImpedance:$D,vacuumImpedanceDependencies:rq,variance:qm,varianceDependencies:H0,varianceTransformDependencies:iq,version:GN,versionDependencies:nq,weakMixingAngle:ZN,weakMixingAngleDependencies:sq,wienDisplacement:qD,wienDisplacementDependencies:aq,xgcd:zv,xgcdDependencies:X2,xor:iD,xorDependencies:oq,zeros:lr,zerosDependencies:vr,zeta:QA,zetaDependencies:uq,zpk2tf:kD,zpk2tfDependencies:lq},Symbol.toStringTag,{value:"Module"}));var Fe={lightGray:"#EEEEEE",mediumGray:"#DDDDDD",darkGray:"#AAAAAA",hiliteColor:"#FF69B4",stepColor:"#9FDAFF",explainColor:"#FFD9B3",red:"#DB2323",green:"#6FDE29",blue:"#2386DB",white:"#FFFFFF"};class Ri{constructor(){this.name="",this.xpos=0,this.scale=1,this.rotation=0,this.ypos=0,this.width=0,this.height=0,this.opacity=1,this.visible=!0,this.svgObject=null,this.childList=[],this.parent=null}setName(e){this.name=e}setPosition(e,t){this.xpos=e,this.ypos=t,this.updateTransform()}setScale(e){this.scale=e,this.updateTransform()}setRotation(e){this.rotation=e,this.updateTransform()}updateTransform(){const e=isNaN(this.xpos)?0:this.xpos,t=isNaN(this.ypos)?0:this.ypos;var r=" translate("+e.toString()+","+t.toString()+") ";this.scale!=1&&(r+=" scale("+this.scale.toString()+")"),this.rotation!=0&&(r+=" rotate("+this.rotation+")"),this.svgObject.setAttribute("transform",r)}setWidth(e){this.width=e,this.svgObject.setAttribute("width",this.width.toString())}setHeight(e){this.height=e,this.svgObject.setAttribute("height",this.height.toString())}setWidthAndHeight(e,t){this.setWidth(e),this.setHeight(t)}setFillColor(e){this.svgObject.setAttribute("fill",e)}setStrokeColor(e){this.svgObject.setAttribute("stroke",e)}setStrokeWidth(e){this.svgObject.setAttribute("stroke-width",e.toString())}setOpacity(e){this.opacity=e,this.svgObject.style.opacity=e}setDropShadow(){this.svgObject.style.filter="drop-shadow(0px 3px 6px rgba(0, 0, 0, 0.4))"}show(){this.visible=!0,this.svgObject.style.display=""}hide(){this.visible=!1,this.svgObject.style.display="none"}update(){if(this.visible)for(var e of this.childList)e.update()}addChild(e){this.svgObject&&e.svgObject&&(this.childList.push(e),this.svgObject.appendChild(e.svgObject),e.parent=this)}getChild(e){return this.childList[e]}replaceChild(e,t){this.svgObject.replaceChild(e.svgObject,t.svgObject);for(var r=0;r<this.childList.length;r++)if(this.childList[r]==t){this.childList[r]=e;break}t.parent=null,e.parent=this}getNumberOfChildren(){return this.childList.length}removeChild(e){const t=this.childList.indexOf(e);this.removeChildByIndex(t),e.parent=null}removeChildByIndex(e){if(e>=0){var t=this.childList[e];this.childList.splice(e,1),this.svgObject.removeChild(t.svgObject),t.parent=null}}removeAllChildren(){for(;this.svgObject.firstChild;)this.svgObject.removeChild(this.svgObject.lastChild);this.childList=[]}sortChildren(e){this.childList.sort(e),this.childList.forEach(t=>this.svgObject.appendChild(t.svgObject))}setClickCallback(e){if(this.svgObject){var t=this;this.svgObject.onclick=function(){e(t)},this.svgObject.style.cursor="pointer"}}enableDragging(){this.svgObject.style.cursor="pointer";var e=this;this.svgObject.onmousedown=function(t){e.lastX=t.clientX,e.lastY=t.clientY,window.onmousemove=function(r){var i=r.clientX-e.lastX,s=r.clientY-e.lastY;e.lastX=r.clientX,e.lastY=r.clientY,e.setPosition(e.xpos+i,e.ypos+s)},window.onmouseup=function(){window.onmousemove=null}}}}class j0 extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"svg"),this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("width","500"),this.svgObject.setAttribute("height","500"),this.svgObject.setAttribute("backgroundColor","blue")}setViewbox(e,t){this.setWidth(e),this.setHeight(t);var r="0 0 "+e.toString()+" "+t.toString();this.svgObject.setAttribute("viewBox",r)}}let Oe=class extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"g"),this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("width","500"),this.svgObject.setAttribute("height","500"),this.svgObject.setAttribute("viewBox","0 0 500 500")}},Ut=class extends Ri{constructor(){super(),this.x1=0,this.y1=0,this.x2=100,this.y2=100;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"line"),this.svgObject.setAttribute("x1","0"),this.svgObject.setAttribute("y1","0"),this.svgObject.setAttribute("x2","100"),this.svgObject.setAttribute("y2","100"),this.setStrokeColor("black"),this.setStrokeWidth(1),this.setEndpointA(this.x1,this.y1),this.setEndpointB(this.x2,this.y2)}setEndpointA(e,t){this.x1=e,this.y1=t,this.svgObject.setAttribute("x1",e.toString()),this.svgObject.setAttribute("y1",t.toString())}setEndpointB(e,t){this.x2=e,this.y2=t,this.svgObject.setAttribute("x2",e.toString()),this.svgObject.setAttribute("y2",t.toString())}setEndpoints(e,t,r,i){this.setEndpointA(e,t),this.setEndpointB(r,i)}};class yt extends Ri{constructor(){super(),this.cornerRadius=0;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"rect"),this.setWidthAndHeight(100,100),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}setCornerRadius(e){this.cornerRadius=e,this.svgObject.setAttribute("rx",e.toString()),this.svgObject.setAttribute("ry",e.toString())}}let Tr=class extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"ellipse"),this.setPosition(0,0),this.setWidthAndHeight(100,100),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}setWidth(e){this.width=e,this.svgObject.setAttribute("rx",(this.width/2).toString())}setHeight(e){this.height=e,this.svgObject.setAttribute("ry",(this.height/2).toString())}setPosition(e,t){this.xpos=e,this.ypos=t,this.svgObject.setAttribute("cx",e.toString()),this.svgObject.setAttribute("cy",t.toString()),this.svgObject.setAttribute("transform","")}updateTransform(){var e="";this.scale!=1&&(e+=" scale("+this.scale.toString()+")"),this.rotation!=0&&(e+=" rotate("+this.rotation+")"),this.svgObject.setAttribute("transform",e.trim())}};class lE extends Ri{constructor(){super();const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"path"),this.setFillColor("white"),this.setStrokeColor("black"),this.setStrokeWidth(0)}createPieSlice(e,t,r){function i(u,c){const h=(c-90)*Math.PI/180;return{x:u*Math.cos(h),y:u*Math.sin(h)}}const s=i(e,r),a=i(e,t),o=r-t<=180?"0":"1",l=["M 0 0",`L ${s.x} ${s.y}`,`A ${e} ${e} 0 ${o} 0 ${a.x} ${a.y}`,"Z"].join(" ");this.svgObject.setAttribute("d",l)}}class Ni extends Ri{constructor(){super(),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.setAttribute("fill","none"),this.path.setAttribute("stroke","black"),this.path.setAttribute("stroke-width","2"),this.svgObject=this.path,this.points=[],this.updatePath()}addPoint(e,t){if(typeof e!="number"||typeof t!="number")throw new Error("Coordinates must be numbers.");this.points.push({x:e,y:t})}updatePath(){if(this.points.length===0){this.path.setAttribute("d","");return}const t=this.points.map((r,i)=>i===0?`M ${r.x},${r.y}`:`L ${r.x},${r.y}`).join(" ");this.path.setAttribute("d",t)}clearPoints(){this.points=[],this.updatePath()}}class Ho extends Ri{constructor(e=300,t=300,r=10){super();const i="http://www.w3.org/2000/svg",s=document.createElementNS(i,"g");this.svgObject=s,this.width=e,this.height=t,this.cornerRadius=r,this.maskID="clipMaskID"+Math.random(),s.setAttribute("width",this.width),s.setAttribute("height",this.height),s.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);const a=document.createElementNS(i,"clipPath");a.setAttribute("id",this.maskID),this.clipRect=document.createElementNS(i,"rect"),this.clipRect.setAttribute("x",0),this.clipRect.setAttribute("y",0),this.clipRect.setAttribute("width",this.width),this.clipRect.setAttribute("height",this.height),this.clipRect.setAttribute("rx",this.cornerRadius),this.clipRect.setAttribute("ry",this.cornerRadius),a.appendChild(this.clipRect),s.appendChild(a),this.clipGroup=new Oe,this.clipGroup.svgObject.setAttribute("clip-path",`url(#${this.maskID})`),super.addChild(this.clipGroup)}setWidth(e){this.width=e,this.svgObject.setAttribute("width",this.width),this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.clipRect.setAttribute("width",this.width)}setHeight(e){this.height=e,this.svgObject.setAttribute("height",this.height),this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.clipRect.setAttribute("height",this.height)}setCornerRadius(e){this.cornerRadius=e,this.clipRect.setAttribute("rx",this.cornerRadius),this.clipRect.setAttribute("ry",this.cornerRadius)}addChild(e){this.clipGroup.addChild(e)}}class cE extends Ri{constructor(){super(),this.preserveAspectRatio=!0;const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"image"),this.setWidthAndHeight(100,100)}setImageURL(e){this.svgObject.setAttribute("href",e),this.imageURL=e}setAspectRatio(e){this.svgObject.setAttribute("preserveAspectRatio",e)}applyRoundedCorners(e,t=0){this.svgObject&&this.svgObject.remove();const r="http://www.w3.org/2000/svg",i=document.createElementNS(r,"g");this.svgObject=i,i.setAttribute("width",this.width),i.setAttribute("height",this.height),i.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);const s=document.createElementNS(r,"clipPath");s.setAttribute("id","rounded-corners");const a=document.createElementNS(r,"rect");a.setAttribute("x",0),a.setAttribute("y",0),a.setAttribute("width",this.width),a.setAttribute("height",this.height),a.setAttribute("rx",e),a.setAttribute("ry",e),s.appendChild(a),i.appendChild(s);const o=document.createElementNS(r,"image");o.setAttribute("href",this.imageURL),o.setAttribute("width",this.width),o.setAttribute("height",this.height),o.setAttribute("clip-path","url(#rounded-corners)"),t&&o.setAttribute("preserveAspectRatio",t),i.appendChild(o)}}let si=class extends Ri{constructor(){super(),this.text="";const e="http://www.w3.org/2000/svg";this.svgObject=document.createElementNS(e,"text"),this.svgObject.textContent="hello world",this.svgObject.setAttribute("x","0"),this.svgObject.setAttribute("y","0"),this.svgObject.setAttribute("fill","black"),this.svgObject.style.fontFamily="Arial, Helvetica, sans-serif;"}setText(e){this.text=e,this.svgObject.textContent=e}getText(){return this.text}setFontSize(e){this.svgObject.style.fontSize=e.toString()+"px"}setFontFamily(e){this.svgObject.style.fontFamily=e}setFontColor(e){this.svgObject.style.fill=e}setTextAnchor(e){this.svgObject.setAttribute("text-anchor",e)}setAlignment(e){this.alignment=e,e=="left"&&this.setTextAnchor("start"),e=="center"&&this.setTextAnchor("middle"),e=="right"&&this.setTextAnchor("end")}setFontWeight(e){this.svgObject.style.fontWeight=e.toString()}},Bt=class extends Oe{constructor(e={}){super(),this.text="",this._useForeignObject=e.useForeignObject===!0,this._textAlign="left",this._verticalCenter=!1,this._lineHeight=null,this._fontSize=16,this._fontFamily="Arial, Helvetica, sans-serif",this._fontWeight="normal",this._fontColor="black";const t="http://www.w3.org/2000/svg";this._useForeignObject?(this.foreignObject=document.createElementNS(t,"foreignObject"),this.foreignObject.style.backgroundColor="none",this.svgObject.appendChild(this.foreignObject),this.div=document.createElement("div"),this.foreignObject.appendChild(this.div)):(this.textElement=document.createElementNS(t,"text"),this.textElement.setAttribute("x","0"),this.textElement.setAttribute("y","0"),this.textElement.setAttribute("fill",this._fontColor),this.textElement.setAttribute("xml:space","preserve"),this.textElement.style.fontFamily=this._fontFamily,this.textElement.style.fontSize=this._fontSize.toString()+"px",this.svgObject.appendChild(this.textElement)),this.setWidthAndHeight(200,100)}_getLineHeight(){return this._lineHeight||this._fontSize}_getTextX(){return this._textAlign==="center"?this.width/2:this._textAlign==="right"||this._textAlign==="end"?this.width:0}_applyTextAnchor(){this.textElement&&(this._textAlign==="center"?this.textElement.setAttribute("text-anchor","middle"):this._textAlign==="right"||this._textAlign==="end"?this.textElement.setAttribute("text-anchor","end"):this.textElement.setAttribute("text-anchor","start"))}_parseHtmlToLines(e){if(!/<\s*(sup|sub|br)\b/i.test(e||""))return[[{text:e||"",mode:null}]];const r=document.createElement("div");r.innerHTML=e||"";const i=[[]],s=(a,o)=>{if(a.nodeType===3){const c=a.nodeValue||"";c.length>0&&i[i.length-1].push({text:c,mode:o});return}if(a.nodeType!==1)return;const l=a.tagName.toLowerCase();if(l==="br"){i.push([]);return}let u=o;l==="sup"&&(u="sup"),l==="sub"&&(u="sub");for(let c=0;c<a.childNodes.length;c++)s(a.childNodes[c],u)};for(let a=0;a<r.childNodes.length;a++)s(r.childNodes[a],null);return i.length>1&&i[i.length-1].length===0&&i.pop(),i}_renderSvgText(e){if(!this.textElement)return;const t="http://www.w3.org/2000/svg",r=this._parseHtmlToLines(e),i=this._getLineHeight(),s=i*r.length,a=this._verticalCenter?Math.max(0,(this.height-s)/2):0,o=this._getTextX();for(;this.textElement.firstChild;)this.textElement.removeChild(this.textElement.firstChild);this._applyTextAnchor(),this.textElement.setAttribute("dominant-baseline","hanging");for(let l=0;l<r.length;l++){const u=r[l];u.length===0&&u.push({text:"",mode:null});for(let c=0;c<u.length;c++){const h=u[c],f=document.createElementNS(t,"tspan");f.textContent=h.text,h.mode==="sup"?(f.setAttribute("baseline-shift","super"),f.setAttribute("font-size","0.7em")):h.mode==="sub"&&(f.setAttribute("baseline-shift","sub"),f.setAttribute("font-size","0.7em")),c===0&&(f.setAttribute("x",o),l===0?f.setAttribute("y",a):f.setAttribute("dy",i)),this.textElement.appendChild(f)}}}_updateSvgLayout(){this.textElement&&this._renderSvgText(this.text)}setText(e){this.text=e||"",this._useForeignObject?this.div.innerHTML=this.text:this._renderSvgText(this.text)}getText(){return this.text}setStyle(e){this._useForeignObject?(this.div.className=e,this.div.style.position="fixed"):this.textElement&&this.textElement.setAttribute("class",e)}setFontFamily(e){this._fontFamily=e,this._useForeignObject?this.div.style.fontFamily=e:this.textElement&&(this.textElement.style.fontFamily=e)}setFontSize(e){this._fontSize=e,this._useForeignObject?this.div.style.fontSize=e.toString()+"px":this.textElement&&(this.textElement.style.fontSize=e.toString()+"px",this._updateSvgLayout())}setLineHeight(e){this._lineHeight=e,this._useForeignObject?this.div.style.lineHeight=e+"px":this._updateSvgLayout()}setFontWeight(e){this._fontWeight=e,this._useForeignObject?this.div.style.fontWeight=e:this.textElement&&(this.textElement.style.fontWeight=e)}setFontColor(e){this._fontColor=e,this._useForeignObject?this.div.style.color=e:this.textElement&&this.textElement.setAttribute("fill",e)}setAlignment(e){this._textAlign=e,this._useForeignObject?this.div.style.textAlign=e:this._updateSvgLayout()}setVerticalCentering(){this._useForeignObject?(this.div.style.display="flex",this.div.style.flexFlow="column",this.div.style.justifyContent="center",this.div.style.alignItems="center"):(this._verticalCenter=!0,this._updateSvgLayout())}makeEditable(){this._useForeignObject&&(this.div.style.contentEditable="true",this.div.onclick=function(){console.log("here"),this.focus()})}setBorderWidthAndColor(e,t){this._useForeignObject&&(this.div.style.border=e+"px solid "+t)}setWidth(e){this.width=e,this._useForeignObject?(this.div&&(this.div.style.width=e+"px"),this.foreignObject&&this.foreignObject.setAttribute("width",e)):this._updateSvgLayout()}setHeight(e){this.height=e,this._useForeignObject?(this.div&&(this.div.style.height=e+"px"),this.foreignObject&&this.foreignObject.setAttribute("height",e)):this._updateSvgLayout()}};class hE extends Bt{constructor(){super({useForeignObject:!0}),this.callback=null,this.foreignObject.removeChild(this.div),this.div=document.createElement("input"),this.div.contentEditable=!0,this.div.onkeyup=this.handleInput.bind(this),this.foreignObject.appendChild(this.div),this.setWidthAndHeight(200,30),this.setPlaceholderText("placeholder")}setStyle(e){this.div.className=e}setPlaceholderText(e){this.div.placeholder=e}setText(e){this.div.value=e}getText(){return this.div.value}setInputCallback(e){this.callback=e}handleInput(e){(e.key=="Enter"||e.keyCode==13)&&this.callback&&this.callback(this.div.value)}}let fE=class extends Bt{constructor(){super({useForeignObject:!0}),this.callback=null,this.foreignObject.removeChild(this.div),this.div=document.createElement("textarea"),this.div.onkeyup=this.handleInput.bind(this),this.foreignObject.appendChild(this.div),this.setWidthAndHeight(200,30),this.setPlaceholderText("placeholder")}setText(e){this.div.value=e}getText(){return this.div.value}setStyle(e){this.div.className=e}handleInput(e){this.callback&&this.callback(this)}setPlaceholderText(e){this.div.placeholder=e}setInputCallback(e){this.callback=e}},Xn=class extends Oe{constructor(){super(),this.callback=null,this.fontSize=12,this.text="button",this.backRect=new yt,this.backRect.setWidthAndHeight(100,30),this.backRect.setFillColor("white"),this.backRect.setStrokeWidth(0),this.backRect.setCornerRadius(15),this.backRect.svgObject.style.cursor="pointer",this.addChild(this.backRect),this.buttonText=new si,this.buttonText.setPosition(50,20),this.buttonText.setFontFamily("Arial"),this.buttonText.setFontSize(12),this.buttonText.setText("button"),this.buttonText.setTextAnchor("middle"),this.buttonText.svgObject.style.cursor="pointer",this.addChild(this.buttonText)}setText(e){this.text=e,this.buttonText.setText(e)}setFontFamily(e){this.buttonText.setFontFamily(e)}setFontSize(e){this.fontSize=e,this.buttonText.setFontSize(e)}setFontColor(e){this.buttonText.setFontColor(e)}setFillColor(e){this.backRect.setFillColor(e)}setStrokeColor(e){this.backRect.setStrokeColor(e)}setStrokeWidth(e){this.backRect.setStrokeWidth(e)}setCornerRadius(e){this.backRect.setCornerRadius(e)}addImage(e,t=30,r=30){this.image=new cE,this.image.setImageURL(e),this.image.setWidthAndHeight(t,r),this.image.setPosition(this.backRect.width/2-t/2,this.backRect.height/2-r/2),this.image.svgObject.style.cursor="pointer",this.addChild(this.image)}setWidthAndHeight(e,t){this.width=e,this.height=t,this.backRect.setWidthAndHeight(e,t),this.buttonText.setPosition(e/2,t*.5+2+this.fontSize*.25),this.image&&this.image.setPosition(this.backRect.width/2-this.image.width/2,this.backRect.height/2-this.image.height/2)}};class qr extends Oe{constructor(){super(),this.spacer=10}setSpacer(e){this.spacer=e}updateLayout(){}showAll(){for(var e=this.getNumberOfChildren(),t=0;t<e;t++){var r=this.getChild(t);r.show()}}showOnly(e){for(var t=this.getNumberOfChildren(),r=0;r<t;r++){var i=this.getChild(r);r==e?i.show():i.hide()}}doVerticalLayout(){for(var e=this.getNumberOfChildren(),t=0,r=0,i=0,s=0;s<e;s++){var a=this.getChild(s);a.visible&&(a.setPosition(t,r),r+=a.height,r+=this.spacer,a.width>i&&(i=a.width))}this.height=r-this.spacer,this.width=i;for(var s=0;s<e;s++){var a=this.getChild(s),t=this.width/2-a.width/2;a.setPosition(t,a.ypos)}}doHorizontalLayout(){for(var e=this.getNumberOfChildren(),t=0,r=0,i=0,s=0;s<e;s++){var a=this.getChild(s);a.visible&&(a.setPosition(t,r),t+=a.width,t+=this.spacer,a.height>i&&(i=a.height))}this.width=t-this.spacer,this.height=i;for(var s=0;s<e;s++){var a=this.getChild(s),r=this.height/2-a.height/2;a.setPosition(a.xpos,r)}}}class mq extends Oe{constructor(){super(),this.scrollPercent=0,this.scrollOffset=0,this.contentHeight=0,this.oldMouseX=0,this.oldMouseY=0,this.clipMask=new Ho(200,400,10),super.addChild(this.clipMask),this.backRect=new yt,this.backRect.setFillColor("white"),this.clipMask.addChild(this.backRect),this.scrollGroup=new Oe,this.clipMask.addChild(this.scrollGroup),this.scrollBar=new yt,this.scrollBar.setWidthAndHeight(10,50),this.scrollBar.setCornerRadius(5),this.scrollBar.setFillColor("darkgray"),this.scrollBar.setPosition(180,10),this.scrollBar.svgObject.onmousedown=this.handleMouseDown.bind(this),this.scrollBar.svgObject.style.cursor="pointer",this.clipMask.addChild(this.scrollBar),this.setWidthAndHeight(200,500),this.updateLayout()}setWidth(e){super.setWidth(e),this.clipMask.setWidth(e),this.backRect.setWidth(e)}setHeight(e){super.setWidth(e),this.clipMask.setHeight(e),this.backRect.setHeight(e)}setCornerRadius(e){this.clipMask.setCornerRadius(e)}addChild(e){this.scrollGroup.addChild(e)}handleMouseDown(e){if(!this.visible)return;function t(i){i.preventDefault();var s,a;if(i.touches&&i.touches.length>=1?(s=i.touches[0].clientX,a=i.touches[0].clientY):(s=i.clientX,a=i.clientY),this.oldMouseX&&this.oldMouseY){s-this.oldMouseX;var o=a-this.oldMouseY,l=this.scrollBar.ypos+o,u=10,c=this.backRect.height-this.scrollBar.height-10;l<u&&(l=u),l>c&&(l=c),this.scrollBar.setPosition(this.scrollBar.xpos,l),this.scrollPercent=(l-u)/(c-u),this.updateLayout()}this.oldMouseX=s,this.oldMouseY=a}function r(i){this.activeBubble=null,window.onmousemove=null,window.ontouchmove=null,window.onmouseup=null,window.ontouchend=null,this.oldMouseX=0,this.oldMouseY=0}window.onmousemove=t.bind(this),window.ontouchmove=t.bind(this),window.onmouseup=r.bind(this),window.ontouchend=r.bind(this)}computeContentBounds(){for(var e=0,t=this.scrollGroup.getNumberOfChildren(),r=0;r<t;r++){var i=this.scrollGroup.getChild(r),s=i.ypos+i.height;s>e&&(e=s)}this.contentHeight=e}updateLayout(){if(this.backRect.width,this.backRect.height,this.computeContentBounds(),this.contentHeight>this.backRect.height){var e=this.contentHeight-this.backRect.height,t=-1*this.scrollPercent*e;this.scrollGroup.setPosition(0,t)}}}class kt extends Oe{constructor(e=1){super(),this.type="",this.value=e,this.defaultOpaqueBack=!0,this.backRect=new yt,this.backRect.setWidthAndHeight(30,30),this.backRect.setCornerRadius(5),this.backRect.setFillColor(this.getBackgroundColor()),this.addChild(this.backRect),this.svgObject.onmouseenter=this.highlightProvenance.bind(this),this.svgObject.onmouseleave=this.clearProvenance.bind(this),this.svgObject.style.cursor="pointer"}setWidthAndHeight(e,t){super.setWidthAndHeight(e,t),this.backRect.setWidthAndHeight(e,t)}setFontSize(e){this.fontSize=e,this.childList&&this.childList.forEach(t=>{t&&typeof t.setFontSize=="function"&&t.setFontSize(e)})}getFontSize(){return this.fontSize?this.fontSize:this.parent&&typeof this.parent.getFontSize=="function"?this.parent.getFontSize():16}getRootFontSize(){return this.parent&&this.parent instanceof kt?this.parent.getRootFontSize():this.fontSize||16}getBackgroundColor(){var e;return((e=this._backgroundStyle)==null?void 0:e.backgroundColor)??Fe.lightGray}highlightProvenance(e,t=Fe.hiliteColor,r=-1/0){e.stopPropagation();const i=this.getRootNode();if(!i||!i.nodeMap)return;i.clearProvenanceHighlights(),this.highlight(t);let s=[...this.provenance];const a=new Set(s);for(;s.length>0;){const o=s.shift(),l=i.nodeMap.get(o);l&&(l.highlight(t),l.provenance&&l.provenance.forEach(u=>{a.has(u)||(a.add(u),s.push(u))}))}}clearProvenance(e){e.stopPropagation();const t=this.getRootNode();t&&t.clearProvenanceHighlights()}highlight(e){this.backRect.setFillColor(e),this.backRect.setOpacity(1),this.childList.forEach(t=>{t instanceof kt&&t.highlight(e)})}clearProvenanceHighlights(){var e;this.isExplainHighlighted?(this.backRect.setFillColor(Fe.explainColor),this.backRect.setOpacity(1)):this.isProvenanceHighlighted?(this.backRect.setFillColor(Fe.explainColor),this.backRect.setOpacity(1)):(this.backRect.setFillColor(((e=this._backgroundStyle)==null?void 0:e.backgroundColor)??Fe.lightGray),this.defaultOpaqueBack||this.backRect.setOpacity(.01)),this.childList.forEach(t=>{t instanceof kt&&typeof t.clearProvenanceHighlights=="function"&&t.clearProvenanceHighlights()})}setExplainHighlight(e=!0,t=Fe.explainColor){this.isExplainHighlighted=e,e?(this.backRect.setFillColor(t),this.backRect.setOpacity(1)):(this.backRect.setFillColor(this.getBackgroundColor()),this.defaultOpaqueBack||this.backRect.setOpacity(.01)),this.argumentNodeList&&Object.values(this.argumentNodeList).forEach(r=>{r&&typeof r.setExplainHighlight=="function"&&r.setExplainHighlight(e,t)})}getRootNode(){let e=this;for(;e.parent&&e.parent instanceof kt;)e=e.parent;return e}findAllNodes(e=[]){return e.push(this),this.childList&&this.childList.forEach(t=>{t.findAllNodes&&t.findAllNodes(e)}),e}select(e){e!==this&&(e instanceof kt||(e=this),this.backRect.setFillColor(Fe.hiliteColor),this.backRect.setOpacity(1),this.childList.forEach(t=>{t instanceof kt&&t.select(e)}),this===e&&this.parent instanceof kt&&e.parent.deselect(e))}deselect(e){e instanceof kt||(e=this),this===e&&this.parent instanceof kt&&e.parent.select(e),!(e===this&&this.parent instanceof kt)&&(this.backRect.setFillColor(this.getBackgroundColor()),this.defaultOpaqueBack==!1&&this.backRect.setOpacity(.01),this.childList.forEach(t=>{t!==e&&t instanceof kt&&t.deselect(e)}))}hideBackgroundByDefault(){this.defaultOpaqueBack=!1,this.backRect.setOpacity(.01)}makeBackgroundLight(){this.backRect.setFillColor(this.getBackgroundColor())}makeBackgroundDark(){this.backRect.setFillColor(Fe.mediumGray)}}let G0=null;function gq(n){G0=n}const ug=class ug extends kt{constructor(e){super(),this.astNodeData=e,this.type="omdNode",this.id=ug.nextId++,this.argumentNodeList={},this.provenance=e&&e.provenance?[...e.provenance]:[],this.isExplainHighlighted=!1,this.parent=null,this.svgElement=null,this.x=0,this.y=0,this.width=0,this.height=0,this.fontSize=32}clone(){const e=JSON.parse(JSON.stringify(this.astNodeData)),t=new this.constructor(e);return t.provenance.push(this.id),t}_syncProvenanceFrom(e){var t;if(e&&(this.provenance.includes(e.id)||this.provenance.push(e.id),e.argumentNodeList&&this.argumentNodeList))for(const r of Object.keys(e.argumentNodeList)){const i=e.argumentNodeList[r],s=this.argumentNodeList[r];if(i&&s)if(Array.isArray(i)&&Array.isArray(s))for(let a=0;a<i.length;a++)(t=s[a])==null||t._syncProvenanceFrom(i[a]);else s._syncProvenanceFrom(i)}}parseValue(){}parseType(){}initialize(){this.computeDimensions(),this.updateLayout()}computeDimensions(){}updateLayout(){}getAlignmentBaseline(){return this.height/2}replaceWith(e,t={updateLayout:!0}){if(!this.parent)return console.error("Cannot replace a node with no parent."),!1;const r=this.parent,i=r.childList.indexOf(this),s=()=>{r.childList[i]=this,e.parent=null,this.parent=r};return i===-1?(console.error("Node not found in parent's childList.",this),!1):(r.childList[i]=e,e.parent=r,this.parent=null,this.replaceNodeInParent(e)?(t.updateLayout&&(this.updateSvg(e),e.updateLayoutUpwards()),!0):(s(),console.error("Failed to replace specific references. Reverting changes."),!1))}replaceNodeInParent(e){const t=e.parent;if(!t||!t.argumentNodeList)return!1;for(const r in t.argumentNodeList){const i=t.argumentNodeList[r];if(i===this)return t.argumentNodeList[r]=e,Object.prototype.hasOwnProperty.call(t,r)&&(t[r]=e),!0;if(Array.isArray(i)&&i.includes(this)){const s=i.indexOf(this);return i[s]=e,t[r]===i&&(t[r][s]=e),!0}}return!1}updateSvg(e){const t=e.parent;if(t&&t.svgObject&&this.svgObject&&e.svgObject)try{t.svgObject.replaceChild(e.svgObject,this.svgObject)}catch(r){console.error("SVG replacement failed, attempting fallback.",r);try{t.svgObject.removeChild(this.svgObject),t.svgObject.appendChild(e.svgObject)}catch(i){console.error("SVG fallback replacement also failed:",i)}}}updateLayoutUpwards(){const e=[];let t=this.parent;for(;t;)e.push(t),t=t.parent;for(const r of e)typeof r.computeDimensions=="function"&&r.computeDimensions();for(let r=e.length-1;r>=0;r--)typeof e[r].updateLayout=="function"&&e[r].updateLayout()}isConstant(){return!1}getValue(){throw new Error("Node is not a constant expression")}getRationalValue(){throw new Error("Node is not a constant rational expression")}simplify(){if(!G0)throw new Error("simplifyStep not set");try{const{foldedCount:e,newRoot:t}=G0(this);return e>0?{success:!0,foldedCount:e,newRoot:t,message:`Simplified! Applied ${e} simplification step(s)`}:{success:!1,foldedCount:0,newRoot:null,message:"No simplifications available"}}catch(e){return{success:!1,foldedCount:0,newRoot:null,message:`Simplification error: ${e.message}`}}}toMathJSNode(){throw new Error(`toMathJSNode() must be implemented by ${this.type}`)}toString(){try{return this.toMathJSNode().toString()}catch{return`[${this.type}]`}}render(){return this.svgElement||(this.svgElement=this.renderSelf()),this.svgElement}renderSelf(){throw new Error(`renderSelf() must be implemented by ${this.type}`)}setFontSize(e){this.fontSize=e,this.childList&&this.childList.forEach(t=>{t&&typeof t.setFontSize=="function"&&t.setFontSize(e)})}moveTo(e,t){const r=e-this.x,i=t-this.y;this.x=e,this.y=t,this.svgElement&&this.svgElement.setAttribute("transform",`translate(${this.x}, ${this.y})`),this.childList&&this.childList.forEach(s=>{s&&typeof s.moveTo=="function"&&s.moveTo(s.x+r,s.y+i)})}show(){this.visible=!0,this.svgElement&&(this.svgElement.style.display="block"),this.svgObject&&(this.svgObject.style.display="block")}hide(){this.visible=!1,this.svgElement&&(this.svgElement.style.display="none"),this.svgObject&&(this.svgObject.style.display="none")}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}findParentOfType(e){let t=this.parent;for(;t;){if(t.type===e||t.type===e)return t;t=t.parent}return null}static fromAST(e){throw new Error("Use omdHelpers.createNodeFromAST() instead")}validateProvenance(e=null){const t=[],r=this.findAllNodes(),i=e?new Set(e.keys()):new Set(r.map(s=>s.id));return r.forEach(s=>{s.provenance&&s.provenance.length>0&&(new Set(s.provenance).size!==s.provenance.length&&t.push({type:"duplicate_provenance",nodeId:s.id,nodeType:s.type,provenance:s.provenance}),s.provenance.forEach(o=>{i.has(o)||t.push({type:"invalid_provenance_reference",nodeId:s.id,nodeType:s.type,invalidId:o})}),s.provenance.includes(s.id)&&t.push({type:"self_reference_provenance",nodeId:s.id,nodeType:s.type}))}),t}setHighlight(e=!0,t=omdColor.highlightColor){this.backRect&&this.backRect.fillColor===omdColor.explainColor||this.isExplainHighlighted||this.backRect&&(this.backRect.setFillColor(e?t:omdColor.lightGray),this.backRect.setOpacity(1))}lowlight(){this.backRect&&this.backRect.fillColor===omdColor.explainColor||this.isExplainHighlighted||super.lowlight()}setFillColor(e){this.isExplainHighlighted}};eu(ug,"nextId",1);let Pt=ug;class Uo extends Pt{constructor(e){super(e),this.type="omdLeafNode"}createTextElement(e){let t=new si;return t.setText(e),t.setTextAnchor("middle"),t.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(t),t}clone(){const e=new this.constructor(this.astNodeData);return e.provenance.push(this.id),e}updateTextElement(e){this.textElement.setText(e)}computeDimensions(){let e=this.getFontSize();this.textElement.setFontSize(e);let t=Jn(this.textElement.getText(),e);this.setWidthAndHeight(t.width,t.height)}updateLayout(){this.updateTextPosition()}updateTextPosition(){this.textElement.setPosition(this.width/2,this.height/2)}}let hr=null,rg=null;const Li={multiplication:{symbol:"·",forceImplicit:!1,implicitCombinations:{constantVariable:!0,variableConstant:!1,parenthesisAfterVariable:!0,parenthesisAfterConstant:!0,variableParenthesis:!0,parenthesisParenthesis:!0,parenthesisVariable:!0,parenthesisConstant:!0,variableVariable:!0}},stepVisualizer:{dotSizes:{level0:8,level1:8,level2:8},fontWeights:{level0:400,level1:400,level2:400}}};async function vq(n=null){return rg&&!n?rg:n&&typeof n=="object"?(hr={...Li,...n},hr):(rg=(async()=>{try{if(typeof window<"u"){const e=n||"./omd/config/omdConfig.json",t=await fetch(e);if(!t.ok)return console.warn(`Config file not found at ${e}, using default configuration`),hr=Li,hr;const r=await t.text(),i=JSON.parse(r);return hr={...Li,...i},hr}else{if(!(typeof process<"u"&&!!(process.versions&&process.versions.node)))return console.warn("Config loading skipped: filesystem APIs unavailable in this environment. Using default configuration."),hr=Li,hr;try{const t=await Promise.resolve().then(()=>vd),r=await Promise.resolve().then(()=>vd),{fileURLToPath:i}=await Promise.resolve().then(()=>vd),s=r.dirname(i(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Lt&&Lt.tagName.toUpperCase()==="SCRIPT"&&Lt.src||new URL("omd.global.js",document.baseURI).href)),a=n||r.join(s,"omdConfig.json");try{const o=await t.readFile(a,"utf-8"),l=JSON.parse(o);hr={...Li,...l}}catch{console.warn(`Config file not found at ${a}, using default configuration`),hr=Li}}catch(t){console.warn("Config loading skipped: unable to access Node filesystem APIs. Using default configuration.",t),hr=Li}return hr}}catch(e){return console.warn("Error loading config, using default configuration:",e),hr=Li,hr}})(),rg)}function ig(){return hr||(hr=Li),hr}async function yq(n=null){await vq(n)}function bq(n){hr={...Li,...n}}function xq(){return{...Li}}function dE(n=null){const e=ig();return n?e.multiplication.implicitCombinations[n]??!1:e.multiplication.forceImplicit}function ai(){return ig().multiplication.symbol}function Ta(n=0){var r,i;const e=ig(),t=`level${n}`;return((i=(r=e.stepVisualizer)==null?void 0:r.dotSizes)==null?void 0:i[t])??6}function wq(n=0){var r,i;const e=ig(),t=`level${n}`;return((i=(r=e.stepVisualizer)==null?void 0:r.fontWeights)==null?void 0:i[t])??400}class ng extends Uo{constructor(e){super(e),this.type="omdOperatorNode",this.opName=this.parseOpName(e);const t=this.opName==="*"?ai():this.opName;this.textElement=super.createTextElement(t)}parseOpName(e){if(typeof e=="string")return e;const t={multiply:ai(),divide:"÷",add:"+",subtract:"−",pow:"^",unaryMinus:"-",unaryPlus:"+"},r=e.op||e.fn;return t[r]||r}parseType(){return"operator"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"OperatorNode",op:this.opName,fn:this.opName,args:[]};return e.clone=function(){const t={...this};return t.argumentNodeList.argument=t.argument,t},e}toString(){return this.opName}highlight(e){super.highlight(e),this.opLabel&&this.opLabel.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.opLabel&&this.opLabel.setFillColor(Fe.text)}}class Zr extends Uo{constructor(e){super(e),this.type="omdConstantNode",this.number=this.parseNumber(e),this.textElement=super.createTextElement(this.number)}parseNumber(e){return typeof e=="number"?e:e.value}parseType(){return"constant"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}isConstant(){return typeof this.number=="number"}getValue(){return this.number}toString(){return this.number.toString()}evaluate(){return this.number}getRationalValue(){return{num:this.getValue(),den:1}}toMathJSNode(){const e={type:"ConstantNode",value:this.number,id:this.id,provenance:this.provenance};return e.clone=function(){return{...this}},e}highlight(e){super.highlight(e),this.textElement&&this.textElement.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.textElement&&this.textElement.setFillColor(Fe.text)}static fromValue(e){const t={type:"ConstantNode",value:e};return new Zr(t)}}class Zi extends Uo{constructor(e){super(e),this.type="omdVariableNode",this.name=this.parseName(e),this.textElement=super.createTextElement(this.name)}parseName(e){return typeof e=="string"?e:e.name}parseType(){return"variable"}computeDimensions(){super.computeDimensions();const t=4*(this.getFontSize()/this.getRootFontSize());let r=this.width+t,i=this.height+t;this.setWidthAndHeight(r,i)}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"SymbolNode",name:this.name,id:this.id,provenance:this.provenance};return e.clone=function(){return{...this}},e}highlight(e){super.highlight(e),this.textElement&&this.textElement.setFillColor(Fe.white)}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.textElement&&this.textElement.setFillColor(Fe.text)}toString(){return this.name}evaluate(e={}){if(Object.prototype.hasOwnProperty.call(e,this.name))return e[this.name];throw new Error(`Variable '${this.name}' is not defined.`)}static fromName(e){const t={type:"SymbolNode",name:e};return new Zi(t)}}function pE(n,e){return e===0?n:pE(e,n%e)}class Hr extends Pt{constructor(e){if(super(e),this.type="omdRationalNode",!e.args||e.args.length<2){console.error("omdRationalNode requires numerator and denominator");return}this.value=this.parseValue(),this.numerator=this.createOperand(e.args[0]),this.denominator=this.createOperand(e.args[1]),this.argumentNodeList.numerator=this.numerator,this.argumentNodeList.denominator=this.denominator,this.fractionLine=new Ut,this.fractionLine.setStrokeColor("black"),this.fractionLine.setStrokeWidth(2),this.addChild(this.fractionLine)}parseValue(){return"/"}createOperand(e){let t=_t(e),r=new t(e);this.addChild(r);try{e.id&&e.provenance&&e.provenance.length>0&&(!r.provenance||r.provenance.length===0)&&(r.provenance=[...e.provenance])}catch(i){console.debug("Failed to preserve lineage in createOperand:",i.message)}return r}computeDimensions(){this.numerator.setFontSize(this.getFontSize()*5/6),this.denominator.setFontSize(this.getFontSize()*5/6),this.numerator.computeDimensions(),this.denominator.computeDimensions();const e=this.getFontSize()/this.getRootFontSize(),t=8*e,r=8*e;let i=Math.max(this.numerator.width,this.denominator.width)+t,s=this.numerator.height+this.denominator.height+r;this.setWidthAndHeight(i,s)}updateLayout(){const t=(this.width-this.numerator.width)/2;this.numerator.updateLayout(),this.numerator.setPosition(t,2);const r=this.numerator.height+2*2;this.fractionLine.setEndpoints(0,r,this.width,r);const i=(this.width-this.denominator.width)/2,s=r+2;this.denominator.updateLayout(),this.denominator.setPosition(i,s)}getAlignmentBaseline(){return this.numerator.height+2*2}isConstant(){return this.numerator.isConstant()&&this.denominator.isConstant()}getRationalValue(){if(this.isConstant())return{num:this.numerator.getValue(),den:this.denominator.getValue()};throw new Error("Rational node is not constant")}getValue(){if(this.isConstant()){const{num:e,den:t}=this.getRationalValue();return t===0?NaN:e/t}throw new Error("Node is not a constant expression")}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Hr(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.numerator=this.numerator.clone(),t.denominator=this.denominator.clone(),t.fractionLine=new Ut,t.fractionLine.setStrokeColor("black"),t.fractionLine.setStrokeWidth(2),t.addChild(t.numerator),t.addChild(t.fractionLine),t.addChild(t.denominator),t.argumentNodeList.numerator=t.numerator,t.argumentNodeList.denominator=t.denominator,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"OperatorNode",op:"/",fn:"divide",args:[this.numerator.toMathJSNode(),this.denominator.toMathJSNode()],id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.numerator.toString(),t=this.denominator.toString(),r=this.numerator.type==="omdBinaryExpressionNode",i=this.denominator.type==="omdBinaryExpressionNode",s=r?`(${e})`:e,a=i?`(${t})`:t;return`${s} / ${a}`}evaluate(e={}){const t=this.numerator.evaluate(e),r=this.denominator.evaluate(e);if(r===0)throw new Error("Division by zero in rational expression.");return t/r}reduce(){if(this.isConstant()){let{num:e,den:t}=this.getRationalValue();t<0&&(e=-e,t=-t);const r=pE(Math.abs(e),Math.abs(t)),i=e/r,s=t/r;if(i===this.numerator.getValue()&&s===this.denominator.getValue())return this;if(s===1)return Zr.fromNumber(i);const a={type:"OperatorNode",op:"/",fn:"divide",args:[Zr.fromNumber(i).toMathJSNode(),Zr.fromNumber(s).toMathJSNode()]};return new Hr(a)}return this.clone()}isProper(){if(this.isConstant()){const{num:e,den:t}=this.getRationalValue();return Math.abs(e)<Math.abs(t)}return null}static fromString(e){try{const t=window.math.parse(e);if(t.type!=="OperatorNode"||t.op!=="/")throw new Error("Expression is not a division operation");return new Hr(t)}catch(t){throw console.error("Failed to create rational node from string:",t),t}}}class Qi extends Pt{constructor(e){if(super(e),this.type="omdUnaryExpressionNode",!e.args||e.args.length!==1){console.error("omdUnaryExpressionNode requires an AST node with exactly 1 argument",e);return}this.op=this.createOperatorNode(e),this.operand=this.createExpressionNode(e.args[0]),this.operation=e.fn||e.op,this.operand=this.operand,this.argument=this.operand,this.argumentNodeList.operand=this.operand,this.argumentNodeList.argument=this.argument,this.addChild(this.op),this.addChild(this.operand)}createOperatorNode(e){const t=new ng({op:e.op,fn:e.fn});return t.parent=this,t}createExpressionNode(e){const t=_t(e),r=new t(e);return r.parent=this,r}computeDimensions(){this.op.computeDimensions(),this.operand.computeDimensions();const e=this.op.width,t=this.operand.width,r=e+t,i=Math.max(this.op.height,this.operand.height);this.setWidthAndHeight(r,i)}updateLayout(){this.op.updateLayout(),this.operand.updateLayout();const e=(this.height-this.op.height)/2,t=(this.height-this.operand.height)/2;this.op.setPosition(0,e),this.operand.setPosition(this.op.width,t)}clone(){const e={type:"OperatorNode",op:"-",args:[{type:"ConstantNode",value:1}]},t=new Qi(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.op=this.op.clone(),t.addChild(t.op),t.operand=this.operand.clone(),t.addChild(t.operand),t.argument=t.operand,t.argumentNodeList={operand:t.operand,argument:t.argument},t.astNodeData=JSON.parse(JSON.stringify(this.astNodeData)),t.provenance.push(this.id),t}isConstant(){return!!(this.operand&&typeof this.operand.isConstant=="function"&&this.operand.isConstant())}getValue(){if(!this.isConstant())throw new Error("Node is not a constant expression");const e=this.operand.getValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?-e:e}getRationalValue(){if(!this.isConstant())throw new Error("Node is not a constant expression");if(typeof this.operand.getRationalValue=="function"){const{num:t,den:r}=this.operand.getRationalValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?{num:-t,den:r}:{num:t,den:r}}const e=this.operand.getValue();return this.operation==="unaryMinus"||this.op&&this.op.opName==="-"?{num:-e,den:1}:{num:e,den:1}}toMathJSNode(){const e={type:"OperatorNode",op:this.op.opName,fn:this.operation,args:[this.operand.toMathJSNode()],id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.operand.toString();return this.needsParentheses()?`${this.op.opName}(${e})`:`${this.op.opName}${e}`}needsParentheses(){return this.operand.type==="omdBinaryExpressionNode"}evaluate(e={}){if(!this.operand.evaluate)return NaN;const t=this.operand.evaluate(e);return this.op.opName==="-"?-t:t}static fromString(e){try{const t=window.math.parse(e);if(t.type==="OperatorNode"&&t.fn==="unaryMinus")return new Qi(t);throw new Error("Expression is not a unary minus operation.")}catch(t){throw console.error("Failed to create unary expression node from string:",t),t}}}function Ur(n,...e){if(!n)return n;n.provenance=n.provenance||[];for(const t of e)t&&(t.id&&!n.provenance.includes(t.id)&&n.provenance.push(t.id),t.provenance&&Array.isArray(t.provenance)&&t.provenance.forEach(r=>{r&&!n.provenance.includes(r)&&n.provenance.push(r)}),X0(t,n.provenance));return n}function X0(n,e){if(!n||!e)return;const t=["left","right","base","exponent","argument","expression","numerator","denominator","content"];for(const r of t){const i=n[r];i&&i.id&&!e.includes(i.id)&&(e.push(i.id),X0(i,e))}n.args&&Array.isArray(n.args)&&n.args.forEach(r=>{r&&r.id&&!e.includes(r.id)&&(e.push(r.id),X0(r,e))})}function Yn(n,e){for(n=Math.abs(n),e=Math.abs(e);e;)[n,e]=[e,n%e];return n}function Y0(n,e){const t={type:"ConstantNode",value:n,clone:function(){return{...this}}},r=new Zr(t);return r.setFontSize(e),r.initialize(),r}function Sq(n,e,t){if(n===t)return{success:!0,newRoot:e};const r=n.replaceWith(e,{updateLayout:!0});if(r){e.astNodeData=e.toMathJSNode();let i=e.parent;for(;i&&i instanceof Pt;){i.astNodeData=i.toMathJSNode();i=i.parent}}return{success:r,newRoot:t}}function Nq(n){const e=[];function t(r){if(r){if(r.type==="omdConstantNode"||r.type==="omdVariableNode"){e.push(r);return}r.left&&t(r.left),r.right&&t(r.right),r.base&&t(r.base),r.exponent&&t(r.exponent),r.argument&&t(r.argument),r.expression&&t(r.expression),r.numerator&&t(r.numerator),r.denominator&&t(r.denominator)}}return t(n),e}function oi(n,e){const t=n.operation;if(n.type==="omdBinaryExpressionNode"&&(t==="add"||t==="+"))oi(n.left,e),oi(n.right,e);else if(n.type==="omdBinaryExpressionNode"&&(t==="subtract"||t==="-")){oi(n.left,e);const r=[];oi(n.right,r),r.forEach(i=>{i.sign*=-1}),e.push(...r)}else{const r=Nq(n);e.push({node:n,sign:1,leafNodes:r})}}function Ts(n,e){if(n.length===0)return Y0(0,e);if(n.sort((i,s)=>s.sign-i.sign),n.length>1&&n[0].sign===-1)if(n[0].node.type==="omdConstantNode"){const i=n.shift();i.sign=1,n.push(i)}else n.unshift({node:Y0(0,e),sign:1});let r=n.shift().node;if(!r||typeof r.updateLayoutUpwards!="function"){const i=r.id;r=r.clone(),r.provenance=r.provenance||[],i&&!r.provenance.includes(i)&&r.provenance.push(i),r.setFontSize(e),r.initialize()}if(n.length===0)return r;for(;n.length>0;){const i=n.shift(),s=i.sign===1?"+":"-",a=i.sign===1?"add":"subtract";let o=i.node;if(!o||typeof o.updateLayoutUpwards!="function"){const f=o.id;o=o.clone(),o.provenance=o.provenance||[],f&&!o.provenance.includes(f)&&o.provenance.push(f),o.setFontSize(e),o.initialize()}i.expansionProvenance&&(o.expansionProvenance=o.expansionProvenance||[],o.expansionProvenance.push(i.expansionProvenance),[i.expansionProvenance.leftSource,i.expansionProvenance.rightSource,i.expansionProvenance.originalMultiplication].forEach(f=>{f&&!o.provenance.includes(f)&&o.provenance.push(f)}));const l={type:"OperatorNode",op:s,fn:a,args:[r.toMathJSNode(),o.toMathJSNode()],clone:function(){return{...this,args:this.args.map(f=>f.clone())}}},u=new Ci(l);u.setFontSize(e),u.initialize();const c=r.provenance||[],h=o.provenance||[];[...c,...h,r.id,o.id].forEach(f=>{f&&!u.provenance.includes(f)&&u.provenance.push(f)}),(o.expansionProvenance||r.expansionProvenance)&&(u.expansionProvenance=u.expansionProvenance||[],o.expansionProvenance&&u.expansionProvenance.push(...o.expansionProvenance),r.expansionProvenance&&u.expansionProvenance.push(...r.expansionProvenance)),r=u}return r}function pt(n){if(!n)return"";const e={add:"+",subtract:"-",multiply:ai(),divide:"÷",unaryMinus:"-",unaryPlus:"+",pow:"^"};if(typeof n.getValue=="function"&&n.isConstant&&n.isConstant())return n.getValue().toString();if(n.name)return n.name;if(n.type==="omdBinaryExpressionNode"){const t=pt(n.left),r=pt(n.right);let i;return n.op&&n.op.opName?i=e[n.op.opName]||n.op.opName:n.operation?i=e[n.operation]||n.operation:i="",i?`${t} ${i} ${r}`:`${t}${r}`}if(n.type==="omdUnaryExpressionNode"){const t=pt(n.argument);let r;return n.op&&n.op.opName?r=e[n.op.opName]||n.op.opName:n.operation?r=e[n.operation]||n.operation:r="-",t.includes(" ")||t.includes("+")||t.includes("-")||t.includes(ai())||t.includes("÷")?`${r}(${t})`:`${r}${t}`}if(n.type==="omdRationalNode"){const t=pt(n.numerator),r=pt(n.denominator);return`(${t}/${r})`}if(n.type==="omdParenthesisNode"){const t=pt(n.content||n.expression);return t.startsWith("(")&&t.endsWith(")")?t:`(${t})`}if(n.type==="omdPowerNode"){const t=pt(n.base),r=pt(n.exponent);return`${t}^${r}`}if(n.type==="omdSqrtNode")return`√(${pt(n.argument)})`;if(n.type==="omdFunctionNode"){const t=n.functionName||n.name||"f";if(n.argNodes&&n.argNodes.length>0){const r=n.argNodes.map(i=>pt(i)).join(", ");return`${t}(${r})`}else if(n.args&&n.args.length>0){const r=n.args.map(i=>pt(i)).join(", ");return`${t}(${r})`}return`${t}()`}if(n.type==="omdEquationNode"){const t=pt(n.left),r=pt(n.right);return`${t} = ${r}`}if(typeof n.toString=="function")try{return n.toString()}catch{}if(n.toMathJSNode)try{return math.parse(n.toMathJSNode()).toString()}catch{}return n.name||n.type||"[unknown]"}function Cq(n,e,t){if(e===1)return n;if(e===2)return mE(n,t);if(e===3)return gE(n,t);if(e===4)return Dq(n,t);let r=n;for(let i=1;i<e;i++)r=J0(r,n,t);return r}function mE(n,e){const t=[];for(const r of n){const i=ie.createBinaryOp(r.node.clone(),"multiply",r.node.clone(),e);(r.leafNodes||[]).forEach(a=>{[i.left,i.right,i].forEach(o=>{o&&!o.provenance.includes(a.id)&&o.provenance.push(a.id)})}),t.push({node:i,sign:r.sign*r.sign})}for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){const s=n[r],a=n[i],o=ie.createConstant(2,e),l=ie.createBinaryOp(o,"multiply",s.node.clone(),e),u=ie.createBinaryOp(l,"multiply",a.node.clone(),e);[...s.leafNodes||[],...a.leafNodes||[]].forEach(h=>{[l.right,u.right,u].forEach(f=>{f&&!f.provenance.includes(h.id)&&f.provenance.push(h.id)})}),t.push({node:u,sign:s.sign*a.sign})}return t}function gE(n,e){if(n.length===2){const[t,r]=n,i=[];return i.push({node:Fa(t.node,3,e,t.leafNodes),sign:Math.pow(t.sign,3)}),i.push({node:Vo(3,t.node,2,r.node,1,e,t.leafNodes,r.leafNodes),sign:Math.pow(t.sign,2)*r.sign}),i.push({node:Vo(3,t.node,1,r.node,2,e,t.leafNodes,r.leafNodes),sign:t.sign*Math.pow(r.sign,2)}),i.push({node:Fa(r.node,3,e,r.leafNodes),sign:Math.pow(r.sign,3)}),i}return J0(mE(n,e),n,e)}function Dq(n,e){if(n.length===2){const[r,i]=n,s=[];return s.push({node:Fa(r.node,4,e,r.leafNodes),sign:Math.pow(r.sign,4)}),s.push({node:Vo(4,r.node,3,i.node,1,e,r.leafNodes,i.leafNodes),sign:Math.pow(r.sign,3)*i.sign}),s.push({node:Vo(6,r.node,2,i.node,2,e,r.leafNodes,i.leafNodes),sign:Math.pow(r.sign,2)*Math.pow(i.sign,2)}),s.push({node:Vo(4,r.node,1,i.node,3,e,r.leafNodes,i.leafNodes),sign:r.sign*Math.pow(i.sign,3)}),s.push({node:Fa(i.node,4,e,i.leafNodes),sign:Math.pow(i.sign,4)}),s}const t=gE(n,e);return J0(t,n,e)}function Fa(n,e,t,r){if(e===1){const o=n.clone();return r&&r.length>0&&r.forEach(l=>{o.provenance.includes(l.id)||o.provenance.push(l.id)}),o}const i=ie.createConstant(e,t),s={type:"OperatorNode",op:"^",fn:"pow",args:[n.toMathJSNode(),i.toMathJSNode()],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}},a=new Ii(s);return a.setFontSize(t),a.initialize(),r&&r.length>0?r.forEach(o=>{a.base.provenance.includes(o.id)||a.base.provenance.push(o.id),a.provenance.includes(o.id)||a.provenance.push(o.id)}):(a.base.provenance.push(n.id),a.provenance.push(n.id)),a}function Vo(n,e,t,r,i,s,a,o){let l=ie.createConstant(n,s);if(t>0){const u=Fa(e,t,s,a);l=ie.createBinaryOp(l,"multiply",u,s),a&&a.length>0&&a.forEach(c=>{l.provenance.includes(c.id)||l.provenance.push(c.id)})}if(i>0){const u=Fa(r,i,s,o);l=ie.createBinaryOp(l,"multiply",u,s),o&&o.length>0&&o.forEach(c=>{l.provenance.includes(c.id)||l.provenance.push(c.id)})}return l}function vE(n,e,t){if(e===1)return n.clone();const r=ie.createConstant(e,t),i={type:"OperatorNode",op:"^",fn:"pow",args:[n.toMathJSNode(),r.toMathJSNode()],clone:function(){return{...this,args:this.args.map(a=>a.clone())}}},s=new Ii(i);return s.setFontSize(t),s.initialize(),s}function J0(n,e,t){const r=[];for(const i of n)for(const s of e){const a=ie.createBinaryOp(i.node.clone(),"multiply",s.node.clone(),t),o=[...i.leafNodes||[],...s.leafNodes||[]];o.forEach(l=>{[a.left,a.right,a].forEach(u=>{u&&!u.provenance.includes(l.id)&&u.provenance.push(l.id)})}),r.push({node:a,sign:i.sign*s.sign,leafNodes:o})}return r}function yE(n,e,t,r,i=[],s=[]){const a={type:"SymbolNode",name:e,clone:function(){return{...this}}},o=new(ie.getNodeClass("omdVariableNode"))(a);o.setFontSize(r),o.initialize(),s&&s.length>0&&(o.provenance=[...s]);let l=o;if(t!==1){const c={type:"OperatorNode",op:"^",fn:"pow",args:[a,{type:"ConstantNode",value:t,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};l=new(ie.getNodeClass("omdPowerNode"))(c),l.setFontSize(r),l.initialize(),l.base&&s&&s.length>0&&(l.base.provenance=[...s])}let u;if(n===1)u=l;else if(n===-1){const c={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[l.toMathJSNode()],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};u=new(ie.getNodeClass("omdUnaryExpressionNode"))(c),u.setFontSize(r),u.initialize(),u.argument&&s&&s.length>0&&(u.argument.provenance=[...s])}else{const c=ie.createConstant(Math.abs(n),r);i&&i.length>0&&(c.provenance=[...i]);const h=ie.createBinaryOp(c,"multiply",l,r);if(h.left&&i&&i.length>0&&(h.left.provenance=[...i]),h.right&&s&&s.length>0&&(h.right.provenance=[...s]),n<0){const f={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(d=>d.clone())}}};u=new(ie.getNodeClass("omdUnaryExpressionNode"))(f),u.setFontSize(r),u.initialize(),u.argument&&(u.argument.left&&i&&i.length>0&&(u.argument.left.provenance=[...i]),u.argument.right&&s&&s.length>0&&(u.argument.right.provenance=[...s]))}else u=h}return u}function Z0(n){const e=[],t=[];function r(i,s=!1){if(i){if(i.type==="omdVariableNode"){t.push(i);return}if(i.type==="omdConstantNode"){if(i.parent&&i.parent.type==="omdPowerNode"&&i.parent.exponent===i)return;e.push(i);return}if(i.type==="omdPowerNode"){i.base&&r(i.base,!1);return}if(i.type==="omdBinaryExpressionNode"){i.operation==="multiply"?(i.left&&r(i.left,!0),i.right&&r(i.right,!1)):(i.left&&r(i.left,s),i.right&&r(i.right,s));return}if(i.type==="omdUnaryExpressionNode"){i.argument&&r(i.argument,s);return}["left","right","base","exponent","argument","expression","numerator","denominator"].forEach(a=>{i[a]&&r(i[a],s)})}}return r(n),{coefficientNodes:e,variableNodes:t}}const rt=class rt{static createConstant(e,t=16,...r){const i=Y0(e,t);return r.length>0&&Ur(i,...r),i}static createBinaryOp(e,t,r,i=16,s=null,a=null,...o){const u={add:{op:"+",fn:"add"},subtract:{op:"−",fn:"subtract"},multiply:{op:ai(),fn:"multiply"},divide:{op:"÷",fn:"divide"}}[t];if(!u)throw new Error(`Unknown operator: ${t}`);let c=e,h=r;if(t==="multiply"){const p=e instanceof Zr&&e.isConstant(),m=r instanceof Zr&&r.isConstant();!p&&m&&(c=r,h=e)}const f={type:"OperatorNode",op:u.op,fn:u.fn,args:[c.toMathJSNode(),h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(p=>p.clone())}}};a&&(f.operatorProvenance=[a.id]);const d=new Ci(f);if(d.setFontSize(i),s)d.provenance=s;else{const p=[c,h];a&&p.push(a),p.push(...o),Ur(d,...p)}return d.initialize(),d}static createMultiplication(e,t,r=16,i=null){var l;const s=e.clone();s.provenance=[e.id];const a=t.clone(),o=((l=e.parent)==null?void 0:l.op)||null;return rt.createBinaryOp(s,"multiply",a,r,i,o)}static createRational(e,t,r=16,...i){if(t===1)return rt.createConstant(e,r,...i);const s={type:"OperatorNode",op:"/",fn:"divide",args:[{type:"ConstantNode",value:Math.abs(e)},{type:"ConstantNode",value:t}],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}};let a=new Hr(s);if(e<0){const o={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[a.toMathJSNode()],clone:function(){return{...this,args:this.args.map(l=>l.clone())}}};a=new Qi(o)}return a.setFontSize(r),i.length>0&&Ur(a,...i),a.initialize(),a}static isType(e,t){return e?e.type===t:!1}static isBinaryOp(e,t=null){if(!rt.isType(e,"omdBinaryExpressionNode"))return!1;if(!t)return!0;let r=e.operation;return typeof r=="object"&&r.name&&(r=r.name),r===t}static isConstantValue(e,t=null){return e.isConstant()?t!==null?e.getValue()===t:!0:!1}static hasConstantOperand(e){return rt.isBinaryOp(e)?e.left.isConstant()?{constant:e.left,other:e.right}:e.right.isConstant()?{constant:e.right,other:e.left}:null:null}static unwrapParentheses(e){return rt.isType(e,"omdParenthesisNode")?e.expression:e}static isMonomial(e){let t=1;for(e=rt.unwrapParentheses(e);rt.isType(e,"omdUnaryExpressionNode")&&e.operation==="unaryMinus";)e=e.argument,t*=-1,e=rt.unwrapParentheses(e);if(rt.isType(e,"omdVariableNode"))return{coefficient:1*t,variable:e.name,power:1,variableNode:e};if(rt.isBinaryOp(e,"multiply")){const r=rt.hasConstantOperand(e);if(r&&rt.isType(r.other,"omdVariableNode"))return{coefficient:r.constant.getValue()*t,variable:r.other.name,power:1,variableNode:r.other,coefficientNode:r.constant};if(r&&rt.isType(r.constant,"omdVariableNode")&&r.other.isConstant())return{coefficient:r.other.getValue()*t,variable:r.constant.name,power:1,variableNode:r.constant,coefficientNode:r.other};const i=rt.hasConstantOperand(e);if(i&&rt.isType(i.other,"omdPowerNode")){const s=i.other;if(rt.isType(s.base,"omdVariableNode")&&s.exponent.isConstant())return{coefficient:i.constant.getValue()*t,variable:s.base.name,power:s.exponent.getValue(),variableNode:s.base,coefficientNode:i.constant,powerNode:s}}}return rt.isType(e,"omdPowerNode")&&rt.isType(e.base,"omdVariableNode")&&e.exponent.isConstant()?{coefficient:1*t,variable:e.base.name,power:e.exponent.getValue(),variableNode:e.base,powerNode:e}:null}static areLikeTerms(e,t){return e.variable===t.variable&&e.power===t.power}static createMonomial(e,t,r,i,s=[]){const a={type:"SymbolNode",name:t,clone:function(){return{...this}}},o=new(rt.getNodeClass("omdVariableNode"))(a);o.setFontSize(i),o.initialize(),s&&s.length>0&&(o.provenance=[...s]);let l=o;if(r!==1){const c={type:"OperatorNode",op:"^",fn:"pow",args:[a,{type:"ConstantNode",value:r,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};l=new(rt.getNodeClass("omdPowerNode"))(c),l.setFontSize(i),l.initialize(),s&&s.length>0&&(l.provenance=[...s],l.base&&(l.base.provenance=[...s]),l.exponent&&(l.exponent.provenance=[...s]))}let u;if(e===1)u=l;else if(e===-1){const c={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[l.toMathJSNode()],clone:function(){return{...this,args:this.args.map(h=>h.clone())}}};u=new Qi(c),u.setFontSize(i),u.initialize(),s&&s.length>0&&(u.provenance=[...s],u.argument&&(u.argument.provenance=[...s]))}else{const c=rt.createConstant(Math.abs(e),i);s&&s.length>0&&(c.provenance=[...s]);const h=rt.createBinaryOp(c,"multiply",l,i);if(s&&s.length>0&&(h.provenance=[...s],h.left&&(h.left.provenance=[...s]),h.right&&(h.right.provenance=[...s])),e<0){const f={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[h.toMathJSNode()],clone:function(){return{...this,args:this.args.map(d=>d.clone())}}};u=new Qi(f),u.setFontSize(i),u.initialize(),s&&s.length>0&&(u.provenance=[...s],u.argument&&(u.argument.provenance=[...s],u.argument.left&&(u.argument.left.provenance=[...s]),u.argument.right&&(u.argument.right.provenance=[...s])))}else u=h}return s&&s.length>0&&s.forEach(c=>{u.provenance.includes(c)||u.provenance.push(c)}),u}static getNodeClass(e){return{omdVariableNode:Zi,omdPowerNode:Ii,omdUnaryExpressionNode:Qi}[e]}static rational(e,t,r){var o,l;const i=Yn(Math.abs(e),Math.abs(t)),s=e/i,a=t/i;return a<0?by(o=rt,Jo,xy).call(o,-s,-a,r):by(l=rt,Jo,xy).call(l,s,a,r)}static combineConstants(e,t,r,i){const s=e.getValue(),a=t.getValue();let o=null;switch(r){case"add":o=rt.createConstant(s+a,i,e,t);break;case"subtract":o=rt.createConstant(s-a,i,e,t);break;case"multiply":o=rt.createConstant(s*a,i,e,t);break;case"divide":if(a===0)return null;o=rt.rational(s,a,i,e,t);break;default:return null}return o}static createRule(e,t,r,i=null,s=null){return new rt.SimplificationRule(e,t,r,i,s)}static createConstantFoldRule(e,t){return rt.createRule(e,r=>rt.isBinaryOp(r,t)?r.left.isConstant()&&r.right.isConstant():!1,r=>rt.combineConstants(r.left,r.right,t,r.getFontSize()),(r,i,s)=>{const a=r.left.getValue(),o=r.right.getValue(),l=s.getValue?s.getValue():s.toString(),c={add:"+",subtract:"-",multiply:ai(),divide:"÷"}[t]||t;return`Combined constants: ${a} ${c} ${o} = ${l}`})}static createIdentityRule(e,t,r,i="both"){return rt.createRule(e,s=>{if(!rt.isBinaryOp(s,t))return!1;const a=rt.hasConstantOperand(s);return!a||!a.constant.isConstant()||a.constant.getValue()!==r||i==="left"&&s.right.isConstant()||i==="right"&&s.left.isConstant()?!1:{other:a.other}},(s,a)=>{const o=a.other.clone();return Ur(o,s),o.__isSimpleIdentity=!0,o},(s,a,o)=>{const{other:l}=a,u=l.toString?l.toString():"expression",c={add:"addition",subtract:"subtraction",multiply:"multiplication",divide:"division"};ai();const h=c[t]||t,d=s.left.isConstant()&&s.left.getValue()===r?"left":"right";return t==="add"&&r===0?`Applied additive identity: "${u} + 0" simplified to "${u}" (adding 0 doesn't change the value)`:t==="subtract"&&r===0?`Applied subtraction identity: "${u} - 0" simplified to "${u}" (subtracting 0 doesn't change the value)`:t==="multiply"&&r===1?`Applied multiplicative identity: "${u} ${ai()} 1" simplified to "${u}" (multiplying by 1 doesn't change the value)`:t==="divide"&&r===1?`Applied division identity: "${u} ÷ 1" simplified to "${u}" (dividing by 1 doesn't change the value)`:`Applied ${h} identity: removed ${r} from ${d} side, leaving "${u}"`})}static createZeroMultiplicationRule(){return rt.createRule("Zero Multiplication",e=>{if(!rt.isBinaryOp(e,"multiply"))return!1;const t=rt.hasConstantOperand(e);return t&&t.constant.getValue()===0},e=>rt.createConstant(0,e.getFontSize(),e),(e,t,r)=>{const s=rt.hasConstantOperand(e).other;return`Applied zero multiplication: ${pt(s)} ${ai()} 0 = 0`})}};Jo=new WeakSet,xy=function(e,t,r){if(t===1)return rt.createConstant(e,r);const i={type:"OperatorNode",op:"/",fn:"divide",args:[{type:"ConstantNode",value:Math.abs(e),clone:function(){return{...this}}},{type:"ConstantNode",value:t,clone:function(){return{...this}}}],clone:function(){return{...this,args:this.args.map(a=>a.clone())}}};let s=new Hr(i);if(e<0){const a={type:"OperatorNode",op:"-",fn:"unaryMinus",args:[s.toMathJSNode()],clone:function(){return{...this,args:this.args.map(o=>o.clone())}}};s=new Qi(a)}return s.setFontSize(r),s.initialize(),s},TE(rt,Jo),eu(rt,"SimplificationRule",class{constructor(t,r,i,s=null,a=null){this.name=t,this.type=a,this.match=r,this.transform=i,this.message=s}canApply(t){const r=this.match(t);return r===!1||r===null||r===void 0?null:r===!0?{}:r}apply(t,r,i){try{if(typeof this.transform!="function")throw new Error(`Invalid transform function for rule: ${this.name}`);const s=this.transform(t,r,i);if(!s)throw new Error(`Transform function for rule '${this.name}' did not return a new node.`);const a=this._collectAffectedNodeIds(t),{success:o,newRoot:l}=Sq(t,s,i);if(o){const u=s.__affectedNodeIds||a,c=s.__resultNodeId||s.id,h={name:this.name,affectedNodes:u,resultNodeId:c,resultProvSources:s.provenance,message:this.message(t,r,s)};return{success:!0,newRoot:l,historyEntry:h}}else return{success:!1,newRoot:i}}catch(s){return console.error(`Error applying rule '${this.name}':`,s),{success:!1,newRoot:i}}}_collectAffectedNodeIds(t){return t&&t.provenance&&t.provenance.length>0?t.provenance.filter(r=>r!==t.id):t&&t.id?[t.id]:[]}_generateMessage(t,r,i){if(this.message)try{return this.message(t,r,i)}catch(o){console.warn(`Error generating message for rule ${this.name}:`,o)}const s=t.toString?t.toString():"expression",a=i.toString?i.toString():"expression";return`Applied ${this.name}: "${s}" → "${a}"`}});let ie=rt;const Aq=[ie.createRule("Simplify Double Negation",n=>n.operation==="unaryMinus"&&ie.isType(n.argument,"omdUnaryExpressionNode")&&n.argument.operation==="unaryMinus",n=>{const e=n.argument.argument.clone();return e.provenance.push(n.id,n.argument.id),e},(n,e,t)=>{const r=pt(n.argument.argument);return`Simplified double negation: -(-${r}) = ${r}`}),ie.createRule("Remove Unary Plus",n=>n.operation==="unaryPlus",n=>{const e=n.argument.clone();return e.provenance.push(n.id),e},(n,e,t)=>`Removed unary plus from "${pt(n.argument)}"`)],Eq=[ie.createRule("Remove Redundant Parentheses",n=>ie.isType(n.expression,"omdParenthesisNode"),n=>{const e=n.expression.clone();return e.provenance.push(n.id),e},(n,e,t)=>`Removed redundant parentheses around "${pt(n.content)}"`)],Mq=[ie.createRule("Simplify Square Root of Constant",n=>{if(!n.argument.isConstant())return!1;const e=n.argument.getValue();if(e<0)return!1;const t=Math.sqrt(e);return Number.isInteger(t)?{value:t}:!1},(n,e)=>{const t=ie.createConstant(e.value,n.getFontSize());return t.provenance.push(n.id,n.argument.id),t},(n,e,t)=>{const r=n.argument.getValue(),i=e.value;return`Calculated square root: √${r} = ${i}`}),ie.createRule("Square Root of Square",n=>{if(!n.argument||n.argument.type!=="omdPowerNode")return!1;const e=n.argument;return!e.exponent.isConstant()||e.exponent.getValue()!==2?!1:{base:e.base}},(n,e)=>{const t=e.base.clone();return t.provenance.push(n.id,n.argument.id),t},(n,e,t)=>{const r=pt(e.base);return`Simplified square root of square: √(${r}²) = ${r}`})];class Fs extends Pt{constructor(e){super(e),this.type="omdSqrtNode",this.args=e.args||[],this.value=this.parseValue(),this.argument=this.createArgumentNode(),this.argument&&(this.argumentNodeList.argument=this.argument),[this.radicalPath,this.radicalLine]=this.createRadicalElements()}parseValue(){return"sqrt"}createArgumentNode(){if(this.args.length===0)return null;const e=this.args[0],t=_t(e);let r=new t(e);return this.addChild(r),r}createRadicalElements(){let e=new Ni;e.setStrokeColor("black"),e.setStrokeWidth(2),e.setFillColor("none"),this.addChild(e);let t=new Ut;return t.setStrokeColor("black"),t.setStrokeWidth(2),this.addChild(t),[e,t]}computeDimensions(){if(!this.argument)return;const e=this.getFontSize(),t=e*5/6;this.argument.setFontSize(t),this.argument.computeDimensions();const r=e/this.getRootFontSize(),i=4*r,s=this.argument.width,a=this.argument.height,l=Math.max(12*r,a*.3)+i+s+i,u=a+8*r;this.setWidthAndHeight(l,u)}updateLayout(){if(!this.argument)return;const t=this.getFontSize()/this.getRootFontSize(),r=4*t;let i=0;const s=this.argument.height,a=Math.max(12*t,s*.3),o=i+a+r,l=(this.height-s)/2;this.argument.setPosition(o,l),this.argument.updateLayout();const u=l+s-2*t,c=l-4*t,h=l+s*.7;this.radicalPath.clearPoints(),this.radicalPath.addPoint(i+a*.3,h),this.radicalPath.addPoint(i+a*.6,u),this.radicalPath.addPoint(i+a,c),this.radicalPath.updatePath();const f=l-2*t,d=i+a,p=o+this.argument.width+r/2;this.radicalLine.setEndpoints(d,f,p,f)}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Fs(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.radicalPath=new Ni,t.radicalPath.setStrokeColor("black"),t.radicalPath.setStrokeWidth(2),t.radicalPath.setFillColor("none"),t.addChild(t.radicalPath),t.radicalLine=new Ut,t.radicalLine.setStrokeColor("black"),t.radicalLine.setStrokeWidth(2),t.addChild(t.radicalLine),this.argument&&(t.argument=this.argument.clone(),t.addChild(t.argument),t.argumentNodeList.argument=t.argument,t.provenance.push(this.id)),t}highlightAll(){this.select(),this.argument&&this.argument.highlightAll&&this.argument.highlightAll()}unhighlightAll(){this.deselect(),this.argument&&this.argument.unhighlightAll&&this.argument.unhighlightAll()}toMathJSNode(){const e={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt",clone:function(){return{...this}}},args:this.argument?[this.argument.toMathJSNode()]:[]};return e.clone=function(){const t={...this};return this.args&&(t.args=this.args.map(r=>r.clone())),this.fn&&typeof this.fn.clone=="function"&&(t.fn=this.fn.clone()),t},e}toString(){return`sqrt(${this.argument?this.argument.toString():""})`}evaluate(e={}){if(!this.argument||!this.argument.evaluate)return NaN;const t=this.argument.evaluate(e);return t<0?NaN:Math.sqrt(t)}isSquareRoot(){return!0}isCubeRoot(){return!1}toPowerForm(){if(!this.argument)return null;const e={type:"OperatorNode",op:"^",fn:"pow",args:[this.argument.toMathJSNode(),Zr.fromNumber(.5).toMathJSNode()]};return new Ii(e)}static fromString(e){try{const t=window.math.parse(e);if(t.type==="FunctionNode"&&t.fn.name==="sqrt")return new Fs(t);throw new Error("Expression is not a 'sqrt' function.")}catch(t){throw console.error("Failed to create sqrt node from string:",t),t}}}const Tq=[ie.createRule("Calculate Powers",n=>{if(!n.base.isConstant()||!n.exponent.isConstant())return!1;const e=n.base.getValue(),t=n.exponent.getValue();return{value:Math.pow(e,t)}},(n,e)=>{const t=ie.createConstant(e.value,n.getFontSize());return t.provenance.push(n.id),t},(n,e,t)=>{const{base:r,exponent:i}=n,s=e.value;return`Calculated power: ${pt(r)}^${pt(i)} = ${s}`}),ie.createRule("Power of Zero",n=>n.exponent.isConstant()&&n.exponent.getValue()===0,n=>{const e=ie.createConstant(1,n.getFontSize());return e.provenance.push(n.id),e},(n,e,t)=>{const{base:r}=n;return`Simplified power of zero: ${pt(r)}^0 = 1`}),ie.createRule("Power of One",n=>n.exponent.isConstant()&&n.exponent.getValue()===1,n=>{const e=n.base.clone();return e.provenance.push(n.id),e},(n,e,t)=>{const{base:r}=n;return`Simplified power of one: ${pt(r)}^1 = ${pt(r)}`}),ie.createRule("Expand Polynomial Power",n=>{if(!n.exponent.isConstant())return!1;const e=n.exponent.getValue();if(!Number.isInteger(e)||e<2||e>4)return!1;let t=ie.unwrapParentheses(n.base);if(!ie.isBinaryOp(t,"add")&&!ie.isBinaryOp(t,"subtract"))return!1;const r=[];return oi(t,r),r.length>5?!1:{baseExpression:t,terms:r,exponent:e}},(n,e)=>{const{terms:t,exponent:r}=e,i=Cq(t,r,n.getFontSize()),s=Ts(i,n.getFontSize());return s&&s.provenance.push(n.id),s},(n,e,t)=>{const{baseExpression:r,exponent:i}=e;return`Expanded polynomial power: (${pt(r)})^${i}`}),ie.createRule("Square of Square Root",n=>!n.exponent.isConstant()||n.exponent.getValue()!==2||n.base.type!=="omdSqrtNode"?!1:{innerArg:n.base.argument},(n,e)=>{const t=e.innerArg.clone();return t.provenance.push(n.id,n.base.id),t},(n,e,t)=>{const r=pt(e.innerArg);return`Simplified square of square root: (√${r})² = ${r}`}),ie.createRule("Fractional Exponent to Square Root",n=>{if(!n.exponent.isConstant())return!1;const e=n.exponent.getValue();return Math.abs(e-.5)>1e-4?!1:{base:n.base}},(n,e)=>{const t={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt"},args:[e.base.toMathJSNode()]},r=new Fs(t);return r.setFontSize(n.getFontSize()),r.initialize(),r.provenance.push(n.id),r},(n,e,t)=>{const r=pt(e.base);return`Converted fractional exponent to square root: ${r}^(1/2) = √${r}`})],Fq=[["sin","arcsin"],["cos","arccos"],["tan","arctan"],["ln","exp"],["log","pow10"],["sqrt","square"],["sinh","asinh"],["cosh","acosh"],["tanh","atanh"]];function _q(n){for(const[e,t]of Fq){if(e===n)return t;if(t===n)return e}return null}const Oq=[ie.createRule("Function Inverse Simplification",n=>{if(n.type!=="omdFunctionNode"||!n.functionName||!n.argNodes||n.argNodes.length!==1)return!1;const e=n.functionName,t=n.argNodes[0];if(t.type!=="omdFunctionNode"||!t.functionName||!t.argNodes||t.argNodes.length!==1)return!1;const r=t.functionName;return _q(e)===r?{outerFunction:e,innerFunction:r,innerArg:t.argNodes[0]}:!1},(n,e)=>{const t=e.innerArg.clone();return t.provenance.push(n.id,n.argNodes[0].id),t},(n,e,t)=>{const{outerFunction:r,innerFunction:i}=e,s=pt(e.innerArg);return`Simplified inverse functions: ${r}(${i}(${s})) = ${s}`}),ie.createRule("Function to Sqrt Node",n=>n.type!=="omdFunctionNode"||n.functionName!=="sqrt"||!n.argNodes||n.argNodes.length!==1?!1:{argument:n.argNodes[0]},(n,e)=>{const t={type:"FunctionNode",fn:{type:"SymbolNode",name:"sqrt"},args:[e.argument.toMathJSNode()]},r=new Fs(t);return r.setFontSize(n.getFontSize()),r.initialize(),r.provenance.push(n.id),r},(n,e,t)=>{const r=pt(e.argument);return`Converted function to sqrt node: sqrt(${r}) = √${r}`})],Bq=[ie.createRule("Unary Minus Cancellation",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdUnaryExpressionNode")&&ie.isType(t,"omdUnaryExpressionNode")?{numeratorArg:e.argument||e.operand,denominatorArg:t.argument||t.operand,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=n.getFontSize(),r=e.numeratorArg,i=e.denominatorArg;if(i&&typeof i.isConstant=="function"&&i.isConstant()&&i.getValue()===1){const u=r.clone();try{Ur(u,n.numerator,n.denominator,n)}catch{u.provenance=u.provenance||[],e.numeratorNode&&u.provenance.push(e.numeratorNode.id),e.denominatorNode&&u.provenance.push(e.denominatorNode.id),u.provenance.push(n.id)}return u}const s=r.clone(),a=i.clone(),o={type:"OperatorNode",op:"/",fn:"divide",args:[s.toMathJSNode(),a.toMathJSNode()],clone:function(){return{...this,args:this.args.map(u=>u.clone())}}},l=new Hr(o);l.setFontSize(t),l.initialize();try{l.numerator&&Ur(l.numerator,n.numerator),l.denominator&&Ur(l.denominator,n.denominator),Ur(l,n.numerator,n.denominator,n)}catch{Q0(l,e.numeratorNode.argument||e.numeratorNode.operand,e.denominatorNode.argument||e.denominatorNode.operand),l.provenance.includes(n.id)||l.provenance.push(n.id)}return l},(n,e,t)=>"Canceled unary negatives in fraction","rational"),ie.createRule("Unary Numerator Divide By -1",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdUnaryExpressionNode")&&t.isConstant&&t.isConstant()&&t.getValue()===-1?{numeratorArg:e.argument||e.operand,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=e.numeratorArg.clone();try{Ur(t,n.numerator,n.denominator,n)}catch{t.provenance=t.provenance||[],e.numeratorNode&&t.provenance.push(e.numeratorNode.id),e.denominatorNode&&t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id)}return t},(n,e,t)=>"Divided by -1 cancels unary minus in numerator","rational"),ie.createRule("Variable Self Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);return ie.isType(e,"omdVariableNode")&&ie.isType(t,"omdVariableNode")&&e.name===t.name?{variable:e.name,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const t=ie.createConstant(1,n.getFontSize());return t.provenance.push(e.numeratorNode.id),t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id),t},(n,e,t)=>{const{variable:r}=e;return`Simplified variable self-division: ${r}/${r} = 1`}),ie.createRule("Power Base Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(ie.isType(e,"omdPowerNode")&&ie.isType(t,"omdVariableNode")&&ie.isType(e.base,"omdVariableNode")&&e.base.name===t.name&&e.exponent.isConstant()){const r=e.exponent.getValue(),i=r-1;return{variable:e.base.name,originalExponent:r,newExponent:i,baseNode:e.base,powerNode:e,denominatorNode:t}}return!1},(n,e)=>{const{variable:t,newExponent:r,baseNode:i,powerNode:s,denominatorNode:a}=e,o=n.getFontSize();let l;return r===0?l=ie.createConstant(1,o):r===1?l=i.clone():l=vE(i.clone(),r,o),l.provenance.push(s.id),l.provenance.push(a.id),l.provenance.push(n.id),l},(n,e,t)=>{const{variable:r,originalExponent:i,newExponent:s}=e;return s===0?`Simplified power division: ${r}^${i}/${r} = 1`:s===1?`Simplified power division: ${r}^${i}/${r} = ${r}`:`Simplified power division: ${r}^${i}/${r} = ${r}^${s}`}),ie.createRule("Monomial Variable Division",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator),r=ie.isMonomial(e);return r&&ie.isType(t,"omdVariableNode")&&r.variable===t.name&&r.power===1?{coefficient:r.coefficient,variable:r.variable,numeratorNode:e,denominatorNode:t}:!1},(n,e)=>{const{coefficient:t}=e,r=n.getFontSize(),i=ie.createConstant(t,r);return i.provenance.push(e.numeratorNode.id),i.provenance.push(e.denominatorNode.id),i.provenance.push(n.id),i},(n,e,t)=>{const{coefficient:r,variable:i}=e;return`Simplified monomial division: ${r}${i}/${i} = ${r}`}),ie.createRule("Simplify Fraction",n=>{if(n.type!=="omdRationalNode")return!1;const e=n.numerator,t=n.denominator;if(!e.isConstant()||!t.isConstant())return!1;const r=e.getValue(),i=t.getValue();if(i===0)return!1;const s=Yn(Math.abs(r),Math.abs(i));return s>1||i<0?{originalNum:r,originalDen:i,gcd:s,simplifiedNum:i<0?-r/s:r/s,simplifiedDen:Math.abs(i)/s}:!1},(n,e)=>{const{simplifiedNum:t,simplifiedDen:r}=e;if(r===1){const i=ie.createConstant(t,n.getFontSize(),n.numerator,n.denominator);return i.provenance.push(n.id),i}else{const i=ie.rational(t,r,n.getFontSize());return Q0(i,n.numerator,n.denominator),i.provenance.push(n.id),i}},(n,e,t)=>{const{originalNum:r,originalDen:i,simplifiedNum:s,simplifiedDen:a,gcd:o}=e;return i<0&&o>1?`Simplified fraction: ${r}/${i} = ${s}/${a} (corrected sign and reduced by GCD ${o})`:a===1?`Simplified fraction to whole number: ${r}/${i} = ${s}`:o>1?`Simplified fraction: ${r}/${i} = ${s}/${a} (reduced by GCD ${o})`:`Corrected fraction sign: ${r}/${i} = ${s}/${a}`}),ie.createRule("Simplify Multiplication in Rational",n=>{let e=n.numerator;if(!n.denominator.isConstant())return!1;const t=n.denominator.getValue();if(t===0||(e=ie.unwrapParentheses(e),!ie.isBinaryOp(e,"multiply")))return!1;const r=ie.hasConstantOperand(e);return r?{numeratorCoeff:r.constant.getValue(),denominator:t,expression:r.other}:!1},(n,e)=>{const{numeratorCoeff:t,denominator:r,expression:i}=e,s=ie.rational(t,r,n.getFontSize());kq(s,n);const a=ie.createBinaryOp(s,"multiply",i.clone(),n.getFontSize());return a.right&&a.right.provenance.push(i.id),a.provenance.push(n.id),a},(n,e,t)=>{const{numeratorCoeff:r,denominator:i}=e,s=Yn(Math.abs(r),Math.abs(i));if(s===1)return"Separated the coefficient from the variable, changing the fraction into a multiplication.";const a=r/s,o=i/s;let l=`The numerator and denominator share a common factor of ${s}. `;return l+=`Dividing both by ${s} (${r} ÷ ${s} = ${a}, and ${i} ÷ ${s} = ${o}) simplifies the fraction.`,l},"rational"),ie.createRule("Cancel Negative Coefficient",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(!ie.isType(e,"omdUnaryExpressionNode"))return!1;const r=e.argument||e.operand;if(!ie.isBinaryOp(r,"multiply"))return!1;const i=ie.hasConstantOperand(r);if(!i||!i.constant.isConstant()||!t.isConstant())return!1;const s=t.getValue();if(s>=0)return!1;const a=i.constant.getValue();return Math.abs(a)===Math.abs(s)?{innerMultiplication:r,otherFactor:i.other,numeratorUnary:e,denominatorNode:t}:!1},(n,e)=>{const t=e.otherFactor.clone();try{Ur(t,e.innerMultiplication||n.numerator,n.denominator,n)}catch{t.provenance=t.provenance||[],t.provenance.push(e.numeratorUnary.id),t.provenance.push(e.denominatorNode.id),t.provenance.push(n.id)}return t},(n,e,t)=>"Canceled matching numeric factors between numerator and denominator","rational"),ie.createRule("Negative Constant Over Negative Product",n=>{if(n.type!=="omdRationalNode")return!1;const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(!e.isConstant||!e.isConstant()||e.getValue()>=0||!ie.isBinaryOp(t,"multiply"))return!1;const i=ie.hasConstantOperand(t);return!i||!i.constant.isConstant()||i.constant.getValue()>=0?!1:{numeratorNode:e,denominatorNode:t,denominatorConst:i.constant,denominatorOther:i.other}},(n,e)=>{const t=n.getFontSize(),r=ie.createConstant(Math.abs(e.numeratorNode.getValue()),t),i=ie.createConstant(Math.abs(e.denominatorConst.getValue()),t),s=ie.createBinaryOp(i,"multiply",e.denominatorOther.clone(),t),a={type:"OperatorNode",op:"/",fn:"divide",args:[r.toMathJSNode(),s.toMathJSNode()],clone:function(){return{...this,args:this.args.map(l=>l.clone())}}},o=new Hr(a);o.setFontSize(t),o.initialize();try{const l=e&&e.numeratorNode&&(e.numeratorNode.argument||e.numeratorNode.operand)||n.numerator;o.numerator&&l&&Ur(o.numerator,l);const u=e&&e.denominatorNode||n.denominator;if(o.denominator&&ie.isBinaryOp(u,"multiply")&&ie.isBinaryOp(o.denominator,"multiply")){const c=e&&e.denominatorConst||u.left||u.right,h=e&&e.denominatorOther||(u.left===c?u.right:u.left);o.denominator.left&&c&&Ur(o.denominator.left,c),o.denominator.right&&h&&Ur(o.denominator.right,h)}else o.denominator&&Ur(o.denominator,n.denominator);Ur(o,n.numerator,n.denominator,n)}catch{Q0(o,n.numerator,n.denominator),o.provenance.includes(n.id)||o.provenance.push(n.id)}return o},(n,e,t)=>"Canceled matching negative factors: simplified sign and magnitude","rational"),ie.createRule("Simplify Rational Division",n=>{if(n.type!=="omdRationalNode")return!1;let e=n.numerator;const t=n.denominator;if(!t.isConstant()||(e=ie.unwrapParentheses(e),!ie.isBinaryOp(e,"add")&&!ie.isBinaryOp(e,"subtract")))return!1;const r=[];return oi(e,r),{terms:r,denominator:t.getValue()}},(n,e)=>{const{terms:t,denominator:r}=e,i=n.getFontSize(),s=t.map(a=>{const l=(a.node.isConstant()?a.node.getValue():1)*a.sign;if(a.node.isConstant()){const u=Yn(Math.abs(l),Math.abs(r)),c=l/u,h=r/u;if(h===1){const f=ie.createConstant(c,i);return K0(f,a.node,n.denominator),{node:f,sign:1}}else{const f=ie.rational(Math.abs(c),h,i);return K0(f,a.node,n.denominator),{node:f,sign:c>=0?1:-1}}}else if(l===r){const u=a.node.clone();return u.provenance.push(a.node.id),{node:u,sign:1}}else{const u=ie.rational(Math.abs(l),r,i),c=ie.createBinaryOp(u,"multiply",a.node.clone(),i);return K0(u,a.node,n.denominator),c.provenance.push(n.id),{node:c,sign:l>=0?1:-1}}});return Ts(s,i)},(n,e,t)=>{const{terms:r,denominator:i}=e,s=pt(n.numerator),a=r.map(l=>{const u=(l.node.isConstant()?l.node.getValue():1)*l.sign,c=Yn(Math.abs(u),Math.abs(i)),h=u/c,f=i/c,d=l.node.isConstant()?"":pt(l.node);return f===1?`${h}${d}`:`(${h}/${f})${d}`}).join(" + ");return`Distributed division: ${s.startsWith("(")&&s.endsWith(")")?s:`(${s})`}/${i} = ${a}`},"rational")];function Q0(n,e,t){e!=null&&e.provenance?e.provenance.forEach(r=>{n.provenance.includes(r)||n.provenance.push(r)}):e&&n.provenance.push(e.id),t!=null&&t.provenance?t.provenance.forEach(r=>{n.provenance.includes(r)||n.provenance.push(r)}):t&&n.provenance.push(t.id)}function kq(n,e){var r,i,s,a;const t=(i=(r=e.numerator)==null?void 0:r.left)!=null&&i.isConstant()?e.numerator.left:(s=e.numerator)==null?void 0:s.right;t!=null&&t.provenance?t.provenance.forEach(o=>{n.provenance.includes(o)||n.provenance.push(o)}):t&&n.provenance.push(t.id),(a=e.denominator)!=null&&a.provenance?e.denominator.provenance.forEach(o=>{n.provenance.includes(o)||n.provenance.push(o)}):e.denominator&&n.provenance.push(e.denominator.id)}function K0(n,e,t){var r,i,s;n.numerator&&e&&(n.numerator.provenance=[],((r=e.provenance)==null?void 0:r.length)>0?e.provenance.forEach(a=>{n.numerator.provenance.push(a)}):n.numerator.provenance.push(e.id)),n.denominator&&t&&(n.denominator.provenance=[],((i=t.provenance)==null?void 0:i.length)>0?t.provenance.forEach(a=>{n.denominator.provenance.push(a)}):n.denominator.provenance.push(t.id)),((s=e.provenance)==null?void 0:s.length)>0&&e.provenance.forEach(a=>{n.provenance.includes(a)||n.provenance.push(a)})}const _s={binary:[ie.createRule("Opposite Term Cancellation",n=>{if(!ie.isBinaryOp(n,"add"))return!1;if(n.left.isConstant()){const i=n.left.getValue();if(ie.isType(n.right,"omdUnaryExpressionNode")&&n.right.operation==="unaryMinus"&&n.right.argument.isConstant()){const s=n.right.argument.getValue();if(i===s)return{leftTerm:n.left,rightTerm:n.right,termType:"constant",leftValue:i,rightValue:-s,isNegatedRight:!0}}if(n.right.isConstant()){const s=n.right.getValue();if(i===-s)return{leftTerm:n.left,rightTerm:n.right,termType:"constant",leftValue:i,rightValue:s,isNegatedRight:!1}}}const e=ie.isMonomial(n.left);let t=null,r=!1;if(ie.isType(n.right,"omdUnaryExpressionNode")&&n.right.operation==="unaryMinus"?(t=ie.isMonomial(n.right.argument),r=!0):t=ie.isMonomial(n.right),e&&t){let i=e.coefficient,s=t.coefficient;if(r&&(s=-s),e.variable===t.variable&&e.power===t.power&&i===-s)return{leftTerm:n.left,rightTerm:n.right,termType:"monomial",variable:e.variable,power:e.power,leftCoeff:i,rightCoeff:s,isNegatedRight:r}}return!1},(n,e)=>{const{leftTerm:t,rightTerm:r}=e,i=ie.createConstant(0,n.getFontSize());return i.provenance.push(t.id),i.provenance.push(r.id),i.provenance.push(n.id),i},(n,e,t)=>{const{termType:r}=e;if(r==="constant"){const{leftValue:i,rightValue:s,isNegatedRight:a}=e;return a?`Cancelled opposite terms: ${i} + (-${i}) = 0`:`Cancelled opposite terms: ${i} + ${s} = 0`}else{const{variable:i,power:s,leftCoeff:a,rightCoeff:o,isNegatedRight:l}=e,u=s!==1?`^${s}`:"",h=`${a===1?"":a===-1?"-":`${a}`}${i}${u}`;let f;if(l){const d=Math.abs(o);f=`(-${d===1?"":`${d}`}${i}${u})`}else f=`${o===1?"":o===-1?"-":`${o}`}${i}${u}`;return`Cancelled opposite terms: ${h} + ${f} = 0`}}),ie.createRule("Cancel Constants in Sums",n=>{if(!ie.isBinaryOp(n)||n.operation!=="add"&&n.operation!=="subtract")return!1;const e=[];if(oi(n,e),e.length<3)return!1;const t=e.filter(a=>a.node.isConstant()),r=e.filter(a=>!a.node.isConstant());if(r.length===0||t.length<2)return!1;const i=[],s=new Set;for(let a=0;a<t.length;a++){if(s.has(a))continue;const o=t[a],l=o.node.getValue()*o.sign;for(let u=a+1;u<t.length;u++){if(s.has(u))continue;const c=t[u],h=c.node.getValue()*c.sign;if(l+h===0){i.push([o,c]),s.add(a),s.add(u);break}}}return i.length>0?{terms:e,cancellingPairs:i,constantTerms:t,nonConstantTerms:r}:!1},(n,e)=>{const{terms:t,cancellingPairs:r,constantTerms:i,nonConstantTerms:s}=e,a=[...s],o=new Set;r.forEach(c=>{c.forEach(h=>o.add(h))}),i.forEach(c=>{o.has(c)||a.push(c)});let l=[];if(r.length>0){const c=ie.createConstant(0,n.getFontSize());r.forEach(h=>{const[f,d]=h,p=t.find(m=>m.node.type==="omdBinaryExpressionNode"&&(m.node.left===f.node&&m.node.right===d.node||m.node.left===d.node&&m.node.right===f.node));h.forEach(m=>{c.provenance.push(m.node.id),l.push(m.node.id),m.node.operation&&(c.provenance.push(m.node.operation.id),l.push(m.node.operation.id))}),p&&p.node.operation&&(c.provenance.push(p.node.operation.id),l.push(p.node.operation.id))}),a.push({node:c,sign:1})}const u=Ts(a,n.getFontSize());return u&&l.forEach(c=>{u.provenance.includes(c)||u.provenance.push(c)}),u},(n,e,t)=>{const{cancellingPairs:r}=e;return`Cancelled constants in sum: ${r.map(s=>{const[a,o]=s,l=a.node.getValue(),u=o.node.getValue(),c=a.sign===1?"+":"-",h=o.sign===1?"+":"-";return`${c} ${l} ${h} ${u} = 0`}).join(", ")}`}),ie.createConstantFoldRule("Add Constants","add"),ie.createConstantFoldRule("Subtract Constants","subtract"),ie.createConstantFoldRule("Multiply Constants","multiply"),ie.createConstantFoldRule("Divide Constants","divide"),ie.createIdentityRule("Add Zero","add",0),ie.createIdentityRule("Subtract Zero","subtract",0,"right"),ie.createIdentityRule("Multiply One","multiply",1),ie.createIdentityRule("Divide One","divide",1,"right"),ie.createZeroMultiplicationRule(),ie.createRule("Combine Coefficients",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;if(!ie.isBinaryOp(t,"multiply"))return!1;const r=ie.hasConstantOperand(t);if(!r)return!1;const i=e.constant.getValue(),s=r.constant.getValue(),a=r.other;return{coefficient:i*s,expression:a}},(n,e)=>{const{coefficient:t,expression:r}=e,i=ie.createMultiplication(ie.createConstant(t,n.getFontSize()),r.clone(),n.getFontSize());return i.provenance.push(n.id),i.left&&i.left.provenance.push(n.left.id,n.right.id),i.right&&i.right.provenance.push(r.id),i},(n,e,t)=>{const{coefficient:r,expression:i}=e,s=ie.hasConstantOperand(n),a=ie.hasConstantOperand(s.other),o=s.constant.getValue(),l=a.constant.getValue();return`Combined coefficients: ${o} ${ai()} ${l} = ${r}`}),ie.createRule("Distributive Property",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;let r=t;return ie.isType(t,"omdParenthesisNode")&&(r=t.expression),!ie.isBinaryOp(r,"add")&&!ie.isBinaryOp(r,"subtract")?!1:{constantNode:e.constant,innerExpr:r,originalInnerNode:t}},(n,e)=>{const{constantNode:t,innerExpr:r}=e,i=t.getValue(),s=n.getFontSize(),a=[];oi(r,a);const o=a.map(l=>{const u=i*l.sign,c=ie.createBinaryOp(ie.createConstant(Math.abs(u),s),"multiply",l.node.clone(),s);return c.provenance.push(n.id,t.id,l.node.id),{node:c,sign:u>=0?1:-1}});return Ts(o,s)},(n,e,t)=>{const{constantNode:r,innerExpr:i}=e,s=r.toString(),a=i.toString();return`Applied distributive property: ${s} ${ai()} (${a})`}),ie.createRule("Expand Polynomial Multiplication",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;let e=ie.unwrapParentheses(n.left),t=ie.unwrapParentheses(n.right);const r=ie.isBinaryOp(e,"add")||ie.isBinaryOp(e,"subtract"),i=ie.isBinaryOp(t,"add")||ie.isBinaryOp(t,"subtract");if(!r||!i)return!1;const s=[],a=[];return oi(e,s),oi(t,a),s.length>4||a.length>4?!1:{leftExpression:e,rightExpression:t,leftTerms:s,rightTerms:a}},(n,e)=>{const{leftTerms:t,rightTerms:r}=e,i=n.getFontSize(),s=[];for(const a of t)for(const o of r){const l=a.sign*o.sign,u=ie.createBinaryOp(a.node.clone(),"multiply",o.node.clone(),i),c=[...a.leafNodes||[],...o.leafNodes||[]];c.forEach(h=>{[u.left,u.right,u].forEach(f=>{f&&!f.provenance.includes(h.id)&&f.provenance.push(h.id)})}),s.push({node:u,sign:l,leafNodes:c})}return Ts(s,i)},(n,e,t)=>{const{leftExpression:r,rightExpression:i}=e,s=pt(r),a=pt(i);return`Expanded polynomial multiplication: (${s})(${a})`}),ie.createRule("Multiply Monomials",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;const e=ie.isMonomial(n.left),t=ie.isMonomial(n.right);return!e||!t||e.variable!==t.variable?!1:{variable:e.variable,leftCoeff:e.coefficient,rightCoeff:t.coefficient,leftPower:e.power,rightPower:t.power,leftNode:n.left,rightNode:n.right}},(n,e)=>{const{variable:t,leftCoeff:r,rightCoeff:i,leftPower:s,rightPower:a,leftNode:o,rightNode:l}=e,u=n.getFontSize(),c=r*i,h=s+a,f=Z0(o),d=Z0(l),p=[...f.coefficientNodes.map(v=>v.id),...d.coefficientNodes.map(v=>v.id)],m=[...f.variableNodes.map(v=>v.id),...d.variableNodes.map(v=>v.id)],y=yE(c,t,h,u,p,m);return y.provenance.push(n.id),y},(n,e,t)=>{const{leftCoeff:r,rightCoeff:i,variable:s,leftPower:a,rightPower:o}=e,l=r*i,u=a+o,c=pt(e.leftNode),h=pt(e.rightNode);return`Multiplied monomials: ${c} ${ai()} ${h} = ${l}${s}${u>1?`^${u}`:""}`}),ie.createRule("Combine Like Factors",n=>{if(!ie.isBinaryOp(n,"multiply"))return!1;if(ie.isType(n.left,"omdVariableNode")&&ie.isType(n.right,"omdVariableNode")&&n.left.name===n.right.name)return{variable:n.left.name,leftNode:n.left,rightNode:n.right,power:2};let e=null,t=1,r=1,i=n.left,s=n.right;if(ie.isType(n.left,"omdVariableNode")?(e=n.left.name,t=1):ie.isType(n.left,"omdPowerNode")&&ie.isType(n.left.base,"omdVariableNode")&&n.left.exponent.isConstant()&&(e=n.left.base.name,t=n.left.exponent.getValue()),ie.isType(n.right,"omdVariableNode"))if(e===n.right.name)r=1;else return!1;else if(ie.isType(n.right,"omdPowerNode")&&ie.isType(n.right.base,"omdVariableNode")&&n.right.exponent.isConstant())if(e===n.right.base.name)r=n.right.exponent.getValue();else return!1;else return!1;return e&&Number.isInteger(t)&&Number.isInteger(r)?{variable:e,leftNode:i,rightNode:s,power:t+r}:!1},(n,e)=>{const{variable:t,power:r,leftNode:i,rightNode:s}=e,a=n.getFontSize();let o;if(r===1)o=ie.createMonomial(1,t,1,a);else{const l=ie.createMonomial(1,t,1,a);o=vE(l,r,a)}return o.provenance.push(i.id,s.id,n.id),o},(n,e,t)=>{const{variable:r,power:i}=e,s=pt(e.leftNode),a=pt(e.rightNode);return`Combined like factors: ${s} ${ai()} ${a} = ${r}${i>1?`^${i}`:""}`}),ie.createRule("Combine Multiple Constants in Sums",n=>{if(!ie.isBinaryOp(n)||n.operation!=="add"&&n.operation!=="subtract")return!1;const e=[];if(oi(n,e),e.filter(a=>a.node.isConstant()).length<=1)return!1;const r=e.filter(a=>a.node.isConstant());let i=0,s=1;for(const a of r){const{num:o,den:l}=a.node.getRationalValue(),u=i*l+o*a.sign*s,c=s*l;i=u,s=c;const h=Yn(Math.abs(i),Math.abs(s));i/=h,s/=h}return i===0?!1:{terms:e}},(n,e)=>{const{terms:t}=e,r=t.filter(c=>c.node.isConstant()),i=t.filter(c=>!c.node.isConstant()),s=r.map(c=>c.node);let a=0,o=1;for(const c of r){const{num:h,den:f}=c.node.getRationalValue(),d=a*f+h*c.sign*o,p=o*f;a=d,o=p;const m=Yn(Math.abs(a),Math.abs(o));a/=m,o/=m}let l=[...i];if(a!==0||l.length===0){o<0&&(a=-a,o=-o);const c=a>=0?1:-1,h=Math.abs(a);let f;o===1?f=ie.createConstant(h,n.getFontSize(),...s):(f=new Hr({type:"OperatorNode",fn:"divide",args:[{type:"ConstantNode",value:h},{type:"ConstantNode",value:o}]}),f.setFontSize(n.getFontSize()),s.forEach(d=>{d.id&&!f.provenance.includes(d.id)&&f.provenance.push(d.id)})),l.push({node:f,sign:c})}if(l.length===0)return ie.createConstant(0,n.getFontSize(),...s);const u=Ts(l,n.getFontSize());return u&&(s.forEach(c=>{c.id&&!u.provenance.includes(c.id)&&u.provenance.push(c.id)}),u.provenance.push(n.id)),u},(n,e,t)=>{const{terms:r}=e,i=r.filter(h=>h.node.isConstant());let s=0,a=1;for(const h of i){const{num:f,den:d}=h.node.getRationalValue(),p=s*d+f*h.sign*a,m=a*d;s=p,a=m;const y=Yn(Math.abs(s),Math.abs(a));s/=y,a/=y}const o=i.map(h=>{const f=pt(h.node);return h.sign===1?`+ ${f}`:`- ${f}`});o.length>0&&o[0].startsWith("+ ")&&(o[0]=o[0].substring(2));const l=o.join(" "),u=a===1?`${s}`:`${s}/${a}`;let c=`Combining the constant terms: ${l} = ${u}. `;return s===0?c+="Since the constants sum to zero, they are replaced by 0.":c+="The constants are replaced by their sum.",c}),ie.createRule("Combine Like Terms",n=>{if(!ie.isBinaryOp(n,"add")&&!ie.isBinaryOp(n,"subtract"))return!1;const e=[];oi(n,e);const t=new Map,r=[];for(const s of e){const a=ie.isMonomial(s.node);if(a){const o=`${a.variable}^${a.power}`;t.has(o)||t.set(o,[]),t.get(o).push({term:s,monomialInfo:a,originalNodeId:s.node.id})}else r.push(s)}return Array.from(t.values()).some(s=>s.length>1)?{likeTermGroups:t,otherTerms:r}:!1},(n,e)=>{const{likeTermGroups:t,otherTerms:r}=e;let i=[...r];const s=[];oi(n,s);for(const[a,o]of t)if(o.length===1){const l=s.findIndex(u=>u.node.id===o[0].term.node.id);l!==-1?i.splice(l,0,o[0].term):i.push(o[0].term)}else{let l=0;const u=[],c=[],h=o.map(f=>f.term.node.id);for(const f of o){const d=f.monomialInfo.coefficient*f.term.sign;l+=d;const p=Z0(f.term.node);p.coefficientNodes.forEach(m=>{u.includes(m.id)||u.push(m.id)}),p.variableNodes.forEach(m=>{c.includes(m.id)||c.push(m.id)})}if(l!==0){const f=o[0],d=yE(l,f.monomialInfo.variable,f.monomialInfo.power,n.getFontSize(),u,c),p=s.findIndex(m=>h.includes(m.node.id));i=i.filter(m=>!h.includes(m.node.id)),p!==-1?i.splice(p,0,{node:d,sign:1}):i.push({node:d,sign:1})}else i=i.filter(f=>!h.includes(f.node.id))}return i.length===0?ie.createConstant(0,n.getFontSize()):Ts(i,n.getFontSize())},(n,e,t)=>{const{likeTermGroups:r}=e,i=[];for(const[s,a]of r)if(a.length>1){let o=0;const l=[];for(const f of a){const d=f.monomialInfo.coefficient*f.term.sign;o+=d;const p=f.monomialInfo.variable,m=f.monomialInfo.power,y=m!==1?`^${m}`:"";d===1?l.push(`${p}${y}`):d===-1?l.push(`-${p}${y}`):l.push(`${d}${p}${y}`)}const u=a[0].monomialInfo.variable,c=a[0].monomialInfo.power,h=c!==1?`^${c}`:"";if(o===0)i.push(`${l.join(" + ").replace("+ -","- ")} = 0 (like terms cancelled)`);else{const f=o===1?`${u}${h}`:o===-1?`-${u}${h}`:`${o}${u}${h}`;i.push(`${l.join(" + ").replace("+ -","- ")} = ${f}`)}}return i.length===0?"No like terms were found to combine":i.length===1?`Combined like terms: ${i[0]}`:`Combined like terms: ${i.join("; ")}`}),ie.createRule("Multiply Divide Same Factor",n=>{if(ie.isType(n,"omdRationalNode")){const e=ie.unwrapParentheses(n.numerator),t=ie.unwrapParentheses(n.denominator);if(ie.isBinaryOp(e,"multiply")&&ie.isType(t,"omdConstantNode")){const r=ie.hasConstantOperand(e);if(r&&r.constant.getValue()===t.getValue())return{pattern:"rational",factor:r.constant.getValue(),expression:r.other,factorNode:r.constant,denominatorNode:t}}}if(ie.isBinaryOp(n,"multiply")){const e=ie.hasConstantOperand(n);if(!e)return!1;const t=e.other;if(ie.isType(t,"omdRationalNode")){const r=ie.unwrapParentheses(t.denominator);if(ie.isType(r,"omdConstantNode")&&e.constant.getValue()===r.getValue())return{pattern:"multiply",factor:e.constant.getValue(),expression:ie.unwrapParentheses(t.numerator),factorNode:e.constant,denominatorNode:r}}}return!1},(n,e)=>{const{expression:t,factorNode:r,denominatorNode:i}=e,s=t.clone();return s.provenance.push(r.id),s.provenance.push(i.id),s.provenance.push(n.id),s},(n,e,t)=>{const{pattern:r,factor:i}=e;return r==="rational"?`Simplified multiplication and division: (${i} × expression)/${i} = expression`:`Simplified multiplication and division: ${i} × (expression/${i}) = expression`})],rational:Bq,parenthesis:Eq,unary:Aq,power:Tq,sqrt:Mq,function:Oq},Pq={omdBinaryExpressionNode:_s.binary,omdRationalNode:_s.rational,omdParenthesisNode:_s.parenthesis,omdUnaryExpressionNode:_s.unary,omdPowerNode:_s.power,omdSqrtNode:_s.sqrt,omdFunctionNode:_s.function};function zq(n){return Pq[n.type]||[]}function Rq(n){const e=[],t=new Set;function r(i){if(!i||t.has(i))return;if(t.add(i),i.childList&&i.childList.length>0)for(const a of i.childList)r(a);const s=zq(i);for(const a of s){const o=a.canApply(i);if(o){e.push({node:i,rule:a,ruleData:o});break}}}return r(n),e}function _a(n){let e=0,t=n,r=null;const i=Rq(n);if(i.length>0){const s=i[0];try{const a=s.rule.apply(s.node,s.ruleData,n);a&&a.success&&a.newRoot&&(t=a.newRoot,e=1,r=a.historyEntry||{name:s.rule.name,affectedNodes:[n.id],message:`Applied ${s.rule.name}`})}catch(a){console.error(`Error applying rule '${s.rule.name}':`,a)}}return{newRoot:t,foldedCount:e,historyEntry:r}}gq(_a);class Ii extends Pt{constructor(e){if(super(e),this.type="omdPowerNode",!e.args||e.args.length!==2){console.error("omdPowerNode requires an AST node with exactly 2 args (base and exponent)",e);return}this.value=this.parseValue(),this.base=this.createOperand(e.args[0]),this.exponent=this.createOperand(e.args[1]),this.argumentNodeList.base=this.base,this.argumentNodeList.exponent=this.exponent}parseValue(){return"^"}createOperand(e){let t=_t(e),r=new t(e);return this.addChild(r),r}computeDimensions(){this.base.computeDimensions(),this.exponent.setFontSize(this.getFontSize()*3/4),this.exponent.computeDimensions();const e=this.base.width+this.exponent.width,t=this.base.height+this.getSuperscriptOffset();this.setWidthAndHeight(e,t)}updateLayout(){const e=this.height-this.base.height;this.base.updateLayout(),this.base.setPosition(0,e);const t=e-this.getSuperscriptOffset();this.exponent.updateLayout(),this.exponent.setPosition(this.base.width,t)}getSuperscriptOffset(){return this.getFontSize()*.4}getAlignmentBaseline(){return this.height-this.base.height+this.base.getAlignmentBaseline()}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Ii(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.base=this.base.clone(),t.exponent=this.exponent.clone(),t.addChild(t.base),t.addChild(t.exponent),t.argumentNodeList.base=t.base,t.argumentNodeList.exponent=t.exponent,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"OperatorNode",op:"^",fn:"pow",args:[this.base.toMathJSNode(),this.exponent.toMathJSNode()]};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.base.toString(),t=this.exponent.toString();let r=e;this.base.needsParentheses&&this.base.needsParentheses()?r=`(${e})`:(this.base.type==="BinaryExpressionNode"||this.base.constructor&&this.base.type==="omdBinaryExpressionNode")&&(r=`(${e})`);let i=t;return(this.exponent.type==="BinaryExpressionNode"||this.exponent.constructor&&this.exponent.type==="omdBinaryExpressionNode"||this.exponent.constructor&&this.exponent.type==="omdPowerNode")&&(i=`(${t})`),`${r}^${i}`}evaluate(e={}){const t=this.base.evaluate?this.base.evaluate(e):this.base.value!==void 0?parseFloat(this.base.value):NaN,r=this.exponent.evaluate?this.exponent.evaluate(e):this.exponent.value!==void 0?parseFloat(this.exponent.value):NaN;return isNaN(t)||isNaN(r)?NaN:Math.pow(t,r)}isSquare(){return this.exponent.value===2||this.exponent.constructor&&this.exponent.type==="omdConstantNode"&&parseFloat(this.exponent.value)===2}isCube(){return this.exponent.value===3||this.exponent.constructor&&this.exponent.type==="omdConstantNode"&&parseFloat(this.exponent.value)===3}static fromString(e){try{const t=window.math.parse(e);if(t.type!=="OperatorNode"||t.op!=="^")throw new Error("Expression is not a power operation");return new Ii(t)}catch(t){throw console.error("Failed to create power node from string:",t),t}}}class sg extends Uo{constructor(e){super(e),this.type="omdGroupNode",this.symbol=this.parseSymbol(e),this.textElement=super.createTextElement(this.symbol)}parseSymbol(e){return e}parseType(){return"parenthesis"}clone(){const e=new sg(this.text);return e.provenance.push(this.id),e}computeDimensions(){super.computeDimensions()}updateLayout(){super.updateLayout()}toMathJSNode(){const e={type:"SymbolNode",name:this.symbol};return e.clone=function(){return{...this}},e}}class Os extends Pt{constructor(e){super(e),this.type="omdParenthesisNode";const t=e.content||e.args&&e.args[0];if(!t){console.error("omdParenthesisNode requires inner content",e);return}this.open=this.createParenthesis("("),this.expression=this.createExpression(t),this.closed=this.createParenthesis(")"),this.argumentNodeList.expression=this.expression}createParenthesis(e){let t=new sg(e);return this.addChild(t),t}createExpression(e){let t=_t(e),r=new t(e);return this.addChild(r),r}computeDimensions(){this.open.computeDimensions(),this.expression.computeDimensions(),this.closed.computeDimensions();let e=4*this.getFontSize()/this.getRootFontSize(),t=this.open.width+this.expression.width+this.closed.width,r=Math.max(this.expression.height,this.closed.height,this.open.height);this.setWidthAndHeight(t,r+e)}updateLayout(){this.expression.updateLayout();const e=this.expression.getAlignmentBaseline(),r=this.getAlignmentBaseline()-e;this.expression.setPosition(this.open.width,r);const s=r+e-this.open.height/2;this.open.updateLayout(),this.open.setPosition(0,s),this.closed.updateLayout(),this.closed.setPosition(this.open.width+this.expression.width,s)}getAlignmentBaseline(){return(this.height-this.expression.height)/2+this.expression.getAlignmentBaseline()}clone(){const e={type:"ParenthesisNode",content:{type:"ConstantNode",value:1}},t=new Os(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.open=this.open.clone(),t.addChild(t.open),t.expression=this.expression.clone(),t.addChild(t.expression),t.closed=this.closed.clone(),t.addChild(t.closed),t.argumentNodeList={expression:t.expression},t.astNodeData=t.toMathJSNode(),t.provenance.push(this.id),t}isConstant(){return this.expression?this.expression.isConstant():!1}getValue(){if(!this.expression)throw new Error("Parenthesis node has no expression from which to get a value.");return this.expression.getValue()}toMathJSNode(){const e={type:"ParenthesisNode",content:this.expression.toMathJSNode(),id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return this.content&&(t.content=this.content.clone()),t},e}toString(){return`(${this.expression.toString()})`}evaluate(e={}){if(!this.expression)throw new Error("Parenthesis node has no expression to evaluate");if(this.expression.evaluate)return this.expression.evaluate(e);if(this.expression.isConstant())return this.expression.getValue();throw new Error("Cannot evaluate parenthesis content")}isNecessary(){if(!this.parent||this.expression.type==="omdConstantNode"||this.expression.type==="omdVariableNode")return!1;const e=this.parent;if(e.type==="omdFunctionNode")return!0;if(e.type==="omdPowerNode"){if(e.base===this)return this.expression.type==="omdBinaryExpressionNode";if(e.exponent===this)return!(this.expression.type==="omdConstantNode"||this.expression.type==="omdVariableNode")}return e.type==="omdBinaryExpressionNode"&&this.expression.type==="omdBinaryExpressionNode"}static fromString(e){if(!window.math)throw new Error("Math.js is required for parsing expressions");const t=e.trim();if(!t.startsWith("(")||!t.endsWith(")"))throw new Error("Expression must be enclosed in parentheses");try{const r=window.math.parse(t);if(r.type!=="ParenthesisNode")throw new Error("Parsed expression is not a parenthesis node");return new Os(r)}catch(r){throw new Error(`Failed to parse parenthesis expression: ${r.message}`)}}}class Ci extends Pt{constructor(e){var t;if(super(e),this.type="omdBinaryExpressionNode",!((t=e.args)!=null&&t.length)||e.args.length<2)throw new Error(`omdBinaryExpressionNode requires an AST node with at least 2 arguments. Received: ${JSON.stringify(e)}`);if(this.left=this.createExpressionNode(e.args[0]),this.argumentNodeList.left=this.left,this.operation=this.parseOperation(),this.op=e.implicit?null:this.createOperatorNode(e),this.isImplicit=e.implicit||!1,this.right=this.createExpressionNode(e.args[1]),this.argumentNodeList.right=this.right,this.op&&(e.op==="*"||e.op==="×"||e.fn==="multiply")){if(this._shouldReorderMultiplication(this.left,this.right)){const r=this.left;this.left=this.right,this.right=r,this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right;const i=this.astNodeData.args[0];this.astNodeData.args[0]=this.astNodeData.args[1],this.astNodeData.args[1]=i}this._shouldUseImplicitMultiplication(this.left,this.right)&&(this.removeChild(this.op),this.op=null,this.astNodeData.implicit=!0)}}parseOperation(){return this.astNodeData.fn}createExpressionNode(e){let t=_t(e),r=new t(e);return this.addChild(r),r}createOperatorNode(e){let t={type:"OperatorNode",op:e.op};e.operatorProvenance&&(t.provenance=e.operatorProvenance);let r=new ng(t);return this.addChild(r),r}computeDimensions(){var a;this.left.computeDimensions(),(a=this.op)==null||a.computeDimensions(),this.right.computeDimensions();let e=this.left.width+this.right.width+(this.op!==null?this.op.width:0),t=Math.max(this.left.height,this.right.height),r=0*this.getFontSize()/this.getRootFontSize(),i=e+this.getSpacing()*2,s=t+r;this.setWidthAndHeight(i,s)}updateLayout(){const e=this.getSpacing(),t=Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline());let r=0;if(this.left.updateLayout(),this.left.setPosition(r,t-this.left.getAlignmentBaseline()),r+=this.left.width+e,this.op!==null){const i=this.op.getAlignmentBaseline();this.op.updateLayout(),this.op.setPosition(r,t-i),r+=this.op.width+e}this.right.updateLayout(),this.right.setPosition(r,t-this.right.getAlignmentBaseline())}getAlignmentBaseline(){return this.op?Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline())-this.op.getAlignmentBaseline()+this.op.getAlignmentBaseline():Math.max(this.left.getAlignmentBaseline(),this.right.getAlignmentBaseline())}clone(){const e={type:"OperatorNode",op:"+",args:[{type:"ConstantNode",value:1},{type:"ConstantNode",value:1}]},t=new Ci(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.left=this.left.clone(),t.addChild(t.left),this.op?(t.op=this.op.clone(),t.addChild(t.op)):t.op=null,t.right=this.right.clone(),t.addChild(t.right),t.argumentNodeList={left:t.left,right:t.right},t.operation=this.operation,t.astNodeData=JSON.parse(JSON.stringify(this.astNodeData)),t.provenance.push(this.id),t}getSpacing(){return this.op===null?0:6*this.getFontSize()/this.getRootFontSize()}_shouldUseImplicitMultiplication(e,t){if(!dE())return this._isCoefficientMultiplication(e,t);const r=this._getNodeCategory(e),i=this._getNodeCategory(t),s=`${r}-${i}`;return this._getImplicitMultiplicationSetting(s)}_getImplicitMultiplicationSetting(e){const i=({"variable-constant":"constant-variable","parenthesis-constant":"constant-parenthesis"}[e]||e).replace(/-([a-z])/g,(s,a)=>a.toUpperCase());return dE(i)}_getNodeCategory(e){return e instanceof Zr&&e.isConstant()?"constant":e instanceof Zi?"variable":e instanceof Ii?"power":e instanceof Os?"parenthesis":"other"}_shouldReorderMultiplication(e,t){const r=this._getNodeCategory(e),i=this._getNodeCategory(t);return r!=="constant"&&i==="constant"}_isCoefficientMultiplication(e,t){const r=e instanceof Zr&&e.isConstant(),i=t instanceof Zi||t instanceof Ii||t instanceof Os;return r&&i}toMathJSNode(){const e={type:"OperatorNode",op:this.op?this.op.opName:"*",fn:this.operation,args:[this.left.toMathJSNode(),this.right.toMathJSNode()],implicit:!this.op,id:this.id,provenance:this.provenance};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),t},e}toString(){const e=this.left.toString(),t=this.right.toString(),r=this.op?` ${this.op.toString()} `:"";if(!this.op)return`${e}${t}`;const i=this.left.needsParentheses&&this.left.needsParentheses(this.op.value)?`(${e})`:e,s=this.right.needsParentheses&&this.right.needsParentheses(this.op.value)?`(${t})`:t;return`${i}${r}${s}`}evaluate(e={}){const t={add:(a,o)=>a+o,subtract:(a,o)=>a-o,multiply:(a,o)=>a*o,divide:(a,o)=>{if(o===0)throw new Error("Division by zero.");return a/o}},r=this.left.evaluate(e),i=this.right.evaluate(e);if(this.isImplicit)return r*i;const s=t[this.operation];if(s)return s(r,i);throw new Error(`Unsupported operation for evaluation: ${this.operation}`)}needsParentheses(){const e=this.parent;if(!e||!(e instanceof Ci))return!1;const t=this.op?this.op.opName:"*",r=e.op?e.op.opName:"*",i={"+":1,"-":1,"*":2,"×":2,"/":2,"÷":2,"^":3},s=i[t]||0,a=i[r]||0;return s<a||s===a&&e.right===this&&(t==="-"||t==="/"||t==="÷")}getFunctionForOperator(e){return{"+":"add","-":"subtract","*":"multiply","×":"multiply","/":"divide","÷":"divide"}[e]||"unknown"}setHighlight(e=!0,t=omdColor.highlightColor){this.isExplainHighlighted||(super.setHighlight(e,t),this.left&&typeof this.left.setHighlight=="function"&&this.left.setHighlight(e,t),this.op&&typeof this.op.setHighlight=="function"&&this.op.setHighlight(e,t),this.right&&typeof this.right.setHighlight=="function"&&this.right.setHighlight(e,t))}clearProvenanceHighlights(){super.clearProvenanceHighlights(),this.left&&typeof this.left.clearProvenanceHighlights=="function"&&this.left.clearProvenanceHighlights(),this.op&&typeof this.op.clearProvenanceHighlights=="function"&&this.op.clearProvenanceHighlights(),this.right&&typeof this.right.clearProvenanceHighlights=="function"&&this.right.clearProvenanceHighlights()}}class Wo extends Pt{constructor(e){var t;super(e),this.type="omdFunctionNode",this.functionName=((t=e.fn)==null?void 0:t.name)||e.name||"f",this.args=e.args||[],this.createTextElements(),this.createArgumentNodes(),this.computeDimensions(),this.updateLayout()}createTextElements(){const e=t=>{const r=new si;return r.setText(t),r.setTextAnchor("start"),r.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(r),r};this.functionNameElement=e(this.functionName),this.openParenElement=e("("),this.closeParenElement=e(")")}createArgumentNodes(){this.argNodes=[],this.commaElements=[],this.argumentNodeList.args=[],this.args.forEach((e,t)=>{const r=_t(e),i=new r(e);if(this.argNodes.push(i),this.addChild(i),this.argumentNodeList.args.push(i),t<this.args.length-1){const s=new si;s.setText(", "),s.setTextAnchor("start"),s.svgObject.setAttribute("dominant-baseline","middle"),this.commaElements.push(s),this.addChild(s)}})}computeDimensions(){const e=this.getFontSize(),t=e*5/6;this.functionNameElement.setFontSize(e),this.openParenElement.setFontSize(e),this.closeParenElement.setFontSize(e),this.argNodes.forEach(p=>{p.setFontSize(t),p.computeDimensions()}),this.commaElements.forEach(p=>{p.setFontSize(t)});const r=e/this.getRootFontSize(),i=2*r,s=2*r,a=Jn(this.functionName,e),o=Jn("(",e),l=Jn(")",e),u=Jn(", ",t);let c=0,h=0;this.argNodes.forEach((p,m)=>{c+=p.width,h=Math.max(h,p.height),m<this.commaElements.length&&(c+=u.width+i)});const f=a.width+s+o.width+c+l.width+i*2,d=Math.max(h,a.height,o.height,l.height)+4*r;this.setWidthAndHeight(f,d)}updateLayout(){const e=this.getFontSize(),t=e*5/6,r=e/this.getRootFontSize(),i=2*r,s=2*r;let a=0;const o=this.height/2;this.functionNameElement.setPosition(a,o),a+=Jn(this.functionName,e).width,a+=s,this.openParenElement.setPosition(a,o),a+=Jn("(",e).width,this.argNodes.forEach((l,u)=>{l.setPosition(a,(this.height-l.height)/2),l.updateLayout(),a+=l.width,u<this.commaElements.length&&(a+=i,this.commaElements[u].setPosition(a,o),a+=Jn(", ",t).width+i)}),this.closeParenElement.setPosition(a,o)}highlightAll(){this.select(),this.argNodes.forEach(e=>{e.highlightAll&&e.highlightAll()})}unhighlightAll(){this.deselect(),this.argNodes.forEach(e=>{e.unhighlightAll&&e.unhighlightAll()})}clone(){let e;typeof this.astNodeData.clone=="function"?e=this.astNodeData.clone():e=JSON.parse(JSON.stringify(this.astNodeData));const t=new Wo(e),r=t.backRect;return t.removeAllChildren(),t.addChild(r),t.functionName=this.functionName,t.args=JSON.parse(JSON.stringify(this.args)),t.createTextElements(),t.argNodes=this.argNodes.map(i=>i.clone()),t.argNodes.forEach(i=>{i.parent=t,t.addChild(i)}),t.argumentNodeList.args=t.argNodes,t.commaElements=this.commaElements.map(i=>{const s=new si;return s.setText(i.text),s.setTextAnchor(i.textAnchor),s.svgObject.setAttribute("dominant-baseline",i.svgObject.getAttribute("dominant-baseline")),s.parent=t,t.addChild(s),s}),t.addChild(t.closedParen),t.argumentNodeList.args=t.args,t.provenance.push(this.id),t}toMathJSNode(){const e={type:"FunctionNode",fn:{type:"SymbolNode",name:this.functionName,clone:function(){return{...this}}},args:this.argNodes.map(t=>t.toMathJSNode())};return e.clone=function(){const t={...this};return t.args=this.args.map(r=>r.clone()),this.fn&&typeof this.fn.clone=="function"&&(t.fn=this.fn.clone()),t},e}toString(){const e=this.argNodes.map(t=>t.toString());return`${this.functionName}(${e.join(", ")})`}evaluate(e={}){const t=this.argNodes.map(r=>{if(r.evaluate)return r.evaluate(e);if(r.type==="omdConstantNode")return parseFloat(r.value);if(r.type==="omdVariableNode"&&e[r.name]!==void 0)return e[r.name];throw new Error(`Cannot evaluate argument: ${r.toString()}`)});if(window.math&&window.math[this.functionName])try{return window.math[this.functionName](...t)}catch(r){throw new Error(`Error evaluating ${this.functionName}: ${r.message}`)}switch(this.functionName){case"sin":return Math.sin(t[0]);case"cos":return Math.cos(t[0]);case"tan":return Math.tan(t[0]);case"asin":return Math.asin(t[0]);case"acos":return Math.acos(t[0]);case"atan":return Math.atan(t[0]);case"sqrt":return Math.sqrt(t[0]);case"abs":return Math.abs(t[0]);case"log":return Math.log(t[0]);case"log10":return Math.log10(t[0]);case"exp":return Math.exp(t[0]);case"pow":return Math.pow(t[0],t[1]);case"min":return Math.min(...t);case"max":return Math.max(...t);case"floor":return Math.floor(t[0]);case"ceil":return Math.ceil(t[0]);case"round":return Math.round(t[0]);default:throw new Error(`Unknown function: ${this.functionName}`)}}static fromString(e){if(!window.math)throw new Error("Math.js is required for parsing function strings");try{const t=window.math.parse(e);if(t.type!=="FunctionNode")throw new Error("String does not represent a function call");return new Wo(t)}catch(t){throw new Error(`Failed to parse function string: ${t.message}`)}}}class ut extends Pt{constructor(e){if(super(e),this.type="omdEquationNode",(e.type||e.mathjs)==="AssignmentNode"){const r=_t(e.object);this.left=new r(e.object);const i=_t(e.value);this.right=new i(e.value),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right}else if(e.args&&e.args.length===2){const r=_t(e.args[0]);this.left=new r(e.args[0]);const i=_t(e.args[1]);this.right=new i(e.args[1]),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right}else this.left=new Pt({type:"SymbolNode",name:"error"}),this.right=new Pt({type:"SymbolNode",name:"error"}),this.argumentNodeList.left=this.left,this.argumentNodeList.right=this.right;this.equalsSign=new ng({type:"OperatorNode",op:"="}),this.addChild(this.left),this.addChild(this.equalsSign),this.addChild(this.right),this._backgroundStyle=null,this._propagateBackgroundStyle(this._backgroundStyle)}computeDimensions(){this.left.computeDimensions(),this.equalsSign.computeDimensions(),this.right.computeDimensions();const e=8*this.getFontSize()/this.getRootFontSize();let t=this.left.width+this.equalsSign.width+this.right.width+e*2;const r=Math.max(this.left.height,this.equalsSign.height,this.right.height),{padX:i,padY:s}=this._getEffectivePadding(r),a=r+s*2;t+=i*2,this.setWidthAndHeight(t,a)}updateLayout(){this.argumentNodeList={left:this.left,right:this.right};const e=8*this.getFontSize()/this.getRootFontSize(),t=Math.max(this.left.getAlignmentBaseline(),this.equalsSign.getAlignmentBaseline(),this.right.getAlignmentBaseline()),r=Math.max(this.left.height,this.equalsSign.height,this.right.height);let{padX:i,padY:s}=this._getEffectivePadding(r),a=i;if(this.left.updateLayout(),this.left.setPosition(a,s+(t-this.left.getAlignmentBaseline())),a+=this.left.width+e,this.equalsSign.updateLayout(),this.equalsSign.setPosition(a,s+(t-this.equalsSign.getAlignmentBaseline())),a+=this.equalsSign.width+e,this.right.updateLayout(),this.right.setPosition(a,s+(t-this.right.getAlignmentBaseline())),this.computeDimensions(),this._backgroundStyle){const{backgroundColor:f,cornerRadius:d,pill:p}=this._backgroundStyle;if(f&&(this.backRect.setFillColor(f),this.backRect.setOpacity(1),this.defaultOpaqueBack=!0),p===!0){const m=Math.max(0,Math.floor(this.height/2));this.backRect.setCornerRadius(m),this._applyPillToDescendants()}else typeof d=="number"&&this.backRect.setCornerRadius(d);f&&this._matchChildBackgrounds(f)}this.backRect&&(this.width||this.height)&&this.backRect.setWidthAndHeight(this.width,this.height);const o=Math.min(this.left.ypos,this.equalsSign.ypos,this.right.ypos),l=Math.max(this.left.ypos+this.left.height,this.equalsSign.ypos+this.equalsSign.height,this.right.ypos+this.right.height),u=o,c=Math.max(0,(this.height||0)-l);let h=(u-c)/2-.06*this.getFontSize();Math.abs(h)>.01&&(this.left.setPosition(this.left.xpos,this.left.ypos-h),this.equalsSign.setPosition(this.equalsSign.xpos,this.equalsSign.ypos-h),this.right.setPosition(this.right.xpos,this.right.ypos-h))}_getEffectivePadding(e){var l,u;const t=this.getFontSize()/this.getRootFontSize(),r=2*t,i=2*t,s=(l=this._backgroundStyle)==null?void 0:l.padding;let a=(typeof s=="number"?s:s==null?void 0:s.x)??r,o=(typeof s=="number"?s:s==null?void 0:s.y)??i;if(((u=this._backgroundStyle)==null?void 0:u.pill)===!0){const c=Math.ceil((e+2*o)/2);a<c&&(a=c)}return{padX:a,padY:o}}_propagateBackgroundStyle(e,t=new Set){if(t.has(this))return;t.add(this),this._backgroundStyle=e;function r(i,s,a){if(!(!i||a.has(i))){if(a.add(i),i._propagateBackgroundStyle){i._propagateBackgroundStyle(s,a);return}if(i._backgroundStyle=s,Array.isArray(i.childList))for(const o of i.childList)r(o,s,a);if(i.argumentNodeList)for(const o of Object.values(i.argumentNodeList))if(Array.isArray(o))for(const l of o)r(l,s,a);else r(o,s,a)}}if(Array.isArray(this.childList))for(const i of this.childList)r(i,e,t);if(this.argumentNodeList&&typeof this.argumentNodeList=="object")for(const i of Object.values(this.argumentNodeList))if(Array.isArray(i))for(const s of i)r(s,e,t);else r(i,e,t)}_applyPillToDescendants(){const e=new Set,t=Array.isArray(this.childList)?[...this.childList]:[];for(;t.length;){const r=t.pop();if(!(!r||e.has(r))){if(e.add(r),r!==this&&r.backRect&&typeof r.backRect.setCornerRadius=="function"){const i=typeof r.height=="number"&&r.height>0?r.height:0,s=Math.max(0,Math.floor(i/2));r.backRect.setCornerRadius(s)}if(Array.isArray(r.childList))for(const i of r.childList)t.push(i);if(r.argumentNodeList&&typeof r.argumentNodeList=="object")for(const i of Object.values(r.argumentNodeList))Array.isArray(i)?i.forEach(s=>s&&t.push(s)):i&&t.push(i)}}}_createNodeFromValue(e){if(typeof e=="number"){const t=new Zr({value:e});return t.initialize(),t}if(typeof e=="object"&&e!==null){const t=_t(e),r=new t(e);return typeof r.initialize=="function"&&r.initialize(),r}return null}_applyOperation(e,t,r){const i=this._createNodeFromValue(e);if(!i)return this;const s=this._needsParenthesesForOperation(this.left,t),a=this._needsParenthesesForOperation(this.right,t),o=s?{type:"ParenthesisNode",content:this.left.toMathJSNode()}:this.left.toMathJSNode(),l=a?{type:"ParenthesisNode",content:this.right.toMathJSNode()}:this.right.toMathJSNode(),u={type:"OperatorNode",op:t,fn:r,args:[o,i.toMathJSNode()]},c={type:"OperatorNode",op:t,fn:r,args:[l,i.toMathJSNode()]};let h,f;t==="/"?(h=new Hr(u),f=new Hr(c)):(h=new Ci(u),f=new Ci(c));const d={type:"AssignmentNode",object:h.toMathJSNode(),index:null,value:f.toMathJSNode()},p=new ut(d);return p.setFontSize(this.getFontSize()),p.provenance.push(this.id),p.left&&this.left&&this._establishGranularProvenance(p.left,this.left,e,r),p.right&&this.right&&this._establishGranularProvenance(p.right,this.right,e,r),p.initialize(),p}_needsParenthesesForOperation(e,t){if(!e||e.type!=="omdBinaryExpressionNode")return!1;const r={"+":1,"-":1,"*":2,"/":2,"^":3};let i=e.operation;typeof i=="object"&&i&&i.name&&(i=i.name),e.astNodeData&&e.astNodeData.op&&(i=e.astNodeData.op);const s={add:"+",subtract:"-",multiply:"*",divide:"/",pow:"^"},a=s[i]||i,o=s[t]||t;return!r[a]||!r[o]?!0:r[a]<r[o]}addToBothSides(e){return this._applyOperation(e,"+","add")}subtractFromBothSides(e){return this._applyOperation(e,"-","subtract")}multiplyBothSides(e,t){return this._applyOperation(e,"*","multiply",t)}divideBothSides(e){return this._applyOperation(e,"/","divide")}_establishGranularProvenance(e,t,r,i){if(!(!e||!t))if(e.provenance||(e.provenance=[]),i==="divide")if(t.type==="omdBinaryExpressionNode"&&this._isMultiplicationOperation(t)){const s=t.left.isConstant(),a=t.right.isConstant(),o=typeof r=="object"&&r.getValue?r.getValue():r;s&&t.left.getValue()===o?this._copyProvenanceStructure(e,t.right):a&&t.right.getValue()===o?this._copyProvenanceStructure(e,t.left):this._copyProvenanceStructure(e,t)}else this._copyProvenanceStructure(e,t);else i==="multiply"?(this._copyProvenanceStructure(e,t),e.type==="omdBinaryExpressionNode"&&e.left&&this._copyProvenanceStructure(e.left,t)):i==="add"||i==="subtract"?(e.provenance.push(t.id),e.type==="omdBinaryExpressionNode"&&e.left&&this._copyProvenanceStructure(e.left,t)):this._copyProvenanceStructure(e,t)}_isMultiplicationOperation(e){if(e.type!=="omdBinaryExpressionNode")return!1;const t=e.operation;return t==="multiply"||typeof t=="object"&&t&&t.name==="multiply"||e.op&&e.op.opName==="*"}_copyProvenanceStructure(e,t){if(!(!e||!t)){if(e.provenance||(e.provenance=[]),t.provenance&&t.provenance.length>0){const r=new Set(e.provenance);t.provenance.forEach(i=>{r.has(i)||(r.add(i),e.provenance.push(i))})}if(e.provenance.includes(t.id)||e.provenance.push(t.id),e.type===t.type&&e.argumentNodeList&&t.argumentNodeList)for(const r of Object.keys(t.argumentNodeList)){const i=e.argumentNodeList[r],s=t.argumentNodeList[r];if(i&&s)if(Array.isArray(i)&&Array.isArray(s))for(let a=0;a<Math.min(i.length,s.length);a++)i[a]&&s[a]&&this._copyProvenanceStructure(i[a],s[a]);else this._copyProvenanceStructure(i,s)}}}static fromString(e){if(!e.includes("="))throw new Error("Input string is not a valid equation.");const t=e.split("=");if(t.length>2)throw new Error("Equation can only have one '=' sign.");const r=t[0].trim(),i=t[1].trim();if(!r||!i)throw new Error("Equation must have a left and a right side.");const s={type:"AssignmentNode",object:math.parse(r),value:math.parse(i),clone:function(){return{type:this.type,object:this.object.clone(),value:this.value.clone(),clone:this.clone}}};return new ut(s)}clone(){const e=JSON.parse(JSON.stringify(this.astNodeData)),t=new ut(e);return t._syncProvenanceFrom(this),t.setFontSize(this.getFontSize()),t.argumentNodeList={left:t.left,right:t.right},t}deselect(e){e instanceof Pt||(e=this),this===e&&this.parent instanceof Pt&&this.parent.select(e),this.backRect.setFillColor(omdColor.lightGray),this.defaultOpaqueBack==!1&&this.backRect.setOpacity(.01),this.childList.forEach(t=>{t!==e&&t instanceof Pt&&t.deselect(e)})}toMathJSNode(){let e;return this.astNodeData.type==="AssignmentNode"?e={type:"AssignmentNode",object:this.left.toMathJSNode(),value:this.right.toMathJSNode(),id:this.id,provenance:this.provenance}:e={type:"OperatorNode",op:"=",fn:"equal",args:[this.left.toMathJSNode(),this.right.toMathJSNode()],id:this.id,provenance:this.provenance},e.clone=function(){const t={...this};return this.object&&(t.object=this.object.clone()),this.value&&(t.value=this.value.clone()),this.args&&(t.args=this.args.map(r=>r.clone())),t},e}applyFunction(e){const t=this._createFunctionNode(e,this.left),r=this._createFunctionNode(e,this.right),i=this._createNewEquation(t,r);return i.provenance.push(this.id),i}_createFunctionNode(e,t){const r={type:"FunctionNode",fn:{type:"SymbolNode",name:e},args:[t.toMathJSNode()]},i=_t(r),s=new i(r);return s.setFontSize(this.getFontSize()),s}_createNewEquation(e,t){const r={type:"AssignmentNode",object:e.toMathJSNode(),value:t.toMathJSNode(),clone:function(){return{type:this.type,object:this.object.clone(),value:this.value.clone(),clone:this.clone}}};return new ut(r)}applyOperation(e,t,r="both"){const s={add:{op:"+",fn:"add"},subtract:{op:"-",fn:"subtract"},multiply:{op:"*",fn:"multiply"},divide:{op:"/",fn:"divide"}}[t];if(!s)throw new Error(`Unknown operation: ${t}`);if(r==="both")return this._applyOperation(e,s.op,s.fn);const a=this._createNodeFromValue(e);if(!a)throw new Error("Invalid value provided");let o,l;if(r==="left"){const p=this._needsParenthesesForOperation(this.left,s.op)?{type:"ParenthesisNode",content:this.left.toMathJSNode()}:this.left.toMathJSNode();o={type:"OperatorNode",op:s.op,fn:s.fn,args:[p,a.toMathJSNode()]},l=this.right.toMathJSNode()}else if(r==="right"){const p=this._needsParenthesesForOperation(this.right,s.op)?{type:"ParenthesisNode",content:this.right.toMathJSNode()}:this.right.toMathJSNode();o=this.left.toMathJSNode(),l={type:"OperatorNode",op:s.op,fn:s.fn,args:[p,a.toMathJSNode()]}}else throw new Error(`Invalid side: ${r}. Must be 'left', 'right', or 'both'`);let u,c;r==="left"&&s.op==="/"?(u=new Hr(o),c=_t(l)===Pt?this.right:new(_t(l))(l)):r==="right"&&s.op==="/"?(u=_t(o)===Pt?this.left:new(_t(o))(o),c=new Hr(l)):r==="left"?(u=new Ci(o),c=_t(l)===Pt?this.right:new(_t(l))(l)):(u=_t(o)===Pt?this.left:new(_t(o))(o),c=new Ci(l));const h={type:"AssignmentNode",object:u.toMathJSNode(),value:c.toMathJSNode()},f=new ut(h);return f.setFontSize(this.getFontSize()),f.provenance.push(this.id),f.initialize(),f}swapSides(){const e=this.clone();return[e.left,e.right]=[e.right,e.left],[e.astNodeData.object,e.astNodeData.value]=[e.astNodeData.value,e.astNodeData.object],e.provenance.push(this.id),e.initialize(),e}toString(){return`${this.left.toString()} = ${this.right.toString()}`}setBackgroundStyle(e={}){this._backgroundStyle={...this._backgroundStyle||{},...e},this._propagateBackgroundStyle(this._backgroundStyle),this.backRect&&(this.width||this.height)&&this.updateLayout()}getEqualsAnchorX(){var i,s,a,o;const e=8*this.getFontSize()/this.getRootFontSize(),t=Math.max(((i=this.left)==null?void 0:i.height)||0,((s=this.equalsSign)==null?void 0:s.height)||0,((a=this.right)==null?void 0:a.height)||0),{padX:r}=this._getEffectivePadding(t);return r+this.left.width+e+(((o=this.equalsSign)==null?void 0:o.width)||0)/2}getBackgroundPaddingX(){var t;const e=(t=this._backgroundStyle)==null?void 0:t.padding;return e==null?0:typeof e=="number"?e:e.x??0}getEffectiveBackgroundPaddingX(){var r,i,s;const e=Math.max(((r=this.left)==null?void 0:r.height)||0,((i=this.equalsSign)==null?void 0:i.height)||0,((s=this.right)==null?void 0:s.height)||0),{padX:t}=this._getEffectivePadding(e);return t}_matchChildBackgrounds(e){const t=new Set,r=Array.isArray(this.childList)?[...this.childList]:[];for(;r.length;){const i=r.pop();if(!(!i||t.has(i))){if(t.add(i),i!==this&&i.backRect&&(i.backRect.setFillColor(e),i.backRect.setOpacity(1)),Array.isArray(i.childList))for(const s of i.childList)r.push(s);if(i.argumentNodeList&&typeof i.argumentNodeList=="object")for(const s of Object.values(i.argumentNodeList))Array.isArray(s)?s.forEach(a=>a&&r.push(a)):s&&r.push(s)}}}evaluate(e={}){const t=this.left.evaluate(e),r=this.right.evaluate(e);return{left:t,right:r}}renderTo(e,t={}){const i={...{side:"both",xMin:-10,xMax:10,yMin:-10,yMax:10,stepSize:1},...t};switch(e.toLowerCase()){case"graph":return this._renderToGraph(i);case"table":return this._renderToTable(i);case"hanger":return this._renderToHanger(i);case"tileequation":{const s=this.getLeft().toString(),a=this.getRight().toString(),o=`${s}=${a}`,l=i.plusColor||"#79BBFD",u=i.equalsColor||"#FF6B6B",c=i.xPillColor,h=i.tileBackgroundColor,f=i.dotColor,d=i.tileSize||28,p=i.dotsPerColumn||10;return{omdType:"tileEquation",equation:o,tileSize:d,dotsPerColumn:p,plusColor:l,equalsColor:u,xPill:c?{color:c}:void 0,numberTileDefaults:{backgroundColor:h,dotColor:f}}}default:throw new Error(`Unknown visualization type: ${e}. Supported types are: graph, table, hanger`)}}getLeft(){return this.left}getRight(){return this.right}_renderToGraph(e){const t=this._normalizeExpressionString(this.getLeft().toString()),r=this._normalizeExpressionString(this.getRight().toString());let i=[];const s=a=>a.trim().toLowerCase()==="y";if(e.side==="left")s(t)||i.push({equation:`y = ${t}`,domain:{min:e.xMin,max:e.xMax},color:"blue",strokeWidth:2});else if(e.side==="right")s(r)||i.push({equation:`y = ${r}`,domain:{min:e.xMin,max:e.xMax},color:"red",strokeWidth:2});else if(s(t)||i.push({equation:`y = ${t}`,domain:{min:e.xMin,max:e.xMax},color:"blue",strokeWidth:2}),!s(r)){const a=s(t)?"blue":"red";i.push({equation:`y = ${r}`,domain:{min:e.xMin,max:e.xMax},color:a,strokeWidth:2})}return{omdType:"coordinatePlane",xMin:e.xMin,xMax:e.xMax,yMin:e.yMin,yMax:e.yMax,xLabel:e.xLabel!==void 0?e.xLabel:"x",yLabel:e.yLabel!==void 0?e.yLabel:"y",size:e.size!==void 0?e.size:"medium",tickInterval:e.tickInterval!==void 0?e.tickInterval:1,forceAllTickLabels:e.forceAllTickLabels!==void 0?e.forceAllTickLabels:!0,showTickLabels:e.showTickLabels!==void 0?e.showTickLabels:!0,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,graphEquations:i,lineSegments:[],dotValues:[],shapeSet:[]}}_renderToTable(e){const t=p=>{const m=this._normalizeExpressionString(p);return/^[a-zA-Z]\s*=/.test(m)?m:`y = ${m}`};if(e.side==="left"){const p=this._normalizeExpressionString(this.getLeft().toString()),m=t(p);return{omdType:"table",title:`Function Table: ${m}`,headers:["x","y"],equation:m,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}else if(e.side==="right"){const p=this._normalizeExpressionString(this.getRight().toString()),m=t(p);return{omdType:"table",title:`Function Table: ${m}`,headers:["x","y"],equation:m,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}const r=this._normalizeExpressionString(this.getLeft().toString()),i=this._normalizeExpressionString(this.getRight().toString());if(r.toLowerCase().trim()==="y"){const p=t(i);return{omdType:"table",title:`Function Table: ${p}`,headers:["x","y"],equation:p,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}if(i.toLowerCase().trim()==="y"){const p=t(r);return{omdType:"table",title:`Function Table: ${p}`,headers:["x","y"],equation:p,xMin:e.xMin,xMax:e.xMax,stepSize:e.stepSize,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}const s=this.getLeft(),a=this.getRight(),o=s.toString(),l=a.toString(),u=["x",o,l],c=[],h=e.xMin,f=e.xMax,d=e.stepSize||1;for(let p=h;p<=f;p+=d)try{const m=s.evaluate({x:p}),y=a.evaluate({x:p});isFinite(m)&&isFinite(y)&&c.push([p,Number(m),Number(y)])}catch{}return{omdType:"table",title:`Equation Table: ${this.toString()}`,headers:u,data:c,backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0,alternatingRowColors:e.alternatingRowColors!==void 0?e.alternatingRowColors:void 0,evenRowColor:e.evenRowColor!==void 0?e.evenRowColor:void 0,oddRowColor:e.oddRowColor!==void 0?e.oddRowColor:void 0,alternatingRowOpacity:e.alternatingRowOpacity!==void 0?e.alternatingRowOpacity:void 0}}_renderSingleSideTable(e,t,r={}){const i=this._normalizeExpressionString(e.toString());return{omdType:"table",title:`${t}: ${i}`,headers:["x","y"],equation:`y = ${i}`,xMin:r.xMin??-5,xMax:r.xMax??5,stepSize:r.stepSize??1}}_renderToHanger(e={}){const t=this._convertToHangerValues(this.getLeft()),r=this._convertToHangerValues(this.getRight());return{omdType:"balanceHanger",leftValues:t,rightValues:r,tilt:"none",backgroundColor:e.backgroundColor!==void 0?e.backgroundColor:void 0,backgroundCornerRadius:e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:void 0,backgroundOpacity:e.backgroundOpacity!==void 0?e.backgroundOpacity:void 0,showBackground:e.showBackground!==void 0?e.showBackground:void 0}}_normalizeExpressionString(e){return!e||typeof e!="string"?String(e||""):e.replace(/(\d)([a-zA-Z])/g,"$1*$2").replace(/([a-zA-Z])(\d)/g,"$1*$2")}_convertToHangerValues(e){const t=[];if(e.type==="omdConstantNode"){const r=e.getValue();r!==0&&t.push(r)}else if(e.type==="omdVariableNode")t.push(e.name||"x");else if(e.type==="omdBinaryExpressionNode"){const r=this._convertToHangerValues(e.left),i=this._convertToHangerValues(e.right);if(e.operation==="add"||e.operation==="plus")t.push(...r,...i);else if(e.operation==="subtract"||e.operation==="minus"){t.push(...r);for(const s of i)typeof s=="number"?t.push(-s):t.push(`-${s}`)}else if(e.operation==="multiply")if(e.left.type==="omdConstantNode"&&e.right.type==="omdVariableNode"){const s=Math.abs(e.left.getValue()),a=e.right.name||"x";for(let o=0;o<s;o++)t.push(a)}else if(e.right.type==="omdConstantNode"&&e.left.type==="omdVariableNode"){const s=Math.abs(e.right.getValue()),a=e.left.name||"x";for(let o=0;o<s;o++)t.push(a)}else t.push(e.toString());else t.push(e.toString())}else t.push(e.toString());return t}}function Lq(n,e){var t,r;switch(n){case"AssignmentNode":return ut;case"OperatorNode":return(e==null?void 0:e.op)==="-"&&e.args.length===1&&!e.implicit?Qi:(e==null?void 0:e.op)==="="?ut:(e==null?void 0:e.op)==="^"?Ii:(e==null?void 0:e.op)==="/"?Hr:Ci;case"ParenthesisNode":return Os;case"ConstantNode":return Zr;case"SymbolNode":return Zi;case"FunctionNode":return(((t=e==null?void 0:e.fn)==null?void 0:t.name)==="multiply"||(e==null?void 0:e.name)==="multiply")&&e.implicit?Ci:((r=e==null?void 0:e.fn)==null?void 0:r.name)==="sqrt"||(e==null?void 0:e.name)==="sqrt"?Fs:Wo;default:return Pt}}function _t(n){let e=n.type;return n.mathjs&&(e=n.mathjs),Lq(e,n)}function Jn(n,e){const t=document.createElement("span");t.style.visibility="hidden",t.style.position="absolute",t.style.whiteSpace="nowrap",t.style.fontFamily="Albert Sans",t.style.fontSize=`${e||16}px`,t.textContent=n,document.body.appendChild(t);const r=t.offsetWidth,i=t.offsetHeight;return document.body.removeChild(t),{width:r,height:i}}const Zo=class Zo extends Pt{constructor(e,t){super({}),this.operation=e,this.value=t,this.type="omdOperationDisplayNode",this._initializeDisplay(),this._createOperationElements(),this._disableAllInteractions(),this._addChildElements()}_initializeDisplay(){this.hideBackgroundByDefault(),this.backRect&&(this.backRect.setOpacity(0),this.backRect.setFillColor("transparent")),this._makeNodeNonHighlightable()}_createOperationElements(){const t=`${this._getOperatorSymbol(this.operation)}${this._valueToString(this.value)}`;this.leftToken=new Zi(t),this.rightToken=new Zi(t),typeof this.leftToken.initialize=="function"&&this.leftToken.initialize(),typeof this.rightToken.initialize=="function"&&this.rightToken.initialize();const r=typeof this.getFontSize=="function"?this.getFontSize():null;r&&typeof this.leftToken.setFontSize=="function"&&this.leftToken.setFontSize(r),r&&typeof this.rightToken.setFontSize=="function"&&this.rightToken.setFontSize(r),[this.leftToken,this.rightToken].forEach(i=>{this._disableHighlighting(i)})}_disableAllInteractions(){[this.leftToken,this.rightToken].forEach(e=>{this._disableElement(e)})}_addChildElements(){this.addChild(this.leftToken),this.addChild(this.rightToken)}_getOperatorSymbol(e){return Zo.OPERATOR_SYMBOLS[e]||""}_createValueElement(e){return new Zi(this._valueToString(e))}_valueToString(e){if(e instanceof Pt)return e.toString();if(typeof e=="object"&&e!==null)try{const t=_t(e),r=new t(e);return typeof r.initialize=="function"&&r.initialize(),r.toString()}catch{return String(e??"")}return String(e??"")}_disableElement(e){e&&(this._hideElementBackground(e),this._disableMouseInteractions(e),this._disableHighlighting(e),this._disableChildElements(e))}_hideElementBackground(e){e.backRect&&(e.hideBackgroundByDefault(),e.backRect.setOpacity(0))}_disableMouseInteractions(e){e.svgObject&&(e.svgObject.onmouseenter=null,e.svgObject.onmouseleave=null,e.svgObject.style.cursor="default")}_disableHighlighting(e){e.setHighlight=()=>{},e.lowlight=()=>{},e.setFillColor=()=>{},e.backRect&&(e.backRect.setOpacity(0),e.backRect.setFillColor("transparent"),e.backRect.setFillColor=()=>{},e.backRect.setOpacity=()=>{})}_makeNodeNonHighlightable(){this.setHighlight=()=>{},this.lowlight=()=>{},this.setFillColor=()=>{},this.backRect&&(this.backRect.setOpacity(0),this.backRect.setFillColor("transparent"),this.backRect.setFillColor=()=>{},this.backRect.setOpacity=()=>{})}_disableChildElements(e){e.childList&&e.childList.forEach(r=>this._disableElement(r)),["left","right","base","exponent","argument","expression","numerator","denominator"].forEach(r=>{e[r]&&this._disableElement(e[r])})}computeDimensions(){this.leftToken&&typeof this.leftToken.updateLayout=="function"&&this.leftToken.updateLayout(),this.rightToken&&typeof this.rightToken.updateLayout=="function"&&this.rightToken.updateLayout();const e=this.leftToken?this.leftToken.width:0,t=this.rightToken?this.rightToken.width:0,r=typeof this.gap=="number"?this.gap:45;this.gap=r,this.leftClusterWidth=e;const i=Math.max(this.leftToken?this.leftToken.height:0,this.rightToken?this.rightToken.height:0),s=6,a=e+r+t,o=i+s*2;this.setWidthAndHeight(a,o)}updateLayout(){[this.leftToken,this.rightToken].forEach(i=>{i.updateLayout()}),this.computeDimensions();const e=this.gap||30,t=this.leftToken.width;let r=0;this.leftToken.setPosition(r,(this.height-this.leftToken.height)/2),r=t+e,this.rightToken.setPosition(r,(this.height-this.rightToken.height)/2),this.rightToken.show(),this._makeNodeNonHighlightable(),super.updateLayout()}getLeftWidthForAlignment(){return typeof this.leftClusterWidth!="number"&&this.computeDimensions(),this.leftClusterWidth||0}showLeftOnly(){this.rightToken.hide();const e=this.leftToken.width,t=typeof this.getFontSize=="function"?this.getFontSize():32,r=this.leftToken.height,i=Math.ceil(t*.35);this.setWidthAndHeight(e,r+i*2),this.leftToken.setPosition(0,(this.height-this.leftToken.height)/2)}clone(){const e=new Zo(this.operation,this.value);return e.provenance.push(this.id),e._makeNodeNonHighlightable(),e}};eu(Zo,"OPERATOR_SYMBOLS",{add:"+",subtract:"-",multiply:"×",divide:"÷"});let Bs=Zo;const es=class es extends Pt{setAlignmentMode(e){e!=="equals"&&e!=="center"?(console.warn(`Invalid alignment mode: ${e}. Using 'equals'.`),this.alignmentMode="equals"):this.alignmentMode=e,this.steps&&this.steps.length>0&&this.updateLayout()}getAlignmentMode(){return this.alignmentMode||"equals"}setFilterLevel(e=0){this.currentFilterLevels=[e],this.updateStepsVisibility(t=>(t.stepMark??0)===e)}setFilterLevels(e=[0]){this.currentFilterLevels=[...e],this.updateStepsVisibility(t=>{const r=t.stepMark??0;return e.includes(r)})}_reapplyCurrentFilter(){this.currentFilterLevels&&this.currentFilterLevels.length>0&&this.updateStepsVisibility(e=>{const t=e.stepMark??0;return this.currentFilterLevels.includes(t)})}getFilterLevel(){return 0}constructor(e){super({}),this.type="omdEquationSequenceNode",this.steps=e,this.argumentNodeList.steps=this.steps,this.steps.forEach(t=>this.addChild(t)),this._initializeState(),this._initializeLayout(),this._initializeNodeMap(),this._disableContainerInteractions(),this._markInitialSteps(),this._applyDefaultFilter(),this.defaultEquationBackground=null}_initializeState(){this.currentStepIndex=0,this.stepDescriptions=[],this.importanceLevels=[],this.simplificationHistory=[],this.currentFilterLevels=[0]}_initializeLayout(){this.hideBackgroundByDefault(),this.layoutHelper=new qr,this.layoutHelper.setSpacer(15),this.alignmentMode="equals"}_initializeNodeMap(){this.nodeMap=new Map,this.rebuildNodeMap()}_disableContainerInteractions(){this.svgObject.onmouseenter=null,this.svgObject.onmouseleave=null,this.svgObject.style.cursor="default",this.svgObject.onclick=null}_markInitialSteps(){!this.steps||!Array.isArray(this.steps)||this.steps.forEach((e,t)=>{e instanceof ut&&(e.stepMark=0)})}_applyDefaultFilter(){this.steps&&Array.isArray(this.steps)&&this.steps.length>0&&this.updateStepsVisibility(e=>(e.stepMark??0)===0)}getCurrentEquation(){if(!this.steps||this.steps.length===0)return null;for(let e=this.steps.length-1;e>=0;e--)if(this.steps[e]instanceof ut)return this.steps[e];return null}addStep(e,t,r){let i={};typeof t=="string"?i={description:t,stepMark:r??2}:t&&(i=t);const s=typeof e=="string"?this._stringToNode(e):e,a=this.steps.length;return i.description!==void 0&&(this.stepDescriptions[a]=i.description),i.stepMark!==void 0?this.importanceLevels[a]=i.stepMark:this.importanceLevels[a]=0,this.defaultEquationBackground&&typeof(s==null?void 0:s.setBackgroundStyle)=="function"&&s.setBackgroundStyle(this.defaultEquationBackground),s.setFontSize(this.getFontSize()),s.initialize(),this.steps.push(s),this.addChild(s),this.argumentNodeList.steps=this.steps,this.rebuildNodeMap(),s instanceof ut?s.stepMark=i.stepMark??this._determineStepMark(s,i):i.stepMark!==void 0?s.stepMark=i.stepMark:s.stepMark=0,this.computeDimensions(),this.updateLayout(),window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),this._reapplyCurrentFilter(),a}setDefaultEquationBackground(e=null){this.defaultEquationBackground=e,e&&((this.steps||[]).forEach(t=>{typeof(t==null?void 0:t.setBackgroundStyle)=="function"&&t.setBackgroundStyle(e)}),this.computeDimensions(),this.updateLayout())}_determineStepMark(e,t){return t.isSimplification?2:this._isFullySimplified(e)?0:2}_isFullySimplified(e){if(!(e instanceof ut))return!1;const t=this._isSimpleExpression(e.left),r=this._isSimpleExpression(e.right);return t&&r}_isSimpleExpression(e){return e.isConstant()||e.type==="omdVariableNode"?!0:e.type==="omdBinaryExpressionNode"?this._isSimpleExpression(e.left)&&this._isSimpleExpression(e.right):!1}rebuildNodeMap(){this.nodeMap||(this.nodeMap=new Map);const e=new Map;this.steps.forEach((t,r)=>{t.findAllNodes().forEach(s=>{e.set(s.id,s)})}),e.set(this.id,this),this.preserveProvenanceHistory(e),this.nodeMap=e}preserveProvenanceHistory(e){const t=this._collectAllProvenanceIds(e);this._preserveReferencedNodes(t,e)}_collectAllProvenanceIds(e){const t=new Set,r=new Set;return e.forEach(i=>this._collectNodeProvenanceIds(i,t,r)),t}_collectNodeProvenanceIds(e,t,r){var i;!e||!e.id||r.has(e.id)||(r.add(e.id),((i=e.provenance)==null?void 0:i.length)>0&&e.provenance.forEach(s=>t.add(s)),e.argumentNodeList&&Object.values(e.argumentNodeList).flat().forEach(s=>{this._collectNodeProvenanceIds(s,t,r)}))}_preserveReferencedNodes(e,t){const r=new Set;e.forEach(i=>this._preserveNodeAndContext(i,t,r))}_preserveNodeAndContext(e,t,r){var s,a;if(r.has(e)||t.has(e)||!((s=this.nodeMap)!=null&&s.has(e)))return;r.add(e);const i=this.nodeMap.get(e);t.set(e,i),((a=i.provenance)==null?void 0:a.length)>0&&i.provenance.forEach(o=>{this._preserveNodeAndContext(o,t,r)}),this._preserveParentContext(i,t),this._preserveSiblingContext(i,t)}_preserveParentContext(e,t){let r=e.parent;for(;r&&r.id;)!t.has(r.id)&&this.nodeMap.has(r.id)&&t.set(r.id,this.nodeMap.get(r.id)),r=r.parent}_preserveSiblingContext(e,t){var r;(r=e.parent)!=null&&r.argumentNodeList&&Object.values(e.parent.argumentNodeList).flat().forEach(i=>{i&&i.id&&!t.has(i.id)&&this.nodeMap.has(i.id)&&t.set(i.id,this.nodeMap.get(i.id))})}recordSimplificationHistory(e,t,r,i={}){const s={name:e,affectedNodes:[...t],message:r,stepNumber:this.steps.length,...i};this.simplificationHistory.push(s)}getSimplificationHistory(){return[...this.simplificationHistory]}clearSimplificationHistory(){this.simplificationHistory=[]}setFontSize(e){super.setFontSize(e),this.steps.forEach(t=>{t.setFontSize(e)}),this.computeDimensions(),this.updateLayout()}refresh(e,t=!0){this.computeDimensions(),this.updateLayout(),e.render(this),t&&e.centerNode()}applyEquationOperation(e,t){if(!es.OPERATION_MAP[t])return console.error(`Invalid operation: ${t}`),this;const r=this.getCurrentEquation();if(!r)return console.error("No equation to apply operation to."),this;let i=e;if(typeof e=="string"){if(!window.math)throw new Error("Math.js is required for parsing expressions");i=isNaN(e)?window.math.parse(e):parseFloat(e)}const s=new Bs(t,e);this.addStep(s,{stepMark:0});const a=r.clone(),o=es.OPERATION_MAP[t],l=a[o](i,s.id),u=l.clone(),{foldedCount:c}=_a(u),h=c===0;return this.addStep(l,{stepMark:h?0:1,description:this._getOperationDescription(t,e,!h)}),this}_getOperationDescription(e,t,r){const s={add:`Added ${t} to both sides`,subtract:`Subtracted ${t} from both sides`,multiply:`Multiplied both sides by ${t}`,divide:`Divided both sides by ${t}`}[e]||`Applied ${e} with ${t}`;return r?`${s} (unsimplified)`:s}applyEquationFunction(e){const t=this.getCurrentEquation();if(!t)throw new Error("No equation found in sequence to operate on");const i=t.clone().applyFunction(e),s=i.clone(),{foldedCount:a}=_a(s),o=a===0?0:1,l=`Applied ${e} to both sides`;return this.addStep(i,{stepMark:o,description:l}),this}simplify(){const e=this.steps[this.steps.length-1];if(!e)return{success:!1,message:"No expression found to simplify"};try{const t=e.clone(),r=_a(t);return r.foldedCount>0?this._handleSuccessfulSimplification(e,r):{success:!1,foldedCount:0,message:"No simplifications available"}}catch(t){return console.error("Error during simplification:",t),{success:!1,message:`Simplification error: ${t.message}`}}}_handleSuccessfulSimplification(e,{newRoot:t,foldedCount:r,historyEntry:i}){i&&(i.stepNumber=this.steps.length-1,i.originalStep=e.toString(),this.simplificationHistory.push(i));const s=t.clone(),{foldedCount:a}=_a(s),o=a===0,l=o?`Fully simplified result (${r} operation${r>1?"s":""} applied)`:`Simplification step (${r} operation${r>1?"s":""} applied)`;this.addStep(t,{stepMark:o?0:2,description:l,isSimplification:!0});const u=o?`Fully simplified! Applied ${r} simplification step(s).`:`Simplified! Applied ${r} simplification step(s), more are available.`;return{success:!0,foldedCount:r,isFinalSimplification:o,message:u}}simplifyAll(e=50){let t=0,r,i=0;do r=this.steps.length,this.simplify().success&&i++,t++;while(this.steps.length>r&&t<e);return t>=e?{success:!1,totalSteps:i,iterations:t,message:`Stopped after ${e} iterations to avoid an infinite loop.`}:{success:!0,totalSteps:i,iterations:t,message:`All possible simplifications completed. Added ${i} simplification steps.`}}evaluate(e={}){const t=this.getCurrentStep();if(!t||typeof t.evaluate!="function"){console.warn("Evaluation not supported for the current step.");return}try{const r=t.evaluate(e);if(typeof r=="object"&&r.left!==void 0&&r.right!==void 0){const{left:i,right:s}=r,a=Math.abs(i-s)<1e-9}}catch(r){console.error("Evaluation failed:",r.message)}}validateSequenceProvenance(){const e=[];return this._validateStepsProvenance(e),this._findOrphanedNodes(e),e}_validateStepsProvenance(e){this.steps.forEach((t,r)=>{t.validateProvenance(this.nodeMap).forEach(s=>e.push({...s,stepIndex:r}))})}_findOrphanedNodes(e){const t=new Set(this.steps.flatMap(i=>i.findAllNodes().map(s=>s.id))),r=this._collectAllProvenanceIds(this.nodeMap);this.nodeMap.forEach((i,s)=>{!t.has(s)&&!r.has(s)&&e.push({type:"orphaned_node",nodeId:s,nodeType:i.type})})}select(){}deselect(){}highlight(e){this.childList.forEach(t=>{t instanceof kt&&t!==this.backRect&&t.highlight(e)})}clearProvenanceHighlights(){this.childList.forEach(e=>{e instanceof kt&&typeof e.clearProvenanceHighlights=="function"&&e!==this.backRect&&e.clearProvenanceHighlights()})}computeDimensions(){const e=this.steps.filter(i=>i.visible!==!1);if(e.length===0){this.setWidthAndHeight(0,0);return}e.forEach(i=>i.computeDimensions()),this.alignPointX=this._calculateAlignmentPoint(e);const{maxWidth:t,totalHeight:r}=this._calculateTotalDimensions(e);this.setWidthAndHeight(t,r)}_calculateAlignmentPoint(e){const t=[];return e.forEach(r=>{if(r instanceof ut){if(typeof r.getEqualsAnchorX=="function")t.push(r.getEqualsAnchorX());else if(r.equalsSign&&r.left){const i=8*r.getFontSize()/r.getRootFontSize();t.push(r.left.width+i+r.equalsSign.width/2)}}}),t.length>0?Math.max(...t):0}_calculateTotalDimensions(e){let t=0,r=0;const i=15*this.getFontSize()/this.getRootFontSize();return e.forEach((s,a)=>{let o=0;s instanceof ut?o=this.alignPointX+s.equalsSign.width+s.right.width:o=s.width,t=Math.max(t,o),r+=s.height,a<e.length-1&&(r+=i)}),{maxWidth:t,totalHeight:r}}_computeStepXOffset(e){if(this.alignmentMode==="center")return(this.width-e.width)/2;if(e instanceof ut){const t=typeof e.getEqualsAnchorX=="function"?e.getEqualsAnchorX():e.left.width;return this.alignPointX-t}if(e instanceof Bs){const t=typeof e.getLeftWidthForAlignment=="function"?e.getLeftWidthForAlignment():e.width/2,r=(typeof e.gap=="number"?e.gap:0)/2;return this.alignPointX-(t+r)}return(this.width-e.width)/2}updateLayout(){const e=15*this.getFontSize()/this.getRootFontSize(),t=this.steps.filter(i=>i.visible!==!1);t.forEach(i=>i.updateLayout()),this.alignPointX=this._calculateAlignmentPoint(t);let r=0;t.forEach((i,s)=>{const a=this._computeStepXOffset(i);i.setPosition(a,r),r+=i.height,s<t.length-1&&(r+=e)})}static fromStringArray(e){const t=e.map(r=>{const i=r.trim();if(i.includes("="))return ut.fromString(i);throw new Error(`Step string "${i}" is not a valid equation for omdEquationSequenceNode.`)});return new es(t)}clone(){const e=this.steps.map(r=>r.clone()),t=new es(e);return t.provenance.push(this.id),t.nodeMap=new Map,t.findAllNodes().forEach(r=>t.nodeMap.set(r.id,r)),t}toMathJSNode(){return this.steps[this.steps.length-1].toMathJSNode()}getCurrentStep(){if(!this.steps||this.steps.length===0)return null;let e=-1;for(let t=this.steps.length-1;t>=0;t--){const r=this.steps[t];if(r&&r.visible!==!1){if(r instanceof ut||r.type==="omdEquationNode"){e=t;break}e===-1&&(e=t)}}return e===-1&&(e=this.steps.length-1),e<0&&(e=0),e>=this.steps.length&&(e=this.steps.length-1),this.currentStepIndex=e,this.steps[e]}navigateToStep(e){return e<0||e>=this.steps.length?!1:(this.currentStepIndex=e,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0)}nextStep(){return this.currentStepIndex<this.steps.length-1?(this.currentStepIndex++,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0):!1}previousStep(){return this.currentStepIndex>0?(this.currentStepIndex--,window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters(),!0):!1}getFilteredSteps(e){const t=[];return this.steps.forEach((r,i)=>{const s=this.importanceLevels[i]!==void 0?this.importanceLevels[i]:r.stepMark!==void 0?r.stepMark:0;s<=e&&t.push({step:r,description:this.stepDescriptions[i]||"",importance:s,index:i})}),t}renderCurrentStep(){const e=this.getCurrentStep();if(!e)return new jsvgGroup().svgObject;const t=new jsvgGroup;e.computeDimensions(),e.updateLayout();const r=e.render();return t.addChild(r),t.svgObject}toString(){return this.steps.length===0?"":this.steps.map((e,t)=>{const r=this.stepDescriptions[t]?` (${this.stepDescriptions[t]})`:"";return`Step ${t+1}: ${e.toString()}${r}`}).join("\\n")}clear(){this.steps.forEach(e=>{this.removeChild(e)}),this.steps=[],this.stepDescriptions=[],this.importanceLevels=[],this.argumentNodeList.steps=[],this.currentStepIndex=0,this.clearSimplificationHistory(),this.rebuildNodeMap(),this.computeDimensions(),this.updateLayout(),window.refreshDisplayAndFilters&&window.refreshDisplayAndFilters()}static fromSteps(e){if(!Array.isArray(e))throw new Error("fromSteps requires an array of expression strings");const t=new es([]);return e.forEach((r,i)=>{const s=r.trim();let a;if(s.includes("="))a=ut.fromString(s);else{if(!window.math)throw new Error("Math.js is required for parsing expressions");const o=window.math.parse(s),l=_t(o);a=new l(o)}t.addStep(a,{stepMark:0,description:""})}),t}_stringToNode(e){const t=e.trim();if(t.includes("="))return ut.fromString(t);if(!window.math)throw new Error("Math.js is required for parsing expressions");const r=window.math.parse(t),i=_t(r);return new i(r)}show(){super.show(),this.layoutManager&&this.layoutManager.updateVisualVisibility()}hide(){super.hide(),this.layoutManager&&this.layoutManager.updateVisualVisibility()}updateStepsVisibility(e){!this.steps||!Array.isArray(this.steps)||(this.steps.forEach(t=>{if(!t)return;e(t)?(t.visible=!0,t.svgObject&&(t.svgObject.style.display="")):(t.visible=!1,t.svgObject&&(t.svgObject.style.display="none"));const r=wq(t.stepMark??0);t.svgObject&&(t.svgObject.style.fontWeight=r.toString())}),this.layoutManager&&this.layoutManager.updateVisualVisibility(),this.computeDimensions(),this.updateLayout())}};eu(es,"OPERATION_MAP",{add:"addToBothSides",subtract:"subtractFromBothSides",multiply:"multiplyBothSides",divide:"divideBothSides"});let jo=es;class je{static isLeafNode(e){if(!e)return!1;const t=["omdConstantNode","omdVariableNode","omdOperatorNode"];return!!(e.constructor&&t.includes(e.type)||e.type==="constant"||e.type==="variable"||e.type==="operator"||!e.left&&!e.right&&!e.argument&&!e.expression)}static isBinaryNode(e){return e?e.type==="omdBinaryExpressionNode"&&e.left&&e.right:!1}static isUnaryNode(e){return e?e.type==="omdUnaryExpressionNode"&&e.argument:!1}static hasExpression(e){return e?e.expression!==void 0:!1}static getNodeValue(e){if(!e)return"undefined";try{return e.constructor&&e.type==="omdVariableNode"&&e.name!==void 0?String(e.name):e.constructor&&e.type==="omdConstantNode"&&typeof e.number=="number"?String(e.number):e.isConstant&&e.isConstant()&&e.getValue&&typeof e.getValue=="function"?String(e.getValue()):e.toString&&typeof e.toString=="function"?e.toString():e.value!==void 0?String(e.value):e.number!==void 0?String(e.number):e.constructor?e.type:"unknown"}catch(t){return console.error("Error getting node value:",t),"error"}}static findLeafNodes(e){if(!e)return[];if(this.isLeafNode(e))return[e];const t=[];try{this.isBinaryNode(e)?(t.push(...this.findLeafNodes(e.left)),t.push(...this.findLeafNodes(e.right))):this.isUnaryNode(e)?t.push(...this.findLeafNodes(e.argument)):this.hasExpression(e)&&t.push(...this.findLeafNodes(e.expression))}catch(r){console.error("Error finding leaf nodes:",r,e)}return t}static findVariableNodes(e){return this.findLeafNodes(e).filter(r=>r.constructor&&r.type==="omdVariableNode")}static findConstantNodes(e){return this.findLeafNodes(e).filter(r=>r.constructor&&r.type==="omdConstantNode")}static findLeafNodesWithValue(e,t){const r=this.findLeafNodes(e),i=r.filter(a=>a.toString()===t);if(i.length>0)return i;const s=parseFloat(t);if(!isNaN(s)){const a=r.filter(o=>o.constructor&&o.type==="omdConstantNode"&&o.number!==void 0?Math.abs(o.number-s)<1e-4:!1);if(a.length>0)return a}return r.filter(a=>{const o=a.toString();return o.includes(t)||t.includes(o)})}static findAllNodes(e){if(!e)return[];const t=[e];try{e.childList&&Array.isArray(e.childList)&&e.childList.forEach(r=>{r&&r!==e.backRect&&t.push(...this.findAllNodes(r))}),e.argumentNodeList&&Object.values(e.argumentNodeList).forEach(r=>{r&&r!==e&&(Array.isArray(r)?r.forEach(i=>{i&&i!==e&&t.push(...this.findAllNodes(i))}):t.push(...this.findAllNodes(r)))})}catch(r){console.error("Error finding all nodes:",r,e)}return t}static findRightmostNodeWithValue(e,t){const i=this.findLeafNodes(e).filter(a=>a.toString()===t||a.constructor&&a.type==="omdConstantNode"&&a.number!==void 0&&Math.abs(a.number-parseFloat(t))<1e-4);if(i.length===0)return null;const s=i.filter(a=>{const o=a.parent;return o&&o.constructor&&o.type==="omdBinaryExpressionNode"&&o.operation==="subtract"&&o.right===a});return s.length>0?s[s.length-1]:i[i.length-1]}}class Iq{static findChangedNodes(e,t,r={}){const{educationalMode:i=!1}=r,s=this.findEquationSpecialCases(e,t);if(s.length>0)return s;const a=[];if(e.left.toString()!==t.left.toString()){const o=this.diffSubtrees(e.left,t.left,i);a.push(...o)}if(e.right.toString()!==t.right.toString()){const o=this.diffSubtrees(e.right,t.right,i);a.push(...o)}return a}static findEquationSpecialCases(e,t){const r=e.left.toString(),i=t.left.toString(),s=e.right.toString(),a=t.right.toString();if(i.startsWith(r)&&a.startsWith(s)){const o=i.substring(r.length).trim(),l=a.substring(s.length).trim();if(o.startsWith("-")&&l.startsWith("-")&&o.substring(1).trim()===l.substring(1).trim()){const u=o.substring(1).trim(),c=[],h=je.findRightmostNodeWithValue(t.left,u);if(h)if(je.isLeafNode(h))c.push(h);else{const d=je.findLeafNodes(h);c.push(...d)}const f=je.findRightmostNodeWithValue(t.right,u);if(f)if(je.isLeafNode(f))c.push(f);else{const d=je.findLeafNodes(f);c.push(...d)}return c}if(o.startsWith("+")&&l.startsWith("+")&&o.substring(1).trim()===l.substring(1).trim()){const u=o.substring(1).trim(),c=[],h=je.findRightmostNodeWithValue(t.left,u);if(h)if(je.isLeafNode(h))c.push(h);else{const d=je.findLeafNodes(h);c.push(...d)}const f=je.findRightmostNodeWithValue(t.right,u);if(f)if(je.isLeafNode(f))c.push(f);else{const d=je.findLeafNodes(f);c.push(...d)}return c}}return[]}static diffSubtrees(e,t,r=!1){const i=this.findCommonPrefixHighlights(e,t);if(i.length>0)return i;const s=this.findVariablePreservationHighlights(e,t);if(s.length>0)return s;const a=this.findTypeDifferenceHighlights(e,t);if(a.length>0)return a;const o=this.findSubtractionPatternHighlights(e,t);if(o.length>0)return o;const l=this.findAllSubtreeMatches(e,t),u=this.selectOptimalMatching(l);let c=this.findUnmatchedLeafNodes(t,u);if(r&&c.length===0){const h=this.findEducationalHighlights(e,t,u);c.push(...h)}return c}static findEducationalHighlights(e,t,r){const i=[],s=this.findAdditiveIdentityChanges(e,t);i.push(...s);const a=this.findMultiplicativeIdentityChanges(e,t);i.push(...a);const o=this.findDoubleNegativeChanges(e,t);return i.push(...o),i}static findAdditiveIdentityChanges(e,t){const r=e.toString(),i=t.toString();if((r.includes(" + 0")||r.includes(" - 0"))&&!i.includes(" + 0")&&!i.includes(" - 0")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findMultiplicativeIdentityChanges(e,t){const r=e.toString(),i=t.toString();if((r.includes(" * 1")||r.includes(" / 1"))&&!i.includes(" * 1")&&!i.includes(" / 1")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findDoubleNegativeChanges(e,t){const r=e.toString(),i=t.toString();if(r.includes("--")&&!i.includes("--")){const s=je.findLeafNodes(t);if(s.length>0)return s}return[]}static findCommonPrefixHighlights(e,t){if(!je.isBinaryNode(t))return[];const r=e.toString(),i=t.toString(),s=this._findCommonPrefix(r,i);if(!s||s.length<=1)return[];const a=r.substring(s.length).trim(),o=i.substring(s.length).trim();if(o==="0"){const l=je.findLeafNodesWithValue(t,"0");if(l.length>0)return l}if(a===""&&o.startsWith("- ")){const l=o.substring(2).trim(),u=je.findLeafNodesWithValue(t,l);if(u.length>0)return u}return[]}static findVariablePreservationHighlights(e,t){if(!je.isBinaryNode(e)||!je.isBinaryNode(t))return[];const r=e.toString(),i=t.toString(),s=/(\d*[a-zA-Z])/,a=r.match(s),o=i.match(s);if(a&&o&&a[0]===o[0]){const l=je.findConstantNodes(e);return je.findConstantNodes(t).filter(h=>!l.some(f=>f.toString()===h.toString()))}return[]}static findTypeDifferenceHighlights(e,t){const r=e.constructor?e.type:"unknown",i=t.constructor?t.type:"unknown";if(r===i)return[];if(je.isBinaryNode(t)){const a=e.toString(),o=t.left?t.left.toString():"",l=t.right?t.right.toString():"";if(a===o){if(t.right)return je.findLeafNodes(t.right)}else if(a===l&&t.left)return je.findLeafNodes(t.left)}return je.findLeafNodes(t)}static findSubtractionPatternHighlights(e,t){var r;if(je.isBinaryNode(t)&&t.operation==="subtract"){const i=e.toString(),s=(r=t.left)==null?void 0:r.toString();if(i===s&&t.right)return je.findLeafNodes(t.right)}return[]}static _findCommonPrefix(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return e.substring(0,r)}static findAllSubtreeMatches(e,t){const r=[],i=this.getAllSubtrees(e),s=this.getAllSubtrees(t);for(const a of i)for(const o of s){const l=this.calculateSimilarity(a,o);l.isMatch&&r.push({oldNode:a,newNode:o,size:l.size,score:l.score,type:l.type})}return r}static getAllSubtrees(e){if(!e)return[];const t=[e];return je.isBinaryNode(e)?(t.push(...this.getAllSubtrees(e.left)),t.push(...this.getAllSubtrees(e.right))):je.isUnaryNode(e)?t.push(...this.getAllSubtrees(e.argument)):je.hasExpression(e)&&t.push(...this.getAllSubtrees(e.expression)),t}static calculateSimilarity(e,t){if(this.treesStructurallyEqual(e,t)){const r=this.getSubtreeSize(e);return{isMatch:!0,size:r,score:r*10,type:"exact"}}if(e.toString()===t.toString()){const r=this.getSubtreeSize(e);return{isMatch:!0,size:r,score:r*8,type:"equivalent"}}if(je.isLeafNode(e)&&je.isLeafNode(t)){const r=je.getNodeValue(e),i=je.getNodeValue(t);if(r===i)return{isMatch:!0,size:1,score:5,type:"leaf"}}return{isMatch:!1,size:0,score:0,type:"none"}}static treesStructurallyEqual(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.constructor?e.type:"unknown",i=t.constructor?t.type:"unknown";if(r!==i)return!1;if(je.isLeafNode(e)){const s=je.getNodeValue(e),a=je.getNodeValue(t);return s===a}return je.isBinaryNode(e)?e.operation!==t.operation?!1:this.treesStructurallyEqual(e.left,t.left)&&this.treesStructurallyEqual(e.right,t.right):je.isUnaryNode(e)?e.operation!==t.operation?!1:this.treesStructurallyEqual(e.argument,t.argument):je.hasExpression(e)?this.treesStructurallyEqual(e.expression,t.expression):!1}static getSubtreeSize(e){if(!e)return 0;let t=1;return je.isBinaryNode(e)?(t+=this.getSubtreeSize(e.left),t+=this.getSubtreeSize(e.right)):je.isUnaryNode(e)?t+=this.getSubtreeSize(e.argument):je.hasExpression(e)&&(t+=this.getSubtreeSize(e.expression)),t}static selectOptimalMatching(e){const t=e.slice().sort((a,o)=>o.score-a.score),r=[],i=new Set,s=new Set;for(const a of t)!this.hasNodeOverlap(a.oldNode,i)&&!this.hasNodeOverlap(a.newNode,s)&&(r.push(a),this.markSubtreeAsUsed(a.oldNode,i),this.markSubtreeAsUsed(a.newNode,s));return r}static hasNodeOverlap(e,t){return this.getAllSubtrees(e).some(i=>t.has(i))}static markSubtreeAsUsed(e,t){this.getAllSubtrees(e).forEach(i=>t.add(i))}static findUnmatchedLeafNodes(e,t){const r=je.findLeafNodes(e),i=new Set;for(const a of t)this.getAllSubtrees(a.newNode).forEach(l=>i.add(l));return r.filter(a=>!i.has(a))}static findUnmatchedOldNodes(e,t){const r=je.findLeafNodes(e),i=new Set;for(const a of t)this.getAllSubtrees(a.oldNode).forEach(l=>i.add(l));return r.filter(a=>!i.has(a))}static debugPrintTree(e,t=0){if(!e)return"";const r=" ".repeat(t),i=e.constructor?e.type:"unknown",s=e.toString?e.toString():"unknown";let a=`${r}${i}: "${s}"
61
61
  `;return je.isBinaryNode(e)?(a+=`${r}├─ left:
62
62
  ${this.debugPrintTree(e.left,t+1)}`,a+=`${r}└─ right:
63
63
  ${this.debugPrintTree(e.right,t+1)}`):je.isUnaryNode(e)?a+=`${r}└─ argument:
@@ -87,10 +87,10 @@ ${this.debugPrintTree(e.expression,t+1)}`),a}}class $q{constructor(e){this.stepV
87
87
  font-size: ${this.fontSize}px !important;
88
88
  display: flex !important;
89
89
  flex-direction: column !important;
90
- `,e.div.querySelectorAll(".step-content, .step-text").forEach(d=>{d.style.lineHeight="1.3 !important",d.style.margin="0 !important",d.style.fontFamily="Albert Sans, Arial, sans-serif !important",d.style.position="static !important"}),e.div.querySelectorAll("span").forEach(d=>{d.style.position="static !important"})),e.div.offsetHeight}setupStepInteractions(e){const t=e.div.style.backgroundColor||"";e.div.addEventListener("mouseenter",()=>{var r;e.div.style.backgroundColor=Fe.mediumGray,(r=this.onStepHover)==null||r.call(this,e.stepIndex,e.stepMessage,!0)}),e.div.addEventListener("mouseleave",()=>{var r;e.div.style.backgroundColor=t,(r=this.onStepHover)==null||r.call(this,e.stepIndex,e.stepMessage,!1)}),e.div.addEventListener("click",()=>{var r;(r=this.onStepClick)==null||r.call(this,e.stepIndex,e.stepMessage)})}calculateContentHeight(e,t,r){const i=document.createElement("div");i.style.position="absolute",i.style.visibility="hidden",i.style.width=`${this.stepWidth-16}px`,i.style.fontSize=`${this.fontSize}px`,i.style.lineHeight="1.3",i.style.fontFamily="Albert Sans, Arial, sans-serif",i.style.whiteSpace="normal",i.style.wordWrap="break-word",i.style.overflowWrap="break-word",i.style.padding="6px 8px",i.style.boxSizing="border-box",i.style.display="flex",i.style.flexDirection="column",i.style.justifyContent="center";const s=this.formatStepContent(e,t,r);i.innerHTML=s,document.body.appendChild(i);const a=i.offsetHeight;return document.body.removeChild(i),Math.max(this.baseStepHeight,a+2)}calculateStepHeight(e){return this.calculateContentHeight(e,0,!1)}updateBackgroundSize(){if(this.backgroundRect&&this.contentGroup){const e=this.contentGroup.height+16,t=this.stepWidth+16;this.backgroundRect.setWidthAndHeight(t,e)}}applyDropShadowIfNeeded(){this.stylingOptions.dropShadow&&this.backgroundRect&&this.backgroundRect.svgObject&&(this.backgroundRect.svgObject.style.filter="drop-shadow(0 2px 8px rgba(0,0,0,0.15))")}setOnStepHover(e){this.onStepHover=e}setOnStepClick(e){this.onStepClick=e}getLayoutGroup(){return this.layoutGroup}setPosition(e,t){this.layoutGroup.setPosition(e,t)}getDimensions(){return{width:this.backgroundRect?this.backgroundRect.width:this.stepWidth+16,height:this.backgroundRect?this.backgroundRect.height:100}}updateStyling(e={}){if(this.stylingOptions={...this.stylingOptions,...e},e.maxWidth&&(this.stepWidth=e.maxWidth),e.fontSize&&(this.fontSize=e.fontSize),this.backgroundRect){const t=this.stylingOptions.backgroundColor||Fe.lightGray,r=this.stylingOptions.borderColor||"#e0e0e0",i=this.stylingOptions.borderWidth||1,s=this.stylingOptions.borderRadius||6;this.backgroundRect.setFillColor(t),this.backgroundRect.setStrokeColor(r),this.backgroundRect.setStrokeWidth(i),this.backgroundRect.setCornerRadius(s),this.backgroundRect.svgObject&&(this.stylingOptions.dropShadow?this.backgroundRect.svgObject.style.filter="drop-shadow(0 2px 8px rgba(0,0,0,0.15))":this.backgroundRect.svgObject.style.filter="")}this.stepElements.forEach((t,r)=>{if(t.div){const i=t.div.innerHTML,s=this.calculateContentHeight(t.stepMessage,r,t.isMultiple);this.applyStepStyling(t,i,t.isMultiple,s),t.setFontSize(this.fontSize),t.setWidthAndHeight(this.stepWidth,s)}}),this.updateBackgroundSize()}getStyling(){return{...this.stylingOptions}}isOperationMessage(e){return["Applied","added","subtracted","multiplied","divided","both sides"].some(r=>e.toLowerCase().includes(r.toLowerCase()))}extractOperationAction(e){const t=e.match(/^(Added|Subtracted|Multiplied|Divided)/i);return t?t[0]:null}extractOperationValue(e){const t=e.match(/(?:Added|Subtracted|Multiplied|Divided)\s(.*?)\s(?:to|by)/i);return t&&t[1]?t[1].includes("[object Object]")?null:t[1]:null}extractOperationValueNode(e){return this.simplificationData&&this.simplificationData.operationValueNode?this.simplificationData.operationValueNode:null}destroy(){this.stepElements=[],this.contentGroup&&this.contentGroup.removeAllChildren(),this.layoutGroup.removeAllChildren(),this.onStepHover=null,this.onStepClick=null}}class Hq{constructor(e,t,r={}){this.stepVisualizer=e,this.highlighting=t,this.stepTextBoxes=[],this.options=r}createTextBoxForDot(e){try{this.removeTextBoxForDot(e);const t=this._findDotAboveForPositioning(e);if(!t){console.error("Target dot not found for positioning text box for dot index:",e);return}const r=this._getSimplificationDataForDot(e);this._createInteractiveStepsForDot(e,t,r)}catch(t){console.error("Error creating text box for dot",e,":",t)}}_createInteractiveStepsForDot(e,t,r){const i=new qq(this.stepVisualizer,r,this.options),s=t.xpos+this.stepVisualizer.dotRadius*2+10,a=t.ypos-this.stepVisualizer.dotRadius;i.setPosition(s,a),i.setOnStepHover((l,u,c)=>{}),i.setOnStepClick((l,u)=>{});const o=i.getLayoutGroup();o.dotIndex=e,this.stepVisualizer.visualContainer.addChild(o),o.svgObject&&(this.options.zIndex||this.options.position)&&(this.options.position&&(o.svgObject.style.position=this.options.position),this.options.zIndex&&(o.svgObject.style.zIndex=String(this.options.zIndex))),this.stepTextBoxes.push({dotIndex:e,interactiveSteps:i,layoutGroup:o})}removeTextBoxForDot(e){const t=this.stepTextBoxes.findIndex(r=>r.dotIndex===e);if(t>=0){const r=this.stepTextBoxes[t];this.stepVisualizer.visualContainer.removeChild(r.layoutGroup),r.interactiveSteps.destroy(),this.stepTextBoxes.splice(t,1)}}clearAllTextBoxes(){this.stepTextBoxes.forEach(e=>{this.stepVisualizer.visualContainer.removeChild(e.layoutGroup),e.interactiveSteps.destroy()}),this.stepTextBoxes=[]}_findDotAboveForPositioning(e){const t=this.stepVisualizer.stepDots[e];if(!t||!t.equationRef)return null;const r=t.equationRef,i=this.stepVisualizer.steps.indexOf(r);for(let s=i-1;s>=0;s--){const a=this.stepVisualizer.steps[s];if(a instanceof ut&&a.visible!==!1){for(let o=e-1;o>=0;o--){const l=this.stepVisualizer.stepDots[o];if(l&&l.equationRef===a)return l}break}}return t}_getSimplificationDataForDot(e){return this.stepVisualizer._getSimplificationDataForDot(e)}getStepTextBoxes(){return this.stepTextBoxes}updateStyling(e={}){this.options={...this.options,...e},this.stepTextBoxes.forEach(t=>{t.interactiveSteps&&typeof t.interactiveSteps.updateStyling=="function"&&t.interactiveSteps.updateStyling(this.options)})}getStyling(){return{...this.options}}}class Uq{constructor(e){this.stepVisualizer=e,this.expansionDots=[],this.fixedVisualizerPosition=250,this.allowEquationRepositioning=!0}setFixedVisualizerPosition(e){this.fixedVisualizerPosition!==e&&(this.fixedVisualizerPosition=e,this.stepVisualizer&&this.stepVisualizer.stepDots.length>0&&this.updateVisualLayout(!0))}updateVisualLayout(e=!1){if(this.stepVisualizer.stepDots.length===0)return;const t=this.stepVisualizer.sequenceWidth||this.stepVisualizer.width,r=this._getMaxEquationEffectivePaddingX(),i=t+r,s=this.fixedVisualizerPosition;if(this.stepVisualizer.visualContainer.setPosition(s,0),this.allowEquationRepositioning&&e){const f=this.fixedVisualizerPosition-this.stepVisualizer.visualSpacing;let d=0;i>f&&(d=f-i),this._adjustEquationPositions(d)}const a=this.stepVisualizer.steps.filter(f=>f.visible!==!1);let o=0;const l=15*this.stepVisualizer.getFontSize()/this.stepVisualizer.getRootFontSize();a.forEach((f,d)=>{if(f instanceof ut){const p=this.findDotIndexForEquation(f);if(p>=0&&p<this.stepVisualizer.stepDots.length){const m=this.stepVisualizer.stepDots[p];let y;f.equalsSign&&f.equalsSign.ypos!==void 0?y=f.equalsSign.ypos+f.equalsSign.height/2:y=f.getAlignmentBaseline?f.getAlignmentBaseline():f.height/2;const v=o+y,S=this.stepVisualizer.dotRadius*3/2;m.setPosition(S,v)}}o+=f.height,d<a.length-1&&(o+=l)}),this.updateAllLinePositions();let u=this.stepVisualizer.dotRadius*3,c=this.stepVisualizer.height;this.stepVisualizer.sequenceHeight||(this.stepVisualizer.sequenceHeight=c);const h=this.stepVisualizer.textBoxManager.getStepTextBoxes();if(h.length>0&&(u=Math.max(u,280+this.stepVisualizer.dotRadius*2+10+20),h.forEach(d=>{if(d.interactiveSteps){const p=d.interactiveSteps.getDimensions(),y=d.interactiveSteps.getLayoutGroup().ypos+p.height;c=Math.max(c,y+20)}})),this.stepVisualizer.stepDots.length>0){Math.max(...this.stepVisualizer.stepDots.map(d=>d.radius||this.stepVisualizer.dotRadius));const f=Math.max(...this.stepVisualizer.stepDots.map(d=>d.ypos+this.stepVisualizer.dotRadius));c=Math.max(c,f)}this.stepVisualizer.visualContainer.setWidthAndHeight(u,c),this.updateVisualZOrder(),this._positionExpansionDots()}_adjustEquationPositions(e){if(e===0)return;this.stepVisualizer.steps.forEach(r=>{if(r&&r.setPosition){const i=r.xpos||0,s=r.ypos||0;if(r.setPosition(i+e,s),r.operationDisplayNode&&r.operationDisplayNode.setPosition){const a=r.operationDisplayNode.xpos||0,o=r.operationDisplayNode.ypos||0;r.operationDisplayNode.setPosition(a+e,o)}}})}_getMaxEquationEffectivePaddingX(){try{const e=this.stepVisualizer.steps||[];let t=0;return e.forEach(r=>{if(r instanceof ut&&r.visible!==!1&&typeof r.getEffectiveBackgroundPaddingX=="function"){const i=Number(r.getEffectiveBackgroundPaddingX());t=Math.max(t,isNaN(i)?0:i)}}),t}catch{return 0}}findDotIndexForEquation(e){return this.stepVisualizer.stepDots.findIndex(t=>t.equationRef===e)}updateVisualZOrder(){if(!this.stepVisualizer.visualContainer)return;this.stepVisualizer.stepLines.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="1",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.stepVisualizer.stepDots.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="2",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.stepVisualizer.textBoxManager.getStepTextBoxes().forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="3",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.expansionDots.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="4",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))})}updateAllLinePositions(){this.stepVisualizer.stepLines.forEach(e=>{const t=this.stepVisualizer.stepDots[e.fromDotIndex],r=this.stepVisualizer.stepDots[e.toDotIndex];t&&r&&e.setEndpoints(t.xpos,t.ypos,r.xpos,r.ypos)})}updateVisualVisibility(){var i,s,a;const e=this.stepVisualizer,t=((i=e.styling)==null?void 0:i.dotColor)||Fe.stepColor;e.stepDots.forEach((o,l)=>{o.equationRef&&o.equationRef.visible!==!1?(o.setFillColor(t),o.setStrokeColor(t),o.show(),o.visible=!0):(o.hide(),o.visible=!1)}),this._clearExpansionDots(),e.stepLines.forEach(o=>{o.parent===e.visualContainer&&e.visualContainer.removeChild(o)}),e.stepLines=[];const r=e.stepDots.filter(o=>o.visible);for(let o=0;o<r.length-1;o++){const l=r[o],u=r[o+1],c=new Ut,h=((s=e.styling)==null?void 0:s.lineColor)||Fe.stepColor;c.setStrokeColor(h),c.setStrokeWidth(((a=e.styling)==null?void 0:a.lineWidth)||e.lineWidth),c.fromDotIndex=e.stepDots.indexOf(l),c.toDotIndex=e.stepDots.indexOf(u),e.visualContainer.addChild(c),e.stepLines.push(c)}this.updateAllLinePositions(),this._createExpansionDots(),this._positionExpansionDots()}updateDotClickability(e){this.stepVisualizer.dotsClickable?(e.svgObject.style.cursor="pointer",e.svgObject.onclick=t=>{try{const r=this.stepVisualizer.stepDots.indexOf(e);if(r<0)return;this.stepVisualizer._handleDotClick(e,r),t.stopPropagation()}catch(r){console.error("Error in dot click handler:",r)}}):(e.svgObject.style.cursor="default",e.svgObject.onclick=null)}_clearExpansionDots(){this.expansionDots.forEach(e=>{e.parentNode===this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.removeChild(e)}),this.expansionDots=[]}_createExpansionDots(){const e=this.stepVisualizer,t=e.stepDots;e.stepDots.filter(i=>i.visible),e.steps.forEach((i,s)=>{i&&(i instanceof ut||i.constructor.name)}),t.forEach((i,s)=>{i&&i.equationRef});const r=[];e.steps.forEach((i,s)=>{i&&(i instanceof ut||i.constructor.name==="omdEquationNode")&&i.stepMark===0&&i.visible===!0&&r.push(s)});for(let i=1;i<r.length;i++){const s=r[i-1],a=r[i];let o=0;for(let l=s+1;l<a;l++){const u=e.steps[l];u&&(u instanceof ut||u.constructor.name==="omdEquationNode")&&u.stepMark>0&&u.visible===!1&&o++}if(o>0){const l=e.steps[a];if(e.stepDots.findIndex(c=>c.equationRef===l)>=0){const c=i,h=this._createSingleExpansionDot(c,s,o);h.majorStepIndex=a,this.expansionDots.push(h),e.visualContainer.addChild(h)}}}this._createCollapseDots()}_countIntermediateStepsBetween(e,t){var u,c;const r=this.stepVisualizer;let i=0;const s=(u=r.stepDots[e])==null?void 0:u.equationRef,a=(c=r.stepDots[t])==null?void 0:c.equationRef;if(!s||!a)return 0;const o=r.steps.indexOf(s),l=r.steps.indexOf(a);for(let h=o+1;h<l;h++){const f=r.steps[h];f&&(f instanceof ut||f.constructor.name==="omdEquationNode")&&f.stepMark!==void 0&&f.stepMark>0&&f.visible===!1&&i++}return i}_countHiddenStepsBetween(e,t){return this._countIntermediateStepsBetween(e,t)}_createSingleExpansionDot(e,t,r){var u,c,h,f;const i=this.stepVisualizer,s=((u=i.styling)==null?void 0:u.dotRadius)||Ta(0),a=Math.max(3,s*(((c=i.styling)==null?void 0:c.expansionDotScale)||.4)),o=new Tr;o.setWidthAndHeight(a*2,a*2);const l=((h=i.styling)==null?void 0:h.dotColor)||Fe.stepColor;return o.setFillColor(l),o.setStrokeColor(l),o.setStrokeWidth(((f=i.styling)==null?void 0:f.dotStrokeWidth)||1),o.isExpansionDot=!0,o.currentStepIndex=e,o.previousStepIndex=t,o.hiddenCount=r,o.radius=a,o.svgObject.style.cursor="pointer",o.svgObject.onclick=d=>{try{this._handleExpansionDotClick(o),d.stopPropagation()}catch(p){console.error("Error in expansion dot click handler:",p)}},o}_positionExpansionDots(){const e=this.stepVisualizer;this.expansionDots.forEach((t,r)=>{let i;if(t.isCollapseDot){const s=t.currentStepIndex;i=e.stepDots[s]}else{const s=t.majorStepIndex,a=e.steps[s];if(a){const o=e.stepDots.findIndex(l=>l.equationRef===a);i=e.stepDots[o]}}if(i&&i.visible){const s=-(t.radius*2+8),a=i.xpos,o=i.ypos+s;t.setPosition(a,o)}})}_createCollapseDots(){const e=this.stepVisualizer,t=e.stepDots,r=[];let i=[];t.forEach((s,a)=>{if(s&&s.visible&&s.equationRef){const o=s.equationRef.stepMark;o!==void 0&&o>0?i.push(a):i.length>0&&(r.push([...i]),i=[])}else i.length>0&&(r.push([...i]),i=[])}),i.length>0&&r.push([...i]),r.forEach((s,a)=>{if(s.length>0){const o=s[s.length-1],u=e.stepDots[o].equationRef,c=e.steps.indexOf(u);let h=-1;for(let f=c+1;f<e.steps.length;f++){const d=e.steps[f];if(d&&(d instanceof ut||d.constructor.name==="omdEquationNode")&&d.stepMark===0&&d.visible===!0){h=f;break}}if(h>=0){const f=e.steps[h],d=e.stepDots.findIndex(p=>p.equationRef===f);if(d>=0){const p=this._createSingleExpansionDot(d,-1,s.length);p.isCollapseDot=!0,p.intermediateSteps=s,p.groupIndex=a,this.expansionDots.push(p),e.visualContainer.addChild(p)}}}})}_handleExpansionDotClick(e){const t=this.stepVisualizer;if(t.highlighting&&typeof t.highlighting.clearAllExplainHighlights=="function"&&t.highlighting.clearAllExplainHighlights(),e.isCollapseDot)(e.intermediateSteps||[]).forEach(i=>{const s=t.stepDots[i];s&&s.equationRef&&(this._hideStep(s.equationRef),s.hide(),s.visible=!1)}),this._removeLinesToHiddenDots();else{const{majorStepIndex:r,previousStepIndex:i}=e;e.parentNode===t.visualContainer&&t.visualContainer.removeChild(e);const s=this.expansionDots.indexOf(e);s>=0&&this.expansionDots.splice(s,1);for(let a=i+1;a<r;a++){const o=t.steps[a];if(o&&(o instanceof ut||o.constructor.name==="omdEquationNode")&&o.stepMark>0){this._showStep(o);const l=t.stepDots.findIndex(u=>u.equationRef===o);if(l>=0){const u=t.stepDots[l];u.show(),u.visible=!0}}}}t.rebuildVisualizer()}_hideStep(e){e.visible=!1,e.svgObject&&(e.svgObject.style.display="none"),e.operationDisplayNode&&(e.operationDisplayNode.visible=!1,e.operationDisplayNode.svgObject&&(e.operationDisplayNode.svgObject.style.display="none")),e.children&&Array.isArray(e.children)&&e.children.forEach(t=>{t&&this._hideStep(t)})}_showStep(e){e.visible=!0,e.svgObject&&(e.svgObject.style.display=""),e.operationDisplayNode&&(e.operationDisplayNode.visible=!0,e.operationDisplayNode.svgObject&&(e.operationDisplayNode.svgObject.style.display="")),e.children&&Array.isArray(e.children)&&e.children.forEach(t=>{t&&this._showStep(t)})}_removeLinesToHiddenDots(){const e=this.stepVisualizer,t=[];e.stepLines.forEach((r,i)=>{const s=e.stepDots[r.fromDotIndex],a=e.stepDots[r.toDotIndex];(s&&!s.visible||a&&!a.visible)&&t.push(r)}),t.forEach(r=>{r.parent===e.visualContainer&&e.visualContainer.removeChild(r);const i=e.stepLines.indexOf(r);i>=0&&e.stepLines.splice(i,1)})}}class Go extends jo{constructor(e,t={}){super(e),this.styling=this._mergeWithDefaults(t||{}),this.stepDots=[],this.stepLines=[],this.visualContainer=new qr,this.dotRadius=this.styling.dotRadius,this.lineWidth=this.styling.lineWidth,this.visualSpacing=this.styling.visualSpacing,this.activeDotIndex=-1,this.dotsClickable=!0,this.nodeToStepMap=new Map,this.stepVisualizerHighlights=new Set,this.highlighting=new $q(this);const r=this.styling.textBoxOptions||{};this.textBoxManager=new Hq(this,this.highlighting,r),this.layoutManager=new Uq(this),this.addChild(this.visualContainer),this._initializeVisualElements(),this.setFilterLevel&&typeof this.setFilterLevel=="function"&&this.setFilterLevel(0),this.computeDimensions(),this.updateLayout()}toggleDot(e){if(typeof e!="number"||e<0||e>=this.stepDots.length)return;const t=this.stepDots[e];this._handleDotClick(t,e)}closeActiveDot(){var e,t,r,i;try{const s=((t=(e=this.textBoxManager)==null?void 0:e.stepTextBoxes)==null?void 0:t.length)||0;this._clearActiveDot(),this.textBoxManager&&typeof this.textBoxManager.clearAllTextBoxes=="function"&&this.textBoxManager.clearAllTextBoxes();const a=((i=(r=this.textBoxManager)==null?void 0:r.stepTextBoxes)==null?void 0:i.length)||0}catch{}}closeAllTextBoxes(){this.closeActiveDot()}forceCloseAll(){this.closeActiveDot()}_mergeWithDefaults(e){const t={dotColor:Fe.stepColor,dotRadius:Ta(0),dotStrokeWidth:2,activeDotColor:Fe.explainColor,expansionDotScale:.4,lineColor:Fe.stepColor,lineWidth:2,activeLineColor:Fe.explainColor,explainColor:Fe.explainColor,highlightColor:Fe.hiliteColor,visualSpacing:30,fixedVisualizerPosition:250,dotVerticalOffset:15,textBoxOptions:{backgroundColor:Fe.white,borderColor:"none",borderWidth:1,borderRadius:5,padding:8,fontSize:14,fontFamily:"Albert Sans, Arial, sans-serif",maxWidth:300,dropShadow:!0},enableAnimations:!0,hoverEffects:!0,backgroundColor:null,cornerRadius:null,pill:null};return this._deepMerge(t,e)}_deepMerge(e,t){const r={...e};for(const i in t)t.hasOwnProperty(i)&&(typeof t[i]=="object"&&t[i]!==null&&!Array.isArray(t[i])?r[i]=this._deepMerge(r[i]||{},t[i]):r[i]=t[i]);return r}setStyling(e){this.styling=this._mergeWithDefaults({...this.styling,...e}),this.dotRadius=this.styling.dotRadius,this.lineWidth=this.styling.lineWidth,this.visualSpacing=this.styling.visualSpacing,this._applyStylingToExistingElements(),e.visualSpacing!==void 0&&(this.visualSpacing=this.styling.visualSpacing),e.fixedVisualizerPosition!==void 0&&this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(this.styling.fixedVisualizerPosition),this.updateLayout()}getStyling(){return{...this.styling}}setStyleProperty(e,t){const r=e.split("."),i=r.pop(),s=r.reduce((a,o)=>(a[o]||(a[o]={}),a[o]),this.styling);s[i]=t,e==="dotRadius"&&(this.dotRadius=t),e==="lineWidth"&&(this.lineWidth=t),e==="visualSpacing"&&(this.visualSpacing=t),e==="fixedVisualizerPosition"&&this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(t),this._applyStylingToExistingElements(),this.updateLayout()}getStyleProperty(e){return e.split(".").reduce((t,r)=>t==null?void 0:t[r],this.styling)}_applyStylingToExistingElements(){this.stepDots.forEach((e,t)=>{if(e&&e.equationRef){const i=this.activeDotIndex===t?this.styling.activeDotColor:this.styling.dotColor;e.setFillColor(i),e.setStrokeColor(i),e.setStrokeWidth(this.styling.dotStrokeWidth);const s=e.equationRef.stepMark??0,a=this.styling.dotRadius||Ta(s);e.setWidthAndHeight(a*2,a*2),e.radius=a}}),this.stepLines.forEach((e,t)=>{if(e){const i=this.activeDotIndex>=0&&(e.toDotIndex===this.activeDotIndex||e.fromDotIndex===this.activeDotIndex)?this.styling.activeLineColor:this.styling.lineColor;e.setStrokeColor(i),e.setStrokeWidth(this.styling.lineWidth)}}),this.layoutManager&&this.layoutManager.expansionDots&&this.layoutManager.expansionDots.forEach(e=>{if(e){const t=this.styling.dotRadius||Ta(0),r=Math.max(3,t*this.styling.expansionDotScale);e.setWidthAndHeight(r*2,r*2),e.radius=r,e.setFillColor(this.styling.dotColor),e.setStrokeColor(this.styling.dotColor)}}),this.textBoxManager&&typeof this.textBoxManager.updateStyling=="function"&&this.textBoxManager.updateStyling(this.styling.textBoxOptions)}setBackgroundStyle(e={}){this.styling.backgroundColor=e.backgroundColor||this.styling.backgroundColor,this.styling.cornerRadius=e.cornerRadius||this.styling.cornerRadius,this.styling.pill=e.pill!==void 0?e.pill:this.styling.pill,typeof this.setDefaultEquationBackground=="function"&&this.setDefaultEquationBackground(e)}getBackgroundStyle(){return{backgroundColor:this.styling.backgroundColor,cornerRadius:this.styling.cornerRadius,pill:this.styling.pill}}setFixedVisualizerPosition(e){this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(e)}rebuildVisualizer(){this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights(),this.visualContainer&&this.removeChild(this.visualContainer),this.visualContainer=new qr,this.addChild(this.visualContainer),this._initializeVisualElements(),this.computeDimensions(),this.updateLayout()}_initializeVisualElements(){this._clearVisualElements(),this.nodeToStepMap.clear(),this.steps.filter(t=>t instanceof ut).forEach((t,r)=>{this._createStepDot(t,r),t.findAllNodes().forEach(i=>{this.nodeToStepMap.set(i.id,r)}),r>0&&this._createStepLine(r-1,r)}),this.layoutManager.updateVisualZOrder(),this.layoutManager.updateVisualLayout(!0)}_createStepDot(e,t){const r=e.stepMark??0,i=this.styling.dotRadius||Ta(r),s=new Tr;s.setWidthAndHeight(i*2,i*2);const a=this.styling.dotColor;return s.setFillColor(a),s.setStrokeColor(a),s.setStrokeWidth(this.styling.dotStrokeWidth),s.radius=i,s.equationRef=e,s.stepIndex=t,e.visible===!1&&s.hide(),this.layoutManager.updateDotClickability(s),this.stepDots.push(s),this.visualContainer.addChild(s),s}_createStepLine(e,t){var o,l;const r=new Ut,i=this.styling.lineColor;r.setStrokeColor(i),r.setStrokeWidth(this.styling.lineWidth),r.fromDotIndex=e,r.toDotIndex=t;const s=(o=this.stepDots[e])==null?void 0:o.equationRef,a=(l=this.stepDots[t])==null?void 0:l.equationRef;return((s==null?void 0:s.visible)===!1||(a==null?void 0:a.visible)===!1)&&r.hide(),this.stepLines.push(r),this.visualContainer.addChild(r),r}_clearVisualElements(){this.stepDots.forEach(e=>this.visualContainer.removeChild(e)),this.stepLines.forEach(e=>this.visualContainer.removeChild(e)),this.textBoxManager.clearAllTextBoxes(),this.stepDots=[],this.stepLines=[],this.activeDotIndex=-1}addStep(e,t={}){if(this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights(),super.addStep(e,t),e instanceof ut){const r=this.steps.filter(i=>i instanceof ut).indexOf(e);if(r>=0){const i=this._createStepDot(e,r);if(e.findAllNodes().forEach(s=>{this.nodeToStepMap.set(s.id,r)}),r>0&&this._createStepLine(r-1,r),i){const s=Ta(e.stepMark??0);i.setWidthAndHeight(s*2,s*2),i.radius=s}}}this.computeDimensions(),this.updateLayout()}getNodeStepNumber(e){return this.nodeToStepMap.get(e)}computeDimensions(){if(super.computeDimensions(),this.sequenceWidth=this.width,this.sequenceHeight=this.height,this.stepDots&&this.stepDots.length>0&&this.layoutManager){const e=this.dotRadius*3,r=(this.layoutManager.fixedVisualizerPosition||250)+this.visualSpacing+e;this.setWidthAndHeight(r,this.height)}}updateLayout(){super.updateLayout(),this.layoutManager&&(this.layoutManager.updateVisualLayout(!0),this.layoutManager.updateVisualVisibility(),this.layoutManager.updateAllLinePositions())}undoLastOperation(){this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights();const e=this.steps.length;return(super.undoLastOperation?super.undoLastOperation():!1)||this.steps.length<e?(this.rebuildVisualizer(),!0):!1}setDotColor(e,t){if(this.stepDots&&e>=0&&e<this.stepDots.length){const r=this.stepDots[e];r.setFillColor(t),r.setStrokeColor(t)}}setLineAboveColor(e,t){let r=this.stepLines.find(i=>i.toDotIndex===e&&i.isTemporary&&i.svgObject&&i.svgObject.style.display!=="none");r||(r=this.stepLines.find(i=>i.toDotIndex===e&&!i.isTemporary&&i.svgObject&&i.svgObject.style.display!=="none")),r&&r.setStrokeColor(t)}setDotsClickable(e){this.dotsClickable=e,e||(this._clearActiveDot(),this.highlighting.clearAllExplainHighlights()),this.stepDots.forEach(t=>{this.layoutManager.updateDotClickability(t)})}_handleDotClick(e,t){if(this.dotsClickable&&!(t<0||t>=this.stepDots.length)){if(this.stepDots[t]!==e){const r=this.stepDots.indexOf(e);if(r===-1)return;t=r}try{if(this.activeDotIndex===t)this._clearActiveDot();else{this.activeDotIndex!==-1&&this._clearActiveDot(),this.setActiveDot(t);const r=this.stepDots[t].equationRef,i=this.steps.indexOf(r),s=this._checkForOperationStep(i);this.highlighting.highlightAffectedNodes(t,s)}}catch(r){console.error("Error handling dot click:",r)}}}setActiveDot(e){if(!this.stepDots||e<0||e>=this.stepDots.length)return;this.activeDotIndex=e,this.activeDot=this.stepDots[e];const t=this.stepDots[e],r=this.styling.activeDotColor;t.setFillColor(r),t.setStrokeColor(r),this.setLineAboveColor(e,this.styling.activeLineColor),this.textBoxManager.createTextBoxForDot(e);const i=this.layoutManager.allowEquationRepositioning;this.layoutManager.allowEquationRepositioning=!1,this.layoutManager.updateVisualZOrder(),this.layoutManager.allowEquationRepositioning=i}_clearActiveDot(){try{if(this.activeDotIndex!==-1){const e=this.stepDots[this.activeDotIndex],t=this.styling.dotColor;e.setFillColor(t),e.setStrokeColor(t),this.setLineAboveColor(this.activeDotIndex,this.styling.lineColor),this.textBoxManager.removeTextBoxForDot(this.activeDotIndex),this.highlighting.clearAllExplainHighlights();const r=this.layoutManager.allowEquationRepositioning;this.layoutManager.allowEquationRepositioning=!1,this.layoutManager.updateVisualZOrder(),this.layoutManager.allowEquationRepositioning=r,this.activeDot=null,this.activeDotIndex=-1}}catch(e){console.error("Error clearing active dot:",e)}}_getSimplificationDataForDot(e){try{const t=this.stepDots[e];if(!t||!t.equationRef)return this._createDefaultSimplificationData("No equation found for this step");const r=this.steps.indexOf(t.equationRef);if(r===-1)return this._createDefaultSimplificationData("Step not found in sequence");const i=this._findPreviousVisibleEquationIndex(r),s=[],a=this.getSimplificationHistory(),o=this._getRelevantSimplifications(a,i,r);s.push(...o);for(let u=i+1;u<=r;u++){const c=this._checkForOperationStep(u);c&&s.push({message:c.message,affectedNodes:c.affectedNodes,stepNumber:u-1})}if(s.sort((u,c)=>u.stepNumber-c.stepNumber),s.length>0)return this._createMultipleSimplificationsData(s);const l=this._checkForSingleSimplification(a,r);return l||this._getFallbackSimplificationData(r)}catch(t){return console.error("Error getting simplification data for dot:",t),this._createDefaultSimplificationData("Error retrieving step data")}}getStepTextBoxes(){return this.textBoxManager.getStepTextBoxes()}_createDefaultSimplificationData(e){return{message:e,rawMessages:[e],ruleNames:["Step Description"],affectedNodes:[],resultNodeIds:[],resultProvSources:[],multipleSimplifications:!1}}_findPreviousVisibleEquationIndex(e){for(let t=e-1;t>=0;t--)if(this.steps[t]instanceof ut&&this.steps[t].visible!==!1)return t;return-1}_getRelevantSimplifications(e,t,r){const i=[];for(let s=t;s<r;s++){const a=e.filter(o=>o.stepNumber===s);a.length>0&&i.push(...a)}return i}_createMultipleSimplificationsData(e){const t=e.map(o=>o.message),r=e.map(o=>o.name||"Operation").filter(Boolean),i=[],s=[],a=[];return e.forEach(o=>{o.affectedNodes&&i.push(...o.affectedNodes),o.resultNodeId&&s.push(o.resultNodeId),o.resultProvSources&&a.push(...o.resultProvSources)}),{message:t.join(". "),rawMessages:t,ruleNames:r,affectedNodes:i,resultNodeIds:s,resultProvSources:a,multipleSimplifications:!0}}_checkForOperationStep(e){if(e>0){const t=this.steps[e-1];if(t instanceof Bs)return{message:`Applied ${t.operation} ${t.value} to both sides`,affectedNodes:[t.operatorLeft,t.valueLeft,t.operatorRight,t.valueRight]}}return null}_checkForSingleSimplification(e,t){const r=e.find(i=>i.stepNumber===t-1);return r?{message:r.message,rawMessages:[r.message],ruleNames:[r.name||"Operation"],affectedNodes:r.affectedNodes||[],resultNodeIds:r.resultNodeId?[r.resultNodeId]:[],resultProvSources:r.resultProvSources||[],multipleSimplifications:!1}:null}_getFallbackSimplificationData(e){const t=this.steps[e];if(e===0&&t.stepMark===0){const r=t.toString();return this._createDefaultSimplificationData(`Starting with equation: ${r}`)}else return t&&t.description?this._createDefaultSimplificationData(t.description):this._createDefaultSimplificationData("Step explanation not available")}}class bE{constructor(e,t,r={}){if(this.parentContainer=e,this.sequence=t,this.config={height:60,padding:6,spacing:8,borderRadius:30,fontFamily:"'Albert Sans', sans-serif",fontWeight:"500",colors:{background:Fe.mediumGray,button:"white",popup:Fe.lightGray,undo:"#87D143"},buttonSize:48,checkMarkSize:24,mainFontSize:32,inputFontSize:28,menuFontSize:24,inputWidth:120,popupDirection:"below",showUndoButton:!1,undoIconUrl:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzciIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCAzNyA0NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCjxwYXRoIGQ9Ik0xOC4zNjc2IDQzLjgzMDFDMTMuNTkxMyA0My44MjM3IDkuMDEyNTYgNDEuOTIzNCA1LjYzNTI1IDM4LjU0NTlDMi4yNTc5MiAzNS4xNjg1IDAuMzU3NjYgMzAuNTg5OSAwLjM1MTA3NCAyNS44MTM2QzAuMzUxMDc0IDI1LjMxOTQgMC41NDc0NDEgMjQuODQ1MiAwLjg5Njk2MSAyNC40OTU4QzEuMjQ2NDggMjQuMTQ2MiAxLjcyMDU1IDIzLjk0OTggMi4yMTQ4NSAyMy45NDk4QzIuNzA5MTUgMjMuOTQ5OCAzLjE4MzIyIDI0LjE0NjIgMy41MzI3NCAyNC40OTU4QzMuODgyMjYgMjQuODQ1MiA0LjA3ODYzIDI1LjMxOTQgNC4wNzg2MyAyNS44MTM2QzQuMDc4NjMgMjguNjM5NiA0LjkxNjY2IDMxLjQwMjIgNi40ODY3NSAzMy43NTIxQzguMDU2ODUgMzYuMTAxOSAxMC4yODg1IDM3LjkzMzQgMTIuODk5NCAzOS4wMTQ5QzE1LjUxMDMgNDAuMDk2NCAxOC4zODM1IDQwLjM3OTQgMjEuMTU1MyAzOS44MjhDMjMuOTI3MSAzOS4yNzY4IDI2LjQ3MyAzNy45MTU3IDI4LjQ3MTUgMzUuOTE3NUMzMC40Njk3IDMzLjkxOTEgMzEuODMwOCAzMS4zNzMxIDMyLjM4MTkgMjguNjAxM0MzMi45MzM0IDI1LjgyOTUgMzIuNjUwMyAyMi45NTYzIDMxLjU2ODggMjAuMzQ1NkMzMC40ODczIDE3LjczNDUgMjguNjU1OSAxNS41MDI5IDI2LjMwNiAxMy45MzI4QzIzLjk1NjIgMTIuMzYyNyAyMS4xOTM2IDExLjUyNDcgMTguMzY3NiAxMS41MjQ3SDEyLjE1NUMxMS42NjA3IDExLjUyNDcgMTEuMTg2NiAxMS4zMjgzIDEwLjgzNzEgMTAuOTc4OEMxMC40ODc2IDEwLjYyOTMgMTAuMjkxMiAxMC4xNTUyIDEwLjI5MTIgOS42NjA5QzEwLjI5MTIgOS4xNjY2IDEwLjQ4NzYgOC42OTI1MyAxMC44MzcxIDguMzQzMDFDMTEuMTg2NiA3Ljk5MzQ5IDExLjY2MDcgNy43OTcxMiAxMi4xNTUgNy43OTcxMkgxOC4zNjc2QzIzLjE0NTggNy43OTcxMiAyNy43Mjg1IDkuNjk1MjkgMzEuMTA3MSAxMy4wNzRDMzQuNDg2IDE2LjQ1MjggMzYuMzg0MSAyMS4wMzU0IDM2LjM4NDEgMjUuODEzNkMzNi4zODQxIDMwLjU5MTkgMzQuNDg2IDM1LjE3NDUgMzEuMTA3MSAzOC41NTMyQzI3LjcyODUgNDEuOTMyMSAyMy4xNDU4IDQzLjgzMDEgMTguMzY3NiA0My44MzAxWiIgZmlsbD0id2hpdGUiLz4NCjxwYXRoIGQ9Ik0xOC4zNjc1IDE4Ljk3OThDMTguMTIyNyAxOC45ODEgMTcuODc5OSAxOC45MzMzIDE3LjY1MzggMTguODM5NEMxNy40Mjc3IDE4Ljc0NTQgMTcuMjIyNyAxOC42MDczIDE3LjA1MDQgMTguNDMzMUw5LjU5NTM2IDEwLjk3OEM5LjI0NjM0IDEwLjYyODYgOS4wNTAyOSAxMC4xNTQ5IDkuMDUwMjkgOS42NjA5NkM5LjA1MDI5IDkuMTY3MDYgOS4yNDYzNCA4LjY5MzM2IDkuNTk1MzYgOC4zNDM4OUwxNy4wNTA0IDAuODg4Nzg5QzE3LjIyMTIgMC43MDU2NjcgMTcuNDI2OSAwLjU1ODgwMSAxNy42NTU1IDAuNDU2OTM5QzE3Ljg4NDIgMC4zNTUwNzggMTguMTMwOSAwLjMwMDMwOCAxOC4zODEyIDAuMjk1ODg0QzE4LjYzMTQgMC4yOTE0NjEgMTguODc5OSAwLjMzNzUwOCAxOS4xMTIgMC40MzEyNDRDMTkuMzQ0MSAwLjUyNDk3OSAxOS41NTQ5IDAuNjY0NDg5IDE5LjczMTggMC44NDE0NzNDMTkuOTA5IDEuMDE4NDYgMjAuMDQ4NCAxLjIyOTI5IDIwLjE0MjEgMS40NjEzNEMyMC4yMzYgMS42OTM0MiAyMC4yODIgMS45NDIgMjAuMjc3NSAyLjE5MjI0QzIwLjI3MyAyLjQ0MjUxIDIwLjIxODQgMi42ODkzIDIwLjExNjUgMi45MTc5MkMyMC4wMTQ2IDMuMTQ2NTQgMTkuODY3NyAzLjM1MjMgMTkuNjg0NiAzLjUyMjkzTDEzLjU0NjUgOS42NjA5NkwxOS42ODQ2IDE1Ljc5OUMyMC4wMzM3IDE2LjE0ODUgMjAuMjI5OCAxNi42MjIyIDIwLjIyOTggMTcuMTE2QzIwLjIyOTggMTcuNjEgMjAuMDMzNyAxOC4wODM3IDE5LjY4NDYgMTguNDMzMUMxOS41MTI2IDE4LjYwNzMgMTkuMzA3MyAxOC43NDU0IDE5LjA4MTIgMTguODM5NEMxOC44NTUxIDE4LjkzMzMgMTguNjEyNSAxOC45ODEgMTguMzY3NSAxOC45Nzk4WiIgZmlsbD0id2hpdGUiLz4NCjwvc3ZnPg0K",onUndo:null,...r},r.styles&&typeof r.styles=="object"){const s=r.styles;s.backgroundColor&&(this.config.colors.background=s.backgroundColor),s.buttonColor&&(this.config.colors.button=s.buttonColor),s.popupBackgroundColor&&(this.config.colors.popup=s.popupBackgroundColor),typeof s.borderRadius=="number"&&(this.config.borderRadius=s.borderRadius),typeof s.buttonSize=="number"&&(this.config.buttonSize=s.buttonSize),typeof s.mainFontSize=="number"&&(this.config.mainFontSize=s.mainFontSize),typeof s.inputFontSize=="number"&&(this.config.inputFontSize=s.inputFontSize),typeof s.menuFontSize=="number"&&(this.config.menuFontSize=s.menuFontSize),typeof s.inputWidth=="number"&&(this.config.inputWidth=s.inputWidth),typeof s.padding=="number"&&(this.config.padding=s.padding),typeof s.spacing=="number"&&(this.config.spacing=s.spacing)}r.backgroundColor&&(this.config.colors.background=r.backgroundColor),r.popupBackgroundColor&&(this.config.colors.popup=r.popupBackgroundColor),!!(r.popupBackgroundColor||r.styles&&r.styles.popupBackgroundColor)||(this.config.colors.popup=this.config.colors.background),this.state={activePopup:null,selectedOperation:"+",inputValue:""},this.elements={},this._render(),this._updateApplyButtonState()}_render(){this.elements.toolbarGroup=new Oe,this.parentContainer.addChild(this.elements.toolbarGroup),(this.config.x||this.config.y)&&this.elements.toolbarGroup.setPosition(this.config.x||0,this.config.y||0),this.elements.toolbarGroup.svgObject.style.userSelect="none",this.elements.background=new yt,this.elements.background.setWidthAndHeight(362,this.config.height),this.elements.background.setCornerRadius(this.config.borderRadius),this.elements.background.setFillColor(this.config.colors.background),this.elements.toolbarGroup.addChild(this.elements.background),this.elements.leftButton=this._createButton({text:this.state.selectedOperation,callback:()=>this._togglePopup("operations")}),this.elements.toolbarGroup.addChild(this.elements.leftButton),this.elements.middleInputButton=this._createButton({width:this.config.inputWidth,text:this.state.inputValue,fontSize:this.config.inputFontSize,cornerRadius:10,callback:()=>this._togglePopup("input")}),this.elements.toolbarGroup.addChild(this.elements.middleInputButton);const e='<svg width="43" height="33" viewBox="0 0 43 33" xmlns="http://www.w3.org/2000/svg"><rect x="9.86" y="28.63" width="40.04" height="5.74" transform="rotate(-45 9.86 28.63)" fill="black"/><rect x="13.9" y="32.69" width="19.64" height="5.74" transform="rotate(-135 13.9 32.69)" fill="black"/></svg>';this.elements.rightButton=this._createButton({svg:e,callback:()=>this._applyOperation()}),this.elements.toolbarGroup.addChild(this.elements.rightButton),this.config.showUndoButton&&(this.elements.undoButton=this._createButton({size:this.config.buttonSize,iconUrl:this.config.undoIconUrl,callback:()=>this._handleUndo()}),this.elements.undoButton.setFillColor(this.config.colors.undo||"#87D143"),this.elements.toolbarGroup.addChild(this.elements.undoButton)),this._updateToolbarLayout()}_bringToFront(e){try{const t=e==null?void 0:e.svgObject,r=t==null?void 0:t.parentNode;t&&r&&r.appendChild(t)}catch{}}_togglePopup(e){if(this.state.activePopup&&this.state.activePopup.type===e){this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null;return}this.state.activePopup&&(this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null);let t;e==="operations"?t=this._renderOperationsMenu():e==="input"&&(t=this.state.selectedOperation==="f"?this._renderFunctionMenu():this._renderDigitGrid()),t&&(this.elements.toolbarGroup.addChild(t),this.state.activePopup={type:e,group:t},this._bringToFront(this.elements.toolbarGroup),this._bringToFront(t))}_renderPopup(e,t){const r=new Oe;r.svgObject&&(r.svgObject.style.pointerEvents="auto");const i=e(),s=i.width+16,a=i.height+16,o=new yt;o.setWidthAndHeight(s,a),o.setCornerRadius(this.config.borderRadius),o.setFillColor(this.config.colors.popup),r.addChild(o),i.setPosition(8,8),r.addChild(i),r.width=s,r.height=a;const l=t.xpos+t.width/2-s/2,c=String(this.config.popupDirection||"below")==="above"?t.ypos-a-this.config.spacing:t.ypos+t.height+this.config.spacing;return r.setPosition(Math.round(l),Math.round(c)),r}_renderOperationsMenu(){const e=["f","÷","×","–","+"];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=this._createButton({text:r,fontSize:this.config.menuFontSize,callback:()=>this._selectOperation(r)});t.addChild(i)}),t.doVerticalLayout(),t},this.elements.leftButton)}_renderFunctionMenu(){const e=["sqrt","cos","sin","tan","ln"];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=this._createButton({width:80,height:48,cornerRadius:10,text:r,fontSize:this.config.inputFontSize,callback:()=>this._handleFunctionClick(r)});t.addChild(i)}),t.doVerticalLayout(),t},this.elements.middleInputButton)}_renderDigitGrid(){const e=[["1","2","3"],["4","5","6"],["7","8","9"],["←","0","x"]];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=new qr({spacer:this.config.spacing});r.forEach(s=>{const a=this._createButton({text:s,fontSize:this.config.inputFontSize,callback:()=>this._handleDigitClick(s)});i.addChild(a)}),i.doHorizontalLayout(),t.addChild(i)}),t.doVerticalLayout(),t},this.elements.middleInputButton)}_handleFunctionClick(e){this.setInputText(e),this._togglePopup("input")}_handleDigitClick(e){e==="←"?this.state.inputValue=this.state.inputValue.slice(0,-1):this.state.inputValue+=e,this.setInputText(this.state.inputValue)}setInputText(e){this.state.inputValue=e;const t=this.elements.middleInputButton;t.setText(e),t.buttonText.setFontSize(this.config.inputFontSize),this._updateApplyButtonState()}_selectOperation(e){var t;(this.state.selectedOperation==="f"||e==="f")&&this.setInputText(""),this.state.selectedOperation=e,this.elements.leftButton.setText(e),this._togglePopup("operations"),e==="f"&&((t=this.state.activePopup)==null?void 0:t.type)==="input"&&(this._togglePopup("input"),this._togglePopup("input"))}_applyOperation(){const e=this.state.selectedOperation,t=this.state.inputValue;if(!(!this.sequence||t==="")){if(e==="f")this.sequence.applyEquationFunction(t);else{const i={"÷":"divide","×":"multiply","–":"subtract","+":"add"}[e];let s,a=!1;const o=parseFloat(t);if(!isNaN(o)&&String(o)===t.trim())s=o,a=!0;else if(typeof window.math<"u"&&window.math.parse)try{s=window.math.parse(t),a=!0}catch{a=!1}i&&a&&this.sequence.applyEquationOperation(s,i)}this.setInputText(""),this.state.activePopup&&(this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null);try{typeof window<"u"&&(typeof window.refreshDisplayAndFilters=="function"&&window.refreshDisplayAndFilters(),typeof window.onOMDOperationApplied=="function"&&window.onOMDOperationApplied(this.sequence))}catch{}}}_createButton({width:e,height:t,size:r,text:i,svg:s,iconUrl:a,fontSize:o,cornerRadius:l,callback:u}){const c=new Xn,h=e||r||this.config.buttonSize,f=t||r||this.config.buttonSize;if(c.setWidthAndHeight(h,f),c.setCornerRadius(l!==void 0?l:h/2),c.setFillColor(this.config.colors.button),c.setText(i||""),c.setFontSize(o||this.config.mainFontSize),c.setFontFamily(this.config.fontFamily),c.buttonText.setFontWeight(this.config.fontWeight),c.buttonText.setPosition(h/2,f/2+(o||this.config.mainFontSize)/3),s){const d="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(s);c.addImage(d,this.config.checkMarkSize,this.config.checkMarkSize)}else if(a){const d=this.config.checkMarkSize;c.addImage(a,d,d)}return c.setClickCallback(u),c}_updateApplyButtonState(){const e=this.elements.rightButton;this.state.inputValue.length>0?(e.setOpacity(1),e.setClickCallback(()=>this._applyOperation())):(e.setOpacity(.5),e.setClickCallback(null))}_updateToolbarLayout(){const e=this.config.buttonSize*2+this.config.inputWidth+this.config.spacing*2+this.config.padding*2;this.elements.background.setWidth(e);const t=this.config.padding;let r=this.config.padding;if(this.elements.leftButton.setPosition(r,t),r+=this.elements.leftButton.width+this.config.spacing,this.elements.middleInputButton.setPosition(r,t),r+=this.elements.middleInputButton.width+this.config.spacing,this.elements.rightButton.setPosition(r,t),this.elements.undoButton){const i=this.elements.background.width+this.config.spacing;this.elements.undoButton.setPosition(i,t)}}_handleUndo(){if(typeof this.config.onUndo=="function"){try{this.config.onUndo(this.sequence)}catch{}return}try{typeof window<"u"&&typeof window.onOMDToolbarUndo=="function"&&window.onOMDToolbarUndo(this.sequence)}catch{}}}class xE extends Oe{constructor(e=[],t={}){var s,a,o,l,u,c;if(super(),this.options={...t},this.toolbarOptions=null,typeof t.toolbar=="object"?this.toolbarOptions={enabled:!0,...t.toolbar}:t.toolbar===!0?this.toolbarOptions={enabled:!0}:t.toolbar===!1&&(this.toolbarOptions={enabled:!1}),this.stylingOptions=t.styling||null,t.stepVisualizer){const h=((s=this.stylingOptions)==null?void 0:s.stepVisualizer)||{};this.sequence=new Go(e,h)}else this.sequence=new jo(e);if((a=this.stylingOptions)!=null&&a.equationBackground&&this.sequence.setDefaultEquationBackground(this.stylingOptions.equationBackground),t.stepVisualizer&&((o=this.stylingOptions)!=null&&o.stepVisualizerBackground)&&typeof this.sequence.setBackgroundStyle=="function"&&this.sequence.setBackgroundStyle(this.stylingOptions.stepVisualizerBackground),(l=this.toolbarOptions)!=null&&l.enabled){const h={...this.toolbarOptions};h.showUndoButton&&!h.onUndo&&(h.onUndo=()=>{if(typeof window<"u"&&typeof window.onOMDToolbarUndo=="function")try{window.onOMDToolbarUndo(this.sequence)}catch{}}),this.toolbar=new bE(this,this.sequence,h)}this.overlayPadding=typeof((u=this.toolbarOptions)==null?void 0:u.overlayPadding)=="number"?this.toolbarOptions.overlayPadding:34,this.layoutGroup=new qr,this.layoutGroup.setSpacer(16),this.layoutGroup.addChild(this.sequence),this._overlayChildren=[];const r=((c=this.toolbarOptions)==null?void 0:c.position)||this.options.toolbarPosition,i=r==="bottom"||r==="overlay-bottom";this.toolbar&&(i?this.addChild(this.toolbar.elements.toolbarGroup):this.layoutGroup.addChild(this.toolbar.elements.toolbarGroup)),this.addChild(this.layoutGroup),this.updateLayout()}updateLayout(){var r;this.sequence.updateLayout(),this.layoutGroup.doVerticalLayout();const e=((r=this.toolbarOptions)==null?void 0:r.position)||this.options.toolbarPosition,t=e==="bottom"||e==="overlay-bottom";if(this.toolbar&&!t){const i=this.sequence.width,s=this.toolbar.elements.background.width,a=this.toolbar.elements.toolbarGroup;a.setPosition((i-s)/2,a.ypos)}this.width=this.layoutGroup.width,this.height=this.layoutGroup.height}initialize(){this.sequence&&typeof this.sequence.initialize=="function"?this.sequence.initialize():this.sequence&&(typeof this.sequence.computeDimensions=="function"&&this.sequence.computeDimensions(),typeof this.sequence.updateLayout=="function"&&this.sequence.updateLayout()),this.updateLayout()}setFontSize(e){this.sequence&&typeof this.sequence.setFontSize=="function"&&this.sequence.setFontSize(e),this.updateLayout()}closeActiveDot(){this.sequence&&typeof this.sequence.closeActiveDot=="function"&&this.sequence.closeActiveDot()}closeAllTextBoxes(){this.sequence&&typeof this.sequence.closeAllTextBoxes=="function"?this.sequence.closeAllTextBoxes():this.sequence&&typeof this.sequence.closeActiveDot=="function"&&this.sequence.closeActiveDot()}forceCloseAll(){this.sequence&&typeof this.sequence.forceCloseAll=="function"?this.sequence.forceCloseAll():this.closeAllTextBoxes()}getSequence(){return this.sequence}getOverlayPadding(){return this.overlayPadding}getToolbarVisualHeight(){return this.toolbar&&this.toolbar.elements&&this.toolbar.elements.background&&this.toolbar.elements.background.height||0}isToolbarOverlay(){var t;const e=((t=this.toolbarOptions)==null?void 0:t.position)||this.options.toolbarPosition;return!!(this.toolbar&&(e==="bottom"||e==="overlay-bottom"))}positionToolbarOverlay(e,t,r=16){var y;if(!this.toolbar||!this.isToolbarOverlay())return;const i=this.toolbar.elements.toolbarGroup,s=this.toolbar.elements.background.width,a=this.toolbar.elements.background.height,o=this.xpos||0,l=this.ypos||0,u=typeof this.scale=="number"&&this.scale>0?this.scale:1,c=typeof r=="number"?r:this.overlayPadding;let h=(e-s)/2,f=t-a-c;h=Math.round(h),f=Math.round(f);const d=(h-o)/u,p=(f-l)/u;let m=i.svgObject;for(;m&&m.tagName!=="svg"&&m.parentElement;)m=m.parentElement;(y=m==null?void 0:m.getAttribute)!=null&&y.call(m,"viewBox"),typeof i.setScale=="function"&&i.setScale(1/u),i.setPosition(d,p),i.svgObject&&(i.svgObject.style.display="block",i.svgObject.style.zIndex="1000");try{this.updateOverlayChildren(e,t,r)}catch{}}addOverlayChild(e,t,r,i={}){var g,b,w,x;const{anchor:s="toolbar-center",offsetX:a=0,offsetY:o=0,padding:l=16,counterScale:u=!0,addToStack:c=!0,customCoords:h=null}=i||{};if(!e||typeof t!="number"||typeof r!="number")return null;const f=this.xpos||0,d=this.ypos||0,p=typeof this.scale=="number"&&this.scale>0?this.scale:1;let m=0,y=0;if(s==="custom"&&h&&typeof h.x=="number"&&typeof h.y=="number")m=Math.round(h.x),y=Math.round(h.y);else if(s.startsWith("toolbar")){if(!this.toolbar)return null;const N=((b=(g=this.toolbar.elements)==null?void 0:g.background)==null?void 0:b.width)||0,D=((x=(w=this.toolbar.elements)==null?void 0:w.background)==null?void 0:x.height)||0,C=(t-N)/2,A=C+N,E=C+N/2;y=Math.round(r-D-(typeof l=="number"?l:this.overlayPadding)),s==="toolbar-center"?m=Math.round(E):s==="toolbar-left"?m=Math.round(C):s==="toolbar-right"?m=Math.round(A):m=Math.round(E)}else if(s.startsWith("top")){const N=Math.round(typeof l=="number"?l:16),D=Math.round(typeof l=="number"?l:16),C=Math.round(t-(typeof l=="number"?l:16));y=N,s==="top-left"?m=D:s==="top-center"?m=Math.round(t/2):s==="top-right"?m=C:m=D}else m=Math.round(t/2),y=Math.round(r/2);m=Math.round(m+(a||0)),y=Math.round(y+(o||0));const v=(m-f)/p,S=(y-d)/p;if(u&&e&&typeof e.setScale=="function")try{e.setScale(1/p)}catch{}if(e&&typeof e.setPosition=="function")try{e.setPosition(v,S)}catch{}if(c)try{this.addChild(e)}catch{try{this.layoutGroup.addChild(e)}catch{}}try{const N={anchor:s,offsetX:a,offsetY:o,padding:l,counterScale:u,addToStack:c,customCoords:h};this._overlayChildren.push({child:e,opts:N})}catch{}if(e&&e.svgObject){try{e.svgObject.style.zIndex="1001"}catch{}try{e.svgObject.style.display="block"}catch{}}return e}updateOverlayChildren(e,t,r=16){var o,l,u,c;if(!Array.isArray(this._overlayChildren)||this._overlayChildren.length===0)return;const i=this.xpos||0,s=this.ypos||0,a=typeof this.scale=="number"&&this.scale>0?this.scale:1;for(const h of this._overlayChildren){if(!h||!h.child)continue;const f=h.child,d=h.opts||{},p=d.anchor||"toolbar-center",m=d.offsetX||0,y=d.offsetY||0,v=typeof d.padding=="number"?d.padding:r,S=typeof d.counterScale=="boolean"?d.counterScale:!0,g=d.customCoords||null;let b=0,w=0;if(p==="custom"&&g&&typeof g.x=="number"&&typeof g.y=="number")b=Math.round(g.x+m),w=Math.round(g.y+y);else if(p.startsWith("toolbar")){if(!this.toolbar)continue;const D=((l=(o=this.toolbar.elements)==null?void 0:o.background)==null?void 0:l.width)||0,C=((c=(u=this.toolbar.elements)==null?void 0:u.background)==null?void 0:c.height)||0,A=(e-D)/2,E=A+D,F=A+D/2;w=Math.round(t-C-v+y),p==="toolbar-center"?b=Math.round(F+m):p==="toolbar-left"?b=Math.round(A+m):p==="toolbar-right"?b=Math.round(E+m):b=Math.round(F+m)}else if(p.startsWith("top")){const D=Math.round(v),C=Math.round(v),A=Math.round(e-v);w=D+y,p==="top-left"?b=C+m:p==="top-center"?b=Math.round(e/2)+m:p==="top-right"?b=A+m:b=C+m}else b=Math.round(e/2+m),w=Math.round(t/2+y);const x=(b-i)/a,N=(w-s)/a;if(S&&f&&typeof f.setScale=="function")try{f.setScale(1/a)}catch{}if(f&&typeof f.setPosition=="function")try{f.setPosition(x,N)}catch{}}}removeOverlayChild(e){if(!e||!Array.isArray(this._overlayChildren))return!1;let t=-1;for(let r=0;r<this._overlayChildren.length;r++)if(this._overlayChildren[r].child===e){t=r;break}if(t===-1)return!1;this._overlayChildren.splice(t,1);try{this.removeChild(e)}catch{}return!0}getToolbar(){return this.toolbar}undoLastOperation(){var i,s;const e=this.sequence;if(!e||!Array.isArray(e.steps)||e.steps.length===0)return!1;let t=-1;for(let a=e.steps.length-1;a>=0;a--){const o=e.steps[a],l=(i=o==null?void 0:o.constructor)==null?void 0:i.name;if(o instanceof ut||l==="omdEquationNode"){t=a;break}}if(t===-1)return!1;let r=t;for(let a=t;a>=0;a--){const o=e.steps[a],l=(s=o==null?void 0:o.constructor)==null?void 0:s.name;if(o instanceof Bs||l==="omdOperationDisplayNode"){r=a;break}}for(let a=e.steps.length-1;a>=r;a--){const o=e.steps[a];try{e.removeChild(o)}catch{}}if(e.steps.splice(r),e.argumentNodeList.steps=e.steps,Array.isArray(e.stepDescriptions)&&(e.stepDescriptions.length=e.steps.length),Array.isArray(e.importanceLevels)&&(e.importanceLevels.length=e.steps.length),typeof e.currentStepIndex=="number"&&e.currentStepIndex>=e.steps.length&&(e.currentStepIndex=Math.max(0,e.steps.length-1)),typeof e.rebuildNodeMap=="function"&&e.rebuildNodeMap(),typeof e.computeDimensions=="function"&&e.computeDimensions(),typeof e.updateLayout=="function"&&e.updateLayout(),typeof e.rebuildVisualizer=="function")try{e.highlighting&&typeof e.highlighting.clearAllExplainHighlights=="function"&&e.highlighting.clearAllExplainHighlights(),e.rebuildVisualizer()}catch{}else if(typeof e._initializeVisualElements=="function")try{e.highlighting&&typeof e.highlighting.clearAllExplainHighlights=="function"&&e.highlighting.clearAllExplainHighlights(),e._initializeVisualElements(),typeof e.computeDimensions=="function"&&e.computeDimensions(),typeof e.updateLayout=="function"&&e.updateLayout()}catch{}try{const a=l=>{var u;return l instanceof ut||((u=l==null?void 0:l.constructor)==null?void 0:u.name)==="omdEquationNode"},o=Array.isArray(e.steps)?e.steps.filter(a).length:0;if(Array.isArray(e.stepDots)&&e.visualContainer){const l=new Set(e.steps.filter(a)),u=[];for(const c of e.stepDots)if(!c||!c.equationRef||!l.has(c.equationRef))try{e.visualContainer.removeChild(c)}catch{}else u.push(c);e.stepDots=u}if(e.visualContainer&&Array.isArray(e.visualContainer.childList)){const l=new Set([...e.stepDots||[],...e.stepLines||[]]),u=[];e.visualContainer.childList.forEach(c=>{l.has(c)||u.push(c)}),u.forEach(c=>{try{e.visualContainer.removeChild(c)}catch{}})}if(Array.isArray(e.stepDots)&&e.visualContainer)for(;e.stepDots.length>o;){const l=e.stepDots.pop();try{e.visualContainer.removeChild(l)}catch{}}if(Array.isArray(e.stepLines)&&e.visualContainer){const l=Math.max(0,o-1);for(;e.stepLines.length>l;){const u=e.stepLines.pop();try{e.visualContainer.removeChild(u)}catch{}}}if(e.layoutManager)try{e.layoutManager.updateVisualLayout(!0),e.layoutManager.updateVisualVisibility(),e.layoutManager.updateAllLinePositions()}catch{}}catch{}return this.updateLayout(),!0}getSvg(){return this.svgObject}}class Vq{constructor(e,t={}){this.container=e;const{stepVisualizer:r=!1,stackOptions:i=null,math:s=typeof window<"u"&&window.math?window.math:null,...a}=t||{};this.options={fontSize:32,centerContent:!0,topMargin:40,bottomMargin:16,observeResize:!0,expandViewboxToFitContent:!0,fitToContent:!0,autoScale:!1,maxScale:1,edgePadding:16,autoCloseStepVisualizer:!0,stepVisualizer:r,stackOptions:i,math:s,...a},this.svg=new j0,this.node=null,this._suppressResizeObserver=!1,this._lastViewbox=null,this._lastContentExtents=null,this._viewboxLocked=!1,this._viewboxLockThreshold=8,this._setupSVG()}_setupSVG(){const e=this.container.offsetWidth||800,t=this.container.offsetHeight||600;this.svg.setViewbox(e,t),this.svg.svgObject.style.width="100%",this.svg.svgObject.style.height="100%",this.svg.svgObject.style.verticalAlign="middle",this.svg.svgObject.style.overflow="hidden",this.container.appendChild(this.svg.svgObject);try{const r="http://www.w3.org/2000/svg";this._contentGroup=document.createElementNS(r,"g"),this._contentGroup.setAttribute("id","omd-content-root"),this.svg.svgObject.appendChild(this._contentGroup),this._contentOffsetX=0,this._contentOffsetY=0}catch{this._contentGroup=null}this.options.observeResize&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this._handleResize()}),this.resizeObserver.observe(this.container))}_handleResize(){if(this._suppressResizeObserver)return;const e=this.container.offsetWidth,t=this.container.offsetHeight;this._lastContainerWidth===e&&this._lastContainerHeight===t||(this._lastContainerWidth=e,this._lastContainerHeight=t,this.svg.setViewbox(e,t),this.options.centerContent&&this.node&&this.centerNode(),this._repositionOverlayToolbar(),this.options.debugExtents&&this._drawDebugOverlays())}_syncViewboxToContainer(e=this.container.offsetWidth||0,t=this.container.offsetHeight||0){!e||!t||(this.svg.setViewbox(e,t),this.svg.setWidthAndHeight(e,t),this._lastViewbox=`0 0 ${e} ${t}`)}_ensureViewboxFits(e,t){if(!this.node)return;const r=10;let i=null;try{const C=this._collectNodeExtents(this.node);C&&(i={minX:C.minX,minY:C.minY,maxX:C.maxX,maxY:C.maxY})}catch{i=null}if(i||(i=this._computeNodeExtents(this.node)),!i)return;const s=Math.floor(i.minX-r),a=Math.floor(i.minY-r),o=Math.ceil(i.maxX+r),l=Math.ceil(i.maxY+r),u=this.svg.svgObject.getAttribute("viewBox")||"";let c=0,h=0,f=0,d=0;if(u){const C=u.split(/\s+/).map(Number).filter(A=>!isNaN(A));C.length===4&&(c=C[0],h=C[1],f=C[2],d=C[3])}const p=c,m=h,y=Math.max(c+f,o),v=Math.max(h+d,l),S=Math.max(f,y-p),g=Math.max(d,v-m),b=Math.abs(S-f),w=Math.abs(g-d),x=1e4;if(S>x||g>x){console.warn("omdDisplay: viewBox growth capped to prevent runaway expansion",S,g);return}if(b<.5&&w<.5)return;const N=`${s},${a},${o},${l}`;if(this._lastContentExtents===N&&w>0&&g>d)return;if(this._viewboxLocked){const C=S-f,A=g-d;if(C<this._viewboxLockThreshold&&A<this._viewboxLockThreshold)return}const D=`${p} ${m} ${S} ${g}`;if(this._lastViewbox!==D){this._suppressResizeObserver=!0;try{this.svg.svgObject.setAttribute("viewBox",D)}finally{setTimeout(()=>{this._suppressResizeObserver=!1},0)}this._lastViewbox=D,this._lastContentExtents=N,w<2&&b<2&&!this._viewboxLocked&&(this._viewboxLocked=!0)}}_computeNodeExtents(e){if(!e)return null;const t=new Set,r=[{node:e,absX:e.xpos||0,absY:e.ypos||0}];let i=1/0,s=1/0,a=-1/0,o=-1/0;for(;r.length;){const{node:l,absX:u,absY:c}=r.pop();if(!l||t.has(l))continue;t.add(l);const h=l.width||0,f=l.height||0,d=u,p=c;if(i=Math.min(i,d),s=Math.min(s,p),a=Math.max(a,d+h),o=Math.max(o,p+f),Array.isArray(l.childList))for(const m of l.childList){if(!m)continue;const y=(m.xpos||0)+d,v=(m.ypos||0)+p;r.push({node:m,absX:y,absY:v})}if(l.argumentNodeList){for(const m of Object.values(l.argumentNodeList))if(Array.isArray(m))for(const y of m){if(!y)continue;const v=(y.xpos||0)+d,S=(y.ypos||0)+p;r.push({node:y,absX:v,absY:S})}else if(m){const y=(m.xpos||0)+d,v=(m.ypos||0)+p;r.push({node:m,absX:y,absY:v})}}}return i===1/0?null:{minX:i,minY:s,maxX:a,maxY:o}}_collectNodeExtents(e){if(!e)return null;const t=new Set,r=[{node:e,absX:e.xpos||0,absY:e.ypos||0,parent:null}],i=[];let s=1/0,a=1/0,o=-1/0,l=-1/0;for(;r.length;){const{node:u,absX:c,absY:h,parent:f}=r.pop();if(!u||t.has(u))continue;t.add(u);let d=c,p=h,m=d,y=p,v=d,S=p;try{if(u.svgObject&&typeof u.svgObject.getBBox=="function"&&typeof u.svgObject.getCTM=="function"){const g=u.svgObject.getBBox(),b=u.svgObject.getCTM(),x=[{x:g.x,y:g.y},{x:g.x+g.width,y:g.y},{x:g.x,y:g.y+g.height},{x:g.x+g.width,y:g.y+g.height}].map(N=>({x:b.a*N.x+b.c*N.y+b.e,y:b.b*N.x+b.d*N.y+b.f}));m=Math.min(...x.map(N=>N.x)),y=Math.min(...x.map(N=>N.y)),v=Math.max(...x.map(N=>N.x)),S=Math.max(...x.map(N=>N.y)),d=m,p=y}else{const g=u.width||0,b=u.height||0;d=c,p=h,m=d,y=p,v=d+g,S=p+b}}catch{const b=u.width||0,w=u.height||0;d=c,p=h,m=d,y=p,v=d+b,S=p+w}if(i.push({node:u,minX:m,minY:y,maxX:v,maxY:S,parent:f}),s=Math.min(s,m),a=Math.min(a,y),o=Math.max(o,v),l=Math.max(l,S),Array.isArray(u.childList))for(const g of u.childList){if(!g)continue;const b=(g.xpos||0)+d,w=(g.ypos||0)+p;r.push({node:g,absX:b,absY:w,parent:u})}if(u.argumentNodeList){for(const g of Object.values(u.argumentNodeList))if(Array.isArray(g))for(const b of g){if(!b)continue;const w=(b.xpos||0)+d,x=(b.ypos||0)+p;r.push({node:b,absX:w,absY:x,parent:u})}else if(g){const b=(g.xpos||0)+d,w=(g.ypos||0)+p;r.push({node:g,absX:b,absY:w,parent:u})}}}return s===1/0?null:{nodes:i,minX:s,minY:a,maxX:o,maxY:l}}_clearDebugOverlays(){if(!this.svg||!this.svg.svgObject)return;const e=this.svg.svgObject.querySelector("#omd-debug-overlays");e&&e.remove()}_drawDebugOverlays(){if(!this.options.debugExtents||!this.svg||!this.svg.svgObject||!this.node)return;this._clearDebugOverlays();const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"g");t.setAttribute("id","omd-debug-overlays"),t.setAttribute("pointer-events","none");const r=this._collectNodeExtents(this.node);if(!r)return;const{nodes:i,minX:s,minY:a,maxX:o,maxY:l}=r,u=document.createElementNS(e,"rect");u.setAttribute("x",String(s)),u.setAttribute("y",String(a)),u.setAttribute("width",String(o-s)),u.setAttribute("height",String(l-a)),u.setAttribute("fill","none"),u.setAttribute("stroke","blue"),u.setAttribute("stroke-dasharray","6 4"),u.setAttribute("stroke-width","0.8"),t.appendChild(u);const c=this.svg.svgObject.getAttribute("viewBox")||"";if(c){const f=c.split(/\s+/).map(Number).filter(d=>!isNaN(d));if(f.length===4){const[d,p,m,y]=f,v=document.createElementNS(e,"rect");v.setAttribute("x",String(d)),v.setAttribute("y",String(p)),v.setAttribute("width",String(m)),v.setAttribute("height",String(y)),v.setAttribute("fill","none"),v.setAttribute("stroke","orange"),v.setAttribute("stroke-width","1"),v.setAttribute("opacity","0.9"),t.appendChild(v)}}const h=[];for(const f of i){const d=document.createElementNS(e,"rect");d.setAttribute("x",String(f.minX)),d.setAttribute("y",String(f.minY)),d.setAttribute("width",String(Math.max(0,f.maxX-f.minX))),d.setAttribute("height",String(Math.max(0,f.maxY-f.minY))),d.setAttribute("fill","none"),d.setAttribute("stroke-width","0.6");let p="green";if(f.parent){const m=(f.parent.xpos||0)+(f.parent._absX||0),y=(f.parent.ypos||0)+(f.parent._absY||0),v=i.find(x=>x.node===f.parent),S=v?v.minX:m,g=v?v.minY:y,b=v?v.maxX:S+(f.parent.width||0),w=v?v.maxY:g+(f.parent.height||0);(f.minX<S||f.minY<g||f.maxX>b||f.maxY>w)&&(p="red",h.push({node:f.node,bounds:f}))}d.setAttribute("stroke",p),d.setAttribute("opacity",p==="red"?"0.9":"0.6"),t.appendChild(d)}h.length&&console.warn("omdDisplay: debugExtents found overflowing nodes:",h.map(f=>{var d;return{type:(d=f.node)==null?void 0:d.type,bounds:f.bounds}})),this.svg.svgObject.appendChild(t)}centerNode(){var m;if(!this.node)return;if(this._centerCallCount||(this._centerCallCount=0),this._centerCallCount++,this._centerCallCount>500){console.warn("omdDisplay: excessive centerNode calls detected; halting further centering to prevent loop");return}const e=this.container.offsetWidth||0,t=this.container.offsetHeight||0;if(this.options.autoCloseStepVisualizer&&this.node)try{typeof this.node.forceCloseAll=="function"?this.node.forceCloseAll():typeof this.node.closeAllTextBoxes=="function"?this.node.closeAllTextBoxes():typeof this.node.closeActiveDot=="function"&&this.node.closeActiveDot()}catch{}let r=this.node.width||0,i=this.node.height||0;if(this.node.getSequence){const y=this.node.getSequence();if(y&&(y.width&&y.height&&(r=y.sequenceWidth||y.width,i=y.sequenceHeight||y.height),y.getCurrentStep)){const v=y.getCurrentStep();if(v&&v.width&&v.height){const S=y.sequenceWidth||v.width,g=y.sequenceHeight||v.height;r=Math.max(r,S),i=Math.max(i,g)}}}let s=1;if(this.options.autoScale&&r>0&&i>0){if(this.options.autoCloseStepVisualizer&&this.node)try{typeof this.node.closeActiveDot=="function"?this.node.closeActiveDot():typeof this.node.closeAllTextBoxes=="function"&&this.node.closeAllTextBoxes()}catch{}let y=!1;if(this.node&&(y=((m=this.node.constructor)==null?void 0:m.name)==="omdStepVisualizer"||this.node.type==="omdStepVisualizer"||typeof Go<"u"&&this.node instanceof Go),y){const v=this.node&&typeof this.node.scale=="number"?this.node.scale:void 0;s=v&&v>0?v:1}else{const v=this.options.edgePadding||0,S=this.options.topMargin||0;let b=this.options.bottomMargin||0;if(this.node&&typeof this.node.isToolbarOverlay=="function"&&this.node.isToolbarOverlay()){const A=typeof this.node.getToolbarVisualHeight=="function"?this.node.getToolbarVisualHeight():0;b+=A+(this.node.getOverlayPadding?this.node.getOverlayPadding():16)}const w=Math.max(0,e-v*2),x=Math.max(0,t-(S+b)),N=w>0?w/r:1,D=x>0?x/i:1,C=typeof this.options.maxScale=="number"?this.options.maxScale:1;s=Math.min(N,D,C),(!isFinite(s)||s<=0)&&(s=1)}}typeof this.node.setScale=="function"&&this.node.setScale(s);let a;if(this.node.type==="omdEquationSequenceNode"&&this.node.alignPointX!==void 0)a=e/2-this.node.alignPointX*s;else{const y=r*s;a=(e-y)/2}const o=r*s,l=i*s,u=Math.max(0,t-(this.options.topMargin||0)-(this.options.bottomMargin||0)),c=(this.options.topMargin||0)+Math.max(0,(u-l)/2),h=l+(this.options.topMargin||0)+(this.options.bottomMargin||0),f=o>e,d=h>t,p=`${r}x${i}x${s}`;if(this._lastCenterSignature===p&&!f&&!d){this.node.setPosition&&this.node.setPosition(a,c);return}f||d?(this.node.setScale&&this.node.setScale(s),this.options.expandViewboxToFitContent!==!1?this._ensureViewboxFits(r,i):this._syncViewboxToContainer(e,t),this._repositionOverlayToolbar(),d?(this.container.style.overflowY="auto",this.container.style.overflowX="hidden"):this.container.style.overflow="hidden",this.options.debugExtents&&this._drawDebugOverlays()):(this.node.setPosition(a,c),this._repositionOverlayToolbar(),this.options.expandViewboxToFitContent!==!1?this._ensureViewboxFits(r,i):this._syncViewboxToContainer(e,t),h>t?(this.container.style.overflowY="auto",this.container.style.overflowX="hidden"):this.container.style.overflow="hidden",this.options.debugExtents&&this._drawDebugOverlays()),this._lastCenterSignature=p}_getMathInstance(){return this.options.math?this.options.math:typeof window<"u"&&window.math?window.math:null}_createNodeFromSegment(e,t){try{if(e.includes("="))return ut.fromString(e);if(!t||typeof t.parse!="function")throw new Error("math.js parser is unavailable");const r=t.parse(e),i=_t(r);return new i(r)}catch(r){const i=(r==null?void 0:r.message)||String(r);throw new Error(`Failed to parse expression "${e}": ${i}`,{cause:r})}}_createNodesFromString(e){const t=(e||"").split(";").map(i=>i.trim()).filter(Boolean);if(!t.length)throw new Error("omdDisplay.render() received an empty expression string.");const r=this._getMathInstance();return t.map(i=>this._createNodeFromSegment(i,r))}_buildStackOptions(){const e={};return typeof this.options.stepVisualizer=="boolean"&&(e.stepVisualizer=this.options.stepVisualizer),this.options.styling&&(e.styling=this.options.styling),Object.prototype.hasOwnProperty.call(this.options,"toolbar")&&(e.toolbar=this.options.toolbar),this.options.stackOptions&&typeof this.options.stackOptions=="object"?{...e,...this.options.stackOptions}:e}_createStackFromSteps(e){if(!e||!e.length)throw new Error("omdDisplay.render() received no steps to render.");return new xE(e,this._buildStackOptions())}fitToContent(){if(!this.node)return;let e=0,t=0,r=0,i=0,s=0,a=0;if(this.node.getSequence){const c=this.node.getSequence();if(c&&c.width&&c.height){if(r=c.sequenceWidth||c.width,i=c.sequenceHeight||c.height,c.getCurrentStep){const h=c.getCurrentStep();h&&h.width&&h.height&&(s=c.sequenceWidth||h.width,a=c.sequenceHeight||h.height)}e=Math.max(r,s),t=Math.max(i,a)}}(e===0||t===0)&&this.node.width&&this.node.height&&(e=this.node.width,t=this.node.height),(e===0||t===0)&&(e=200,t=60);const o=10,l=e+o*2,u=t+o*2;this.node&&this.node.setPosition&&this.node.setPosition(o,o),this.svg.setViewbox(l,u),this.svg.setWidthAndHeight(l,u),this.container.style.width=`${l}px`,this.container.style.height=`${u}px`,this.options.debugExtents?this._drawDebugOverlays():this._clearDebugOverlays()}render(e){if(this.node&&this.removeChild(this.node),typeof e=="string"){const r=this._createNodesFromString(e);this.node=this._createStackFromSteps(r)}else if(Array.isArray(e)){const r=e.flatMap(i=>typeof i=="string"?this._createNodesFromString(i):i).filter(Boolean);this.node=this._createStackFromSteps(r)}else this.node=e;if(!this.node)throw new Error("omdDisplay.render() was unable to create a node from the provided expression.");const t=this.node.getSequence?this.node.getSequence():null;if(t&&(t.setFontSize(this.options.fontSize),t.updateStepsVisibility(r=>(r.stepMark??0)===t.getFilterLevel())),this._contentGroup&&this.node&&this.node.svgObject)try{this._contentGroup.appendChild(this.node.svgObject)}catch{this.svg.addChild(this.node)}else this.svg.addChild(this.node);if(this.options.fontFamily&&this.setFont(this.options.fontFamily,this.options.fontWeight||"400"),this.options.fitToContent?this.fitToContent():this.options.centerContent&&this.centerNode(),this._repositionOverlayToolbar(),this.options.expandViewboxToFitContent!==!1){const r=this.node&&this.node.width?this.node.width:0,i=this.node&&this.node.height?this.node.height:0;this._ensureViewboxFits(r,i)}else this._syncViewboxToContainer();return this.options.debugExtents?this._drawDebugOverlays():this._clearDebugOverlays(),typeof window<"u"&&!window.refreshDisplayAndFilters&&(window.refreshDisplayAndFilters=()=>{try{const r=this.getCurrentNode(),i=r!=null&&r.getSequence?r.getSequence():null;i&&(typeof i.simplifyAll=="function"&&i.simplifyAll(),typeof i.updateStepsVisibility=="function"&&i.updateStepsVisibility(s=>(s.stepMark??0)===0),typeof r.updateLayout=="function"&&r.updateLayout()),this.options.centerContent&&this.centerNode()}catch{}}),this.node}addChild(e){if(this._contentGroup&&e&&e.svgObject)try{this._contentGroup.appendChild(e.svgObject)}catch{this.svg.addChild(e)}else this.svg.addChild(e);return this.options.centerContent&&this.centerNode(),e}removeChild(e){if(this.svg){try{e&&e.svgObject?this._contentGroup&&this._contentGroup.contains(e.svgObject)?this._contentGroup.removeChild(e.svgObject):this.svg.svgObject&&this.svg.svgObject.contains(e.svgObject)?this.svg.svgObject.removeChild(e.svgObject):typeof this.svg.removeChild=="function"&&this.svg.removeChild(e):typeof this.svg.removeChild=="function"&&this.svg.removeChild(e)}catch{}this.node===e&&(this.node=null)}}update(e){if(this.node&&(this._contentGroup&&this.node&&this.node.svgObject&&this._contentGroup.contains(this.node.svgObject)?this._contentGroup.removeChild(this.node.svgObject):typeof this.svg.removeChild=="function"&&this.svg.removeChild(this.node)),this.node=e,this.node.setFontSize(this.options.fontSize),this.node.initialize(),this._contentGroup&&this.node&&this.node.svgObject)try{this._contentGroup.appendChild(this.node.svgObject)}catch{this.svg.addChild(this.node)}else this.svg.addChild(this.node);this.options.centerContent&&this.centerNode(),this._repositionOverlayToolbar()}setFontSize(e){this.options.fontSize=e,this.node&&(this.node.getSequence&&typeof this.node.getSequence=="function"?this.node.getSequence().setFontSize(e):this.node.setFontSize&&typeof this.node.setFontSize=="function"&&this.node.setFontSize(e),this.node.initialize(),this.options.centerContent&&this.centerNode())}setFont(e,t="400"){var r;if((r=this.svg)!=null&&r.svgObject){const i=s=>{s.style&&(s.style.fontFamily=e,s.style.fontWeight=t),Array.from(s.children||[]).forEach(i)};i(this.svg.svgObject),this.options.fontFamily=e,this.options.fontWeight=t}}clear(){this.node&&(this.removeChild(this.node),this.node=null)}destroy(){this.clear(),this.resizeObserver&&this.resizeObserver.disconnect(),this.container.contains(this.svg.svgObject)&&this.container.removeChild(this.svg.svgObject)}_repositionOverlayToolbar(){const e=this.container.offsetWidth||0,t=this.container.offsetHeight||0,r=this.node;if(!r)return;if(typeof r.isToolbarOverlay=="function"&&typeof r.positionToolbarOverlay=="function"&&r.isToolbarOverlay()){const s=typeof r.getOverlayPadding=="function"?r.getOverlayPadding():16;r.positionToolbarOverlay(e,t,s)}}getCurrentNode(){return this.node}getSVG(){return this.svg.svgObject}}class Wq{constructor(e,t,r={}){this.targetNode=e,this.parentElement=t,this.options={editable:!0,animationDuration:200,...r},this.popup=null,this.popupBackground=null,this.popupTextInput=null,this.penCanvas=null,this.penCanvasCleanup=null,this.currentMode="text",this.popupAnimationId=null,this.penButton=null,this.textButton=null,this.clearButton=null,this.submitButton=null,this.onValidateCallback=null,this.onClearCallback=null,this.popupWidth=400,this.buttonSize=18,this.margin=10,this.buttonSpacing=4,this.canvasMinWidth=100,this.canvasMinHeight=60,this.popupHeightMultiplier=2,this.targetNodeDefaultHeight=40,this.canvasTopOffset=this.margin,this.canvasLeftOffset=this.margin}show(e,t){return this.popup?this.hide().then(()=>this.show(e,t)):(this._createPopup(),this._positionPopup(e,t),this.parentElement.addChild(this.popup),this.popup.setOpacity(0),this._animateOpacity(0,1,this.options.animationDuration))}hide(){var a,o;if(!this.popup)return Promise.resolve();const e=this.popup.opacity,t=((o=(a=this.popupTextInput)==null?void 0:a.div)==null?void 0:o.style.opacity)||"1";this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.display="block"),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.opacity=t);const r=this.options.animationDuration||300,i=performance.now(),s=l=>{const u=l-i,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e*(1-h);this.popup&&this.popup.setOpacity(f),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.opacity=f),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.opacity=f),c<1?this.popupAnimationId=requestAnimationFrame(s):(this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.display="none",this.penCanvas.container.style.opacity="1"),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="none"),this._cleanup())};return this.popupAnimationId=requestAnimationFrame(s),new Promise(l=>{setTimeout(l,r)})}toggle(e,t){return this.popup&&this.popup.visible?this.hide():this.show(e,t)}setValidationCallback(e){this.onValidateCallback=e}setClearCallback(e){this.onClearCallback=e}getValue(){if(this.transcribedText){const e=this.transcribedText;return this.transcribedText=null,e}return this.currentMode==="text"&&this.popupTextInput?this.popupTextInput.getText():""}setValue(e){this.currentMode==="text"&&this.popupTextInput&&this.popupTextInput.setText(e)}switchToMode(e){this.currentMode===e||!this.popup||(this.currentMode=e,e==="pen"?this._showPenMode():this._showTextMode(),this._updateButtonStates())}_createPopup(){var t;const e=(((t=this.targetNode)==null?void 0:t.height)||this.targetNodeDefaultHeight)*this.popupHeightMultiplier;this.popup=new qr,this.popupBackground=new yt,this.popupBackground.setWidthAndHeight(this.popupWidth,e),this.popupBackground.setFillColor("white"),this.popupBackground.setStrokeColor("black"),this.popupBackground.setStrokeWidth(2),this.popupBackground.setCornerRadius(8),this.popup.addChild(this.popupBackground),this._createButtons(this.popupWidth,e,this.buttonSize,this.margin,this.buttonSpacing),this._createTextInput(this.popupWidth,e,this.margin),this.currentMode="text",this._updateButtonStates()}_createButtons(e,t,r,i,s){const a=e-r-i,o=t-r*2-i-s;this.clearButton=new Xn,this.clearButton.setText("C"),this.clearButton.setWidthAndHeight(r,r),this.clearButton.setFillColor("#E65423"),this.clearButton.setFontColor("white"),this.clearButton.buttonText.setFontWeight("bold"),this.clearButton.setPosition(a,o),this.clearButton.setClickCallback(()=>{this.currentMode==="pen"&&this.penCanvas?this.penCanvas.clear():this.currentMode==="text"&&this.popupTextInput&&this.popupTextInput.setText(""),this.onClearCallback&&this.onClearCallback()}),this.popup.addChild(this.clearButton);const l=t-r-i;this.submitButton=new Xn,this.submitButton.setText("✓"),this.submitButton.setWidthAndHeight(r,r),this.submitButton.setFillColor("#2ECC71"),this.submitButton.setFontColor("white"),this.submitButton.buttonText.setFontWeight("bold"),this.submitButton.setPosition(a,l),this.submitButton.setClickCallback(()=>{this.currentMode==="pen"&&this.penCanvas?(this._setSubmitButtonLoading(!0),this._downloadCanvasAsBitmap()):this.onValidateCallback&&this.onValidateCallback()}),this.popup.addChild(this.submitButton);const u=i;this.textButton=new Xn,this.textButton.setText("T"),this.textButton.setWidthAndHeight(r,r),this.textButton.setFillColor("#28a745"),this.textButton.setFontColor("white"),this.textButton.buttonText.setFontWeight("bold"),this.textButton.setPosition(u,o),this.textButton.setClickCallback(()=>{this.switchToMode("text")}),this.popup.addChild(this.textButton),this.penButton=new Xn,this.penButton.setText(""),this.penButton.setWidthAndHeight(r,r),this.penButton.setFillColor("#007bff"),this.penButton.setPosition(u,l),this.penButton.setClickCallback(()=>this.switchToMode("pen"));const h="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(`<svg width="12" height="12" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
90
+ `,e.div.querySelectorAll(".step-content, .step-text").forEach(d=>{d.style.lineHeight="1.3 !important",d.style.margin="0 !important",d.style.fontFamily="Albert Sans, Arial, sans-serif !important",d.style.position="static !important"}),e.div.querySelectorAll("span").forEach(d=>{d.style.position="static !important"})),e.div.offsetHeight}setupStepInteractions(e){const t=e.div.style.backgroundColor||"";e.div.addEventListener("mouseenter",()=>{var r;e.div.style.backgroundColor=Fe.mediumGray,(r=this.onStepHover)==null||r.call(this,e.stepIndex,e.stepMessage,!0)}),e.div.addEventListener("mouseleave",()=>{var r;e.div.style.backgroundColor=t,(r=this.onStepHover)==null||r.call(this,e.stepIndex,e.stepMessage,!1)}),e.div.addEventListener("click",()=>{var r;(r=this.onStepClick)==null||r.call(this,e.stepIndex,e.stepMessage)})}calculateContentHeight(e,t,r){const i=document.createElement("div");i.style.position="absolute",i.style.visibility="hidden",i.style.width=`${this.stepWidth-16}px`,i.style.fontSize=`${this.fontSize}px`,i.style.lineHeight="1.3",i.style.fontFamily="Albert Sans, Arial, sans-serif",i.style.whiteSpace="normal",i.style.wordWrap="break-word",i.style.overflowWrap="break-word",i.style.padding="6px 8px",i.style.boxSizing="border-box",i.style.display="flex",i.style.flexDirection="column",i.style.justifyContent="center";const s=this.formatStepContent(e,t,r);i.innerHTML=s,document.body.appendChild(i);const a=i.offsetHeight;return document.body.removeChild(i),Math.max(this.baseStepHeight,a+2)}calculateStepHeight(e){return this.calculateContentHeight(e,0,!1)}updateBackgroundSize(){if(this.backgroundRect&&this.contentGroup){const e=this.contentGroup.height+16,t=this.stepWidth+16;this.backgroundRect.setWidthAndHeight(t,e)}}applyDropShadowIfNeeded(){this.stylingOptions.dropShadow&&this.backgroundRect&&this.backgroundRect.svgObject&&(this.backgroundRect.svgObject.style.filter="drop-shadow(0 2px 8px rgba(0,0,0,0.15))")}setOnStepHover(e){this.onStepHover=e}setOnStepClick(e){this.onStepClick=e}getLayoutGroup(){return this.layoutGroup}setPosition(e,t){this.layoutGroup.setPosition(e,t)}getDimensions(){return{width:this.backgroundRect?this.backgroundRect.width:this.stepWidth+16,height:this.backgroundRect?this.backgroundRect.height:100}}updateStyling(e={}){if(this.stylingOptions={...this.stylingOptions,...e},e.maxWidth&&(this.stepWidth=e.maxWidth),e.fontSize&&(this.fontSize=e.fontSize),this.backgroundRect){const t=this.stylingOptions.backgroundColor||Fe.lightGray,r=this.stylingOptions.borderColor||"#e0e0e0",i=this.stylingOptions.borderWidth||1,s=this.stylingOptions.borderRadius||6;this.backgroundRect.setFillColor(t),this.backgroundRect.setStrokeColor(r),this.backgroundRect.setStrokeWidth(i),this.backgroundRect.setCornerRadius(s),this.backgroundRect.svgObject&&(this.stylingOptions.dropShadow?this.backgroundRect.svgObject.style.filter="drop-shadow(0 2px 8px rgba(0,0,0,0.15))":this.backgroundRect.svgObject.style.filter="")}this.stepElements.forEach((t,r)=>{if(t.div){const i=t.div.innerHTML,s=this.calculateContentHeight(t.stepMessage,r,t.isMultiple);this.applyStepStyling(t,i,t.isMultiple,s),t.setFontSize(this.fontSize),t.setWidthAndHeight(this.stepWidth,s)}}),this.updateBackgroundSize()}getStyling(){return{...this.stylingOptions}}isOperationMessage(e){return["Applied","added","subtracted","multiplied","divided","both sides"].some(r=>e.toLowerCase().includes(r.toLowerCase()))}extractOperationAction(e){const t=e.match(/^(Added|Subtracted|Multiplied|Divided)/i);return t?t[0]:null}extractOperationValue(e){const t=e.match(/(?:Added|Subtracted|Multiplied|Divided)\s(.*?)\s(?:to|by)/i);return t&&t[1]?t[1].includes("[object Object]")?null:t[1]:null}extractOperationValueNode(e){return this.simplificationData&&this.simplificationData.operationValueNode?this.simplificationData.operationValueNode:null}destroy(){this.stepElements=[],this.contentGroup&&this.contentGroup.removeAllChildren(),this.layoutGroup.removeAllChildren(),this.onStepHover=null,this.onStepClick=null}}class Hq{constructor(e,t,r={}){this.stepVisualizer=e,this.highlighting=t,this.stepTextBoxes=[],this.options=r}createTextBoxForDot(e){try{this.removeTextBoxForDot(e);const t=this._findDotAboveForPositioning(e);if(!t){console.error("Target dot not found for positioning text box for dot index:",e);return}const r=this._getSimplificationDataForDot(e);this._createInteractiveStepsForDot(e,t,r)}catch(t){console.error("Error creating text box for dot",e,":",t)}}_createInteractiveStepsForDot(e,t,r){const i=new qq(this.stepVisualizer,r,this.options),s=t.xpos+this.stepVisualizer.dotRadius*2+10,a=t.ypos-this.stepVisualizer.dotRadius;i.setPosition(s,a),i.setOnStepHover((l,u,c)=>{}),i.setOnStepClick((l,u)=>{});const o=i.getLayoutGroup();o.dotIndex=e,this.stepVisualizer.visualContainer.addChild(o),o.svgObject&&(this.options.zIndex||this.options.position)&&(this.options.position&&(o.svgObject.style.position=this.options.position),this.options.zIndex&&(o.svgObject.style.zIndex=String(this.options.zIndex))),this.stepTextBoxes.push({dotIndex:e,interactiveSteps:i,layoutGroup:o})}removeTextBoxForDot(e){const t=this.stepTextBoxes.findIndex(r=>r.dotIndex===e);if(t>=0){const r=this.stepTextBoxes[t];this.stepVisualizer.visualContainer.removeChild(r.layoutGroup),r.interactiveSteps.destroy(),this.stepTextBoxes.splice(t,1)}}clearAllTextBoxes(){this.stepTextBoxes.forEach(e=>{this.stepVisualizer.visualContainer.removeChild(e.layoutGroup),e.interactiveSteps.destroy()}),this.stepTextBoxes=[]}_findDotAboveForPositioning(e){const t=this.stepVisualizer.stepDots[e];if(!t||!t.equationRef)return null;const r=t.equationRef,i=this.stepVisualizer.steps.indexOf(r);for(let s=i-1;s>=0;s--){const a=this.stepVisualizer.steps[s];if(a instanceof ut&&a.visible!==!1){for(let o=e-1;o>=0;o--){const l=this.stepVisualizer.stepDots[o];if(l&&l.equationRef===a)return l}break}}return t}_getSimplificationDataForDot(e){return this.stepVisualizer._getSimplificationDataForDot(e)}getStepTextBoxes(){return this.stepTextBoxes}updateStyling(e={}){this.options={...this.options,...e},this.stepTextBoxes.forEach(t=>{t.interactiveSteps&&typeof t.interactiveSteps.updateStyling=="function"&&t.interactiveSteps.updateStyling(this.options)})}getStyling(){return{...this.options}}}class Uq{constructor(e){this.stepVisualizer=e,this.expansionDots=[],this.fixedVisualizerPosition=250,this.allowEquationRepositioning=!0}setFixedVisualizerPosition(e){this.fixedVisualizerPosition!==e&&(this.fixedVisualizerPosition=e,this.stepVisualizer&&this.stepVisualizer.stepDots.length>0&&this.updateVisualLayout(!0))}updateVisualLayout(e=!1){if(this.stepVisualizer.stepDots.length===0)return;const t=this.stepVisualizer.sequenceWidth||this.stepVisualizer.width,r=this._getMaxEquationEffectivePaddingX(),i=t+r,s=this.fixedVisualizerPosition;if(this.stepVisualizer.visualContainer.setPosition(s,0),this.allowEquationRepositioning&&e){const f=this.fixedVisualizerPosition-this.stepVisualizer.visualSpacing;let d=0;i>f&&(d=f-i),this._adjustEquationPositions(d)}const a=this.stepVisualizer.steps.filter(f=>f.visible!==!1);let o=0;const l=15*this.stepVisualizer.getFontSize()/this.stepVisualizer.getRootFontSize();a.forEach((f,d)=>{if(f instanceof ut){const p=this.findDotIndexForEquation(f);if(p>=0&&p<this.stepVisualizer.stepDots.length){const m=this.stepVisualizer.stepDots[p];let y;f.equalsSign&&f.equalsSign.ypos!==void 0?y=f.equalsSign.ypos+f.equalsSign.height/2:y=f.getAlignmentBaseline?f.getAlignmentBaseline():f.height/2;const v=o+y,S=this.stepVisualizer.dotRadius*3/2;m.setPosition(S,v)}}o+=f.height,d<a.length-1&&(o+=l)}),this.updateAllLinePositions();let u=this.stepVisualizer.dotRadius*3,c=this.stepVisualizer.height;this.stepVisualizer.sequenceHeight||(this.stepVisualizer.sequenceHeight=c);const h=this.stepVisualizer.textBoxManager.getStepTextBoxes();if(h.length>0&&(u=Math.max(u,280+this.stepVisualizer.dotRadius*2+10+20),h.forEach(d=>{if(d.interactiveSteps){const p=d.interactiveSteps.getDimensions(),y=d.interactiveSteps.getLayoutGroup().ypos+p.height;c=Math.max(c,y+20)}})),this.stepVisualizer.stepDots.length>0){Math.max(...this.stepVisualizer.stepDots.map(d=>d.radius||this.stepVisualizer.dotRadius));const f=Math.max(...this.stepVisualizer.stepDots.map(d=>d.ypos+this.stepVisualizer.dotRadius));c=Math.max(c,f)}this.stepVisualizer.visualContainer.setWidthAndHeight(u,c),this.updateVisualZOrder(),this._positionExpansionDots()}_adjustEquationPositions(e){if(e===0)return;this.stepVisualizer.steps.forEach(r=>{if(r&&r.setPosition){const i=r.xpos||0,s=r.ypos||0;if(r.setPosition(i+e,s),r.operationDisplayNode&&r.operationDisplayNode.setPosition){const a=r.operationDisplayNode.xpos||0,o=r.operationDisplayNode.ypos||0;r.operationDisplayNode.setPosition(a+e,o)}}})}_getMaxEquationEffectivePaddingX(){try{const e=this.stepVisualizer.steps||[];let t=0;return e.forEach(r=>{if(r instanceof ut&&r.visible!==!1&&typeof r.getEffectiveBackgroundPaddingX=="function"){const i=Number(r.getEffectiveBackgroundPaddingX());t=Math.max(t,isNaN(i)?0:i)}}),t}catch{return 0}}findDotIndexForEquation(e){return this.stepVisualizer.stepDots.findIndex(t=>t.equationRef===e)}updateVisualZOrder(){if(!this.stepVisualizer.visualContainer)return;this.stepVisualizer.stepLines.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="1",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.stepVisualizer.stepDots.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="2",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.stepVisualizer.textBoxManager.getStepTextBoxes().forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="3",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))}),this.expansionDots.forEach(t=>{t&&t.svgObject&&(t.svgObject.style.zIndex="4",t.parentNode!==this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.addChild(t))})}updateAllLinePositions(){this.stepVisualizer.stepLines.forEach(e=>{const t=this.stepVisualizer.stepDots[e.fromDotIndex],r=this.stepVisualizer.stepDots[e.toDotIndex];t&&r&&e.setEndpoints(t.xpos,t.ypos,r.xpos,r.ypos)})}updateVisualVisibility(){var i,s,a;const e=this.stepVisualizer,t=((i=e.styling)==null?void 0:i.dotColor)||Fe.stepColor;e.stepDots.forEach((o,l)=>{o.equationRef&&o.equationRef.visible!==!1?(o.setFillColor(t),o.setStrokeColor(t),o.show(),o.visible=!0):(o.hide(),o.visible=!1)}),this._clearExpansionDots(),e.stepLines.forEach(o=>{o.parent===e.visualContainer&&e.visualContainer.removeChild(o)}),e.stepLines=[];const r=e.stepDots.filter(o=>o.visible);for(let o=0;o<r.length-1;o++){const l=r[o],u=r[o+1],c=new Ut,h=((s=e.styling)==null?void 0:s.lineColor)||Fe.stepColor;c.setStrokeColor(h),c.setStrokeWidth(((a=e.styling)==null?void 0:a.lineWidth)||e.lineWidth),c.fromDotIndex=e.stepDots.indexOf(l),c.toDotIndex=e.stepDots.indexOf(u),e.visualContainer.addChild(c),e.stepLines.push(c)}this.updateAllLinePositions(),this._createExpansionDots(),this._positionExpansionDots()}updateDotClickability(e){this.stepVisualizer.dotsClickable?(e.svgObject.style.cursor="pointer",e.svgObject.onclick=t=>{try{const r=this.stepVisualizer.stepDots.indexOf(e);if(r<0)return;this.stepVisualizer._handleDotClick(e,r),t.stopPropagation()}catch(r){console.error("Error in dot click handler:",r)}}):(e.svgObject.style.cursor="default",e.svgObject.onclick=null)}_clearExpansionDots(){this.expansionDots.forEach(e=>{e.parentNode===this.stepVisualizer.visualContainer&&this.stepVisualizer.visualContainer.removeChild(e)}),this.expansionDots=[]}_createExpansionDots(){const e=this.stepVisualizer,t=e.stepDots;e.stepDots.filter(i=>i.visible),e.steps.forEach((i,s)=>{i&&(i instanceof ut||i.type)}),t.forEach((i,s)=>{i&&i.equationRef});const r=[];e.steps.forEach((i,s)=>{i&&(i instanceof ut||i.type==="omdEquationNode")&&i.stepMark===0&&i.visible===!0&&r.push(s)});for(let i=1;i<r.length;i++){const s=r[i-1],a=r[i];let o=0;for(let l=s+1;l<a;l++){const u=e.steps[l];u&&(u instanceof ut||u.type==="omdEquationNode")&&u.stepMark>0&&u.visible===!1&&o++}if(o>0){const l=e.steps[a];if(e.stepDots.findIndex(c=>c.equationRef===l)>=0){const c=i,h=this._createSingleExpansionDot(c,s,o);h.majorStepIndex=a,this.expansionDots.push(h),e.visualContainer.addChild(h)}}}this._createCollapseDots()}_countIntermediateStepsBetween(e,t){var u,c;const r=this.stepVisualizer;let i=0;const s=(u=r.stepDots[e])==null?void 0:u.equationRef,a=(c=r.stepDots[t])==null?void 0:c.equationRef;if(!s||!a)return 0;const o=r.steps.indexOf(s),l=r.steps.indexOf(a);for(let h=o+1;h<l;h++){const f=r.steps[h];f&&(f instanceof ut||f.type==="omdEquationNode")&&f.stepMark!==void 0&&f.stepMark>0&&f.visible===!1&&i++}return i}_countHiddenStepsBetween(e,t){return this._countIntermediateStepsBetween(e,t)}_createSingleExpansionDot(e,t,r){var u,c,h,f;const i=this.stepVisualizer,s=((u=i.styling)==null?void 0:u.dotRadius)||Ta(0),a=Math.max(3,s*(((c=i.styling)==null?void 0:c.expansionDotScale)||.4)),o=new Tr;o.setWidthAndHeight(a*2,a*2);const l=((h=i.styling)==null?void 0:h.dotColor)||Fe.stepColor;return o.setFillColor(l),o.setStrokeColor(l),o.setStrokeWidth(((f=i.styling)==null?void 0:f.dotStrokeWidth)||1),o.isExpansionDot=!0,o.currentStepIndex=e,o.previousStepIndex=t,o.hiddenCount=r,o.radius=a,o.svgObject.style.cursor="pointer",o.svgObject.onclick=d=>{try{this._handleExpansionDotClick(o),d.stopPropagation()}catch(p){console.error("Error in expansion dot click handler:",p)}},o}_positionExpansionDots(){const e=this.stepVisualizer;this.expansionDots.forEach((t,r)=>{let i;if(t.isCollapseDot){const s=t.currentStepIndex;i=e.stepDots[s]}else{const s=t.majorStepIndex,a=e.steps[s];if(a){const o=e.stepDots.findIndex(l=>l.equationRef===a);i=e.stepDots[o]}}if(i&&i.visible){const s=-(t.radius*2+8),a=i.xpos,o=i.ypos+s;t.setPosition(a,o)}})}_createCollapseDots(){const e=this.stepVisualizer,t=e.stepDots,r=[];let i=[];t.forEach((s,a)=>{if(s&&s.visible&&s.equationRef){const o=s.equationRef.stepMark;o!==void 0&&o>0?i.push(a):i.length>0&&(r.push([...i]),i=[])}else i.length>0&&(r.push([...i]),i=[])}),i.length>0&&r.push([...i]),r.forEach((s,a)=>{if(s.length>0){const o=s[s.length-1],u=e.stepDots[o].equationRef,c=e.steps.indexOf(u);let h=-1;for(let f=c+1;f<e.steps.length;f++){const d=e.steps[f];if(d&&(d instanceof ut||d.type==="omdEquationNode")&&d.stepMark===0&&d.visible===!0){h=f;break}}if(h>=0){const f=e.steps[h],d=e.stepDots.findIndex(p=>p.equationRef===f);if(d>=0){const p=this._createSingleExpansionDot(d,-1,s.length);p.isCollapseDot=!0,p.intermediateSteps=s,p.groupIndex=a,this.expansionDots.push(p),e.visualContainer.addChild(p)}}}})}_handleExpansionDotClick(e){const t=this.stepVisualizer;if(t.highlighting&&typeof t.highlighting.clearAllExplainHighlights=="function"&&t.highlighting.clearAllExplainHighlights(),e.isCollapseDot)(e.intermediateSteps||[]).forEach(i=>{const s=t.stepDots[i];s&&s.equationRef&&(this._hideStep(s.equationRef),s.hide(),s.visible=!1)}),this._removeLinesToHiddenDots();else{const{majorStepIndex:r,previousStepIndex:i}=e;e.parentNode===t.visualContainer&&t.visualContainer.removeChild(e);const s=this.expansionDots.indexOf(e);s>=0&&this.expansionDots.splice(s,1);for(let a=i+1;a<r;a++){const o=t.steps[a];if(o&&(o instanceof ut||o.type==="omdEquationNode")&&o.stepMark>0){this._showStep(o);const l=t.stepDots.findIndex(u=>u.equationRef===o);if(l>=0){const u=t.stepDots[l];u.show(),u.visible=!0}}}}t.rebuildVisualizer()}_hideStep(e){e.visible=!1,e.svgObject&&(e.svgObject.style.display="none"),e.operationDisplayNode&&(e.operationDisplayNode.visible=!1,e.operationDisplayNode.svgObject&&(e.operationDisplayNode.svgObject.style.display="none")),e.children&&Array.isArray(e.children)&&e.children.forEach(t=>{t&&this._hideStep(t)})}_showStep(e){e.visible=!0,e.svgObject&&(e.svgObject.style.display=""),e.operationDisplayNode&&(e.operationDisplayNode.visible=!0,e.operationDisplayNode.svgObject&&(e.operationDisplayNode.svgObject.style.display="")),e.children&&Array.isArray(e.children)&&e.children.forEach(t=>{t&&this._showStep(t)})}_removeLinesToHiddenDots(){const e=this.stepVisualizer,t=[];e.stepLines.forEach((r,i)=>{const s=e.stepDots[r.fromDotIndex],a=e.stepDots[r.toDotIndex];(s&&!s.visible||a&&!a.visible)&&t.push(r)}),t.forEach(r=>{r.parent===e.visualContainer&&e.visualContainer.removeChild(r);const i=e.stepLines.indexOf(r);i>=0&&e.stepLines.splice(i,1)})}}class Go extends jo{constructor(e,t={}){super(e),this.styling=this._mergeWithDefaults(t||{}),this.stepDots=[],this.stepLines=[],this.visualContainer=new qr,this.dotRadius=this.styling.dotRadius,this.lineWidth=this.styling.lineWidth,this.visualSpacing=this.styling.visualSpacing,this.activeDotIndex=-1,this.dotsClickable=!0,this.nodeToStepMap=new Map,this.stepVisualizerHighlights=new Set,this.highlighting=new $q(this);const r=this.styling.textBoxOptions||{};this.textBoxManager=new Hq(this,this.highlighting,r),this.layoutManager=new Uq(this),this.addChild(this.visualContainer),this._initializeVisualElements(),this.setFilterLevel&&typeof this.setFilterLevel=="function"&&this.setFilterLevel(0),this.computeDimensions(),this.updateLayout()}toggleDot(e){if(typeof e!="number"||e<0||e>=this.stepDots.length)return;const t=this.stepDots[e];this._handleDotClick(t,e)}closeActiveDot(){var e,t,r,i;try{const s=((t=(e=this.textBoxManager)==null?void 0:e.stepTextBoxes)==null?void 0:t.length)||0;this._clearActiveDot(),this.textBoxManager&&typeof this.textBoxManager.clearAllTextBoxes=="function"&&this.textBoxManager.clearAllTextBoxes();const a=((i=(r=this.textBoxManager)==null?void 0:r.stepTextBoxes)==null?void 0:i.length)||0}catch{}}closeAllTextBoxes(){this.closeActiveDot()}forceCloseAll(){this.closeActiveDot()}_mergeWithDefaults(e){const t={dotColor:Fe.stepColor,dotRadius:Ta(0),dotStrokeWidth:2,activeDotColor:Fe.explainColor,expansionDotScale:.4,lineColor:Fe.stepColor,lineWidth:2,activeLineColor:Fe.explainColor,explainColor:Fe.explainColor,highlightColor:Fe.hiliteColor,visualSpacing:30,fixedVisualizerPosition:250,dotVerticalOffset:15,textBoxOptions:{backgroundColor:Fe.white,borderColor:"none",borderWidth:1,borderRadius:5,padding:8,fontSize:14,fontFamily:"Albert Sans, Arial, sans-serif",maxWidth:300,dropShadow:!0},enableAnimations:!0,hoverEffects:!0,backgroundColor:null,cornerRadius:null,pill:null};return this._deepMerge(t,e)}_deepMerge(e,t){const r={...e};for(const i in t)t.hasOwnProperty(i)&&(typeof t[i]=="object"&&t[i]!==null&&!Array.isArray(t[i])?r[i]=this._deepMerge(r[i]||{},t[i]):r[i]=t[i]);return r}setStyling(e){this.styling=this._mergeWithDefaults({...this.styling,...e}),this.dotRadius=this.styling.dotRadius,this.lineWidth=this.styling.lineWidth,this.visualSpacing=this.styling.visualSpacing,this._applyStylingToExistingElements(),e.visualSpacing!==void 0&&(this.visualSpacing=this.styling.visualSpacing),e.fixedVisualizerPosition!==void 0&&this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(this.styling.fixedVisualizerPosition),this.updateLayout()}getStyling(){return{...this.styling}}setStyleProperty(e,t){const r=e.split("."),i=r.pop(),s=r.reduce((a,o)=>(a[o]||(a[o]={}),a[o]),this.styling);s[i]=t,e==="dotRadius"&&(this.dotRadius=t),e==="lineWidth"&&(this.lineWidth=t),e==="visualSpacing"&&(this.visualSpacing=t),e==="fixedVisualizerPosition"&&this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(t),this._applyStylingToExistingElements(),this.updateLayout()}getStyleProperty(e){return e.split(".").reduce((t,r)=>t==null?void 0:t[r],this.styling)}_applyStylingToExistingElements(){this.stepDots.forEach((e,t)=>{if(e&&e.equationRef){const i=this.activeDotIndex===t?this.styling.activeDotColor:this.styling.dotColor;e.setFillColor(i),e.setStrokeColor(i),e.setStrokeWidth(this.styling.dotStrokeWidth);const s=e.equationRef.stepMark??0,a=this.styling.dotRadius||Ta(s);e.setWidthAndHeight(a*2,a*2),e.radius=a}}),this.stepLines.forEach((e,t)=>{if(e){const i=this.activeDotIndex>=0&&(e.toDotIndex===this.activeDotIndex||e.fromDotIndex===this.activeDotIndex)?this.styling.activeLineColor:this.styling.lineColor;e.setStrokeColor(i),e.setStrokeWidth(this.styling.lineWidth)}}),this.layoutManager&&this.layoutManager.expansionDots&&this.layoutManager.expansionDots.forEach(e=>{if(e){const t=this.styling.dotRadius||Ta(0),r=Math.max(3,t*this.styling.expansionDotScale);e.setWidthAndHeight(r*2,r*2),e.radius=r,e.setFillColor(this.styling.dotColor),e.setStrokeColor(this.styling.dotColor)}}),this.textBoxManager&&typeof this.textBoxManager.updateStyling=="function"&&this.textBoxManager.updateStyling(this.styling.textBoxOptions)}setBackgroundStyle(e={}){this.styling.backgroundColor=e.backgroundColor||this.styling.backgroundColor,this.styling.cornerRadius=e.cornerRadius||this.styling.cornerRadius,this.styling.pill=e.pill!==void 0?e.pill:this.styling.pill,typeof this.setDefaultEquationBackground=="function"&&this.setDefaultEquationBackground(e)}getBackgroundStyle(){return{backgroundColor:this.styling.backgroundColor,cornerRadius:this.styling.cornerRadius,pill:this.styling.pill}}setFixedVisualizerPosition(e){this.layoutManager&&this.layoutManager.setFixedVisualizerPosition(e)}rebuildVisualizer(){this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights(),this.visualContainer&&this.removeChild(this.visualContainer),this.visualContainer=new qr,this.addChild(this.visualContainer),this._initializeVisualElements(),this.computeDimensions(),this.updateLayout()}_initializeVisualElements(){this._clearVisualElements(),this.nodeToStepMap.clear(),this.steps.filter(t=>t instanceof ut).forEach((t,r)=>{this._createStepDot(t,r),t.findAllNodes().forEach(i=>{this.nodeToStepMap.set(i.id,r)}),r>0&&this._createStepLine(r-1,r)}),this.layoutManager.updateVisualZOrder(),this.layoutManager.updateVisualLayout(!0)}_createStepDot(e,t){const r=e.stepMark??0,i=this.styling.dotRadius||Ta(r),s=new Tr;s.setWidthAndHeight(i*2,i*2);const a=this.styling.dotColor;return s.setFillColor(a),s.setStrokeColor(a),s.setStrokeWidth(this.styling.dotStrokeWidth),s.radius=i,s.equationRef=e,s.stepIndex=t,e.visible===!1&&s.hide(),this.layoutManager.updateDotClickability(s),this.stepDots.push(s),this.visualContainer.addChild(s),s}_createStepLine(e,t){var o,l;const r=new Ut,i=this.styling.lineColor;r.setStrokeColor(i),r.setStrokeWidth(this.styling.lineWidth),r.fromDotIndex=e,r.toDotIndex=t;const s=(o=this.stepDots[e])==null?void 0:o.equationRef,a=(l=this.stepDots[t])==null?void 0:l.equationRef;return((s==null?void 0:s.visible)===!1||(a==null?void 0:a.visible)===!1)&&r.hide(),this.stepLines.push(r),this.visualContainer.addChild(r),r}_clearVisualElements(){this.stepDots.forEach(e=>this.visualContainer.removeChild(e)),this.stepLines.forEach(e=>this.visualContainer.removeChild(e)),this.textBoxManager.clearAllTextBoxes(),this.stepDots=[],this.stepLines=[],this.activeDotIndex=-1}addStep(e,t={}){if(this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights(),super.addStep(e,t),e instanceof ut){const r=this.steps.filter(i=>i instanceof ut).indexOf(e);if(r>=0){const i=this._createStepDot(e,r);if(e.findAllNodes().forEach(s=>{this.nodeToStepMap.set(s.id,r)}),r>0&&this._createStepLine(r-1,r),i){const s=Ta(e.stepMark??0);i.setWidthAndHeight(s*2,s*2),i.radius=s}}}this.computeDimensions(),this.updateLayout()}getNodeStepNumber(e){return this.nodeToStepMap.get(e)}computeDimensions(){if(super.computeDimensions(),this.sequenceWidth=this.width,this.sequenceHeight=this.height,this.stepDots&&this.stepDots.length>0&&this.layoutManager){const e=this.dotRadius*3,r=(this.layoutManager.fixedVisualizerPosition||250)+this.visualSpacing+e;this.setWidthAndHeight(r,this.height)}}updateLayout(){super.updateLayout(),this.layoutManager&&(this.layoutManager.updateVisualLayout(!0),this.layoutManager.updateVisualVisibility(),this.layoutManager.updateAllLinePositions())}undoLastOperation(){this.highlighting&&typeof this.highlighting.clearAllExplainHighlights=="function"&&this.highlighting.clearAllExplainHighlights();const e=this.steps.length;return(super.undoLastOperation?super.undoLastOperation():!1)||this.steps.length<e?(this.rebuildVisualizer(),!0):!1}setDotColor(e,t){if(this.stepDots&&e>=0&&e<this.stepDots.length){const r=this.stepDots[e];r.setFillColor(t),r.setStrokeColor(t)}}setLineAboveColor(e,t){let r=this.stepLines.find(i=>i.toDotIndex===e&&i.isTemporary&&i.svgObject&&i.svgObject.style.display!=="none");r||(r=this.stepLines.find(i=>i.toDotIndex===e&&!i.isTemporary&&i.svgObject&&i.svgObject.style.display!=="none")),r&&r.setStrokeColor(t)}setDotsClickable(e){this.dotsClickable=e,e||(this._clearActiveDot(),this.highlighting.clearAllExplainHighlights()),this.stepDots.forEach(t=>{this.layoutManager.updateDotClickability(t)})}_handleDotClick(e,t){if(this.dotsClickable&&!(t<0||t>=this.stepDots.length)){if(this.stepDots[t]!==e){const r=this.stepDots.indexOf(e);if(r===-1)return;t=r}try{if(this.activeDotIndex===t)this._clearActiveDot();else{this.activeDotIndex!==-1&&this._clearActiveDot(),this.setActiveDot(t);const r=this.stepDots[t].equationRef,i=this.steps.indexOf(r),s=this._checkForOperationStep(i);this.highlighting.highlightAffectedNodes(t,s)}}catch(r){console.error("Error handling dot click:",r)}}}setActiveDot(e){if(!this.stepDots||e<0||e>=this.stepDots.length)return;this.activeDotIndex=e,this.activeDot=this.stepDots[e];const t=this.stepDots[e],r=this.styling.activeDotColor;t.setFillColor(r),t.setStrokeColor(r),this.setLineAboveColor(e,this.styling.activeLineColor),this.textBoxManager.createTextBoxForDot(e);const i=this.layoutManager.allowEquationRepositioning;this.layoutManager.allowEquationRepositioning=!1,this.layoutManager.updateVisualZOrder(),this.layoutManager.allowEquationRepositioning=i}_clearActiveDot(){try{if(this.activeDotIndex!==-1){const e=this.stepDots[this.activeDotIndex],t=this.styling.dotColor;e.setFillColor(t),e.setStrokeColor(t),this.setLineAboveColor(this.activeDotIndex,this.styling.lineColor),this.textBoxManager.removeTextBoxForDot(this.activeDotIndex),this.highlighting.clearAllExplainHighlights();const r=this.layoutManager.allowEquationRepositioning;this.layoutManager.allowEquationRepositioning=!1,this.layoutManager.updateVisualZOrder(),this.layoutManager.allowEquationRepositioning=r,this.activeDot=null,this.activeDotIndex=-1}}catch(e){console.error("Error clearing active dot:",e)}}_getSimplificationDataForDot(e){try{const t=this.stepDots[e];if(!t||!t.equationRef)return this._createDefaultSimplificationData("No equation found for this step");const r=this.steps.indexOf(t.equationRef);if(r===-1)return this._createDefaultSimplificationData("Step not found in sequence");const i=this._findPreviousVisibleEquationIndex(r),s=[],a=this.getSimplificationHistory(),o=this._getRelevantSimplifications(a,i,r);s.push(...o);for(let u=i+1;u<=r;u++){const c=this._checkForOperationStep(u);c&&s.push({message:c.message,affectedNodes:c.affectedNodes,stepNumber:u-1})}if(s.sort((u,c)=>u.stepNumber-c.stepNumber),s.length>0)return this._createMultipleSimplificationsData(s);const l=this._checkForSingleSimplification(a,r);return l||this._getFallbackSimplificationData(r)}catch(t){return console.error("Error getting simplification data for dot:",t),this._createDefaultSimplificationData("Error retrieving step data")}}getStepTextBoxes(){return this.textBoxManager.getStepTextBoxes()}_createDefaultSimplificationData(e){return{message:e,rawMessages:[e],ruleNames:["Step Description"],affectedNodes:[],resultNodeIds:[],resultProvSources:[],multipleSimplifications:!1}}_findPreviousVisibleEquationIndex(e){for(let t=e-1;t>=0;t--)if(this.steps[t]instanceof ut&&this.steps[t].visible!==!1)return t;return-1}_getRelevantSimplifications(e,t,r){const i=[];for(let s=t;s<r;s++){const a=e.filter(o=>o.stepNumber===s);a.length>0&&i.push(...a)}return i}_createMultipleSimplificationsData(e){const t=e.map(o=>o.message),r=e.map(o=>o.name||"Operation").filter(Boolean),i=[],s=[],a=[];return e.forEach(o=>{o.affectedNodes&&i.push(...o.affectedNodes),o.resultNodeId&&s.push(o.resultNodeId),o.resultProvSources&&a.push(...o.resultProvSources)}),{message:t.join(". "),rawMessages:t,ruleNames:r,affectedNodes:i,resultNodeIds:s,resultProvSources:a,multipleSimplifications:!0}}_checkForOperationStep(e){if(e>0){const t=this.steps[e-1];if(t instanceof Bs)return{message:`Applied ${t.operation} ${t.value} to both sides`,affectedNodes:[t.operatorLeft,t.valueLeft,t.operatorRight,t.valueRight]}}return null}_checkForSingleSimplification(e,t){const r=e.find(i=>i.stepNumber===t-1);return r?{message:r.message,rawMessages:[r.message],ruleNames:[r.name||"Operation"],affectedNodes:r.affectedNodes||[],resultNodeIds:r.resultNodeId?[r.resultNodeId]:[],resultProvSources:r.resultProvSources||[],multipleSimplifications:!1}:null}_getFallbackSimplificationData(e){const t=this.steps[e];if(e===0&&t.stepMark===0){const r=t.toString();return this._createDefaultSimplificationData(`Starting with equation: ${r}`)}else return t&&t.description?this._createDefaultSimplificationData(t.description):this._createDefaultSimplificationData("Step explanation not available")}}class bE{constructor(e,t,r={}){if(this.parentContainer=e,this.sequence=t,this.config={height:60,padding:6,spacing:8,borderRadius:30,fontFamily:"'Albert Sans', sans-serif",fontWeight:"500",colors:{background:Fe.mediumGray,button:"white",popup:Fe.lightGray,undo:"#87D143"},buttonSize:48,checkMarkSize:24,mainFontSize:32,inputFontSize:28,menuFontSize:24,inputWidth:120,popupDirection:"below",showUndoButton:!1,undoIconUrl:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzciIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCAzNyA0NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCjxwYXRoIGQ9Ik0xOC4zNjc2IDQzLjgzMDFDMTMuNTkxMyA0My44MjM3IDkuMDEyNTYgNDEuOTIzNCA1LjYzNTI1IDM4LjU0NTlDMi4yNTc5MiAzNS4xNjg1IDAuMzU3NjYgMzAuNTg5OSAwLjM1MTA3NCAyNS44MTM2QzAuMzUxMDc0IDI1LjMxOTQgMC41NDc0NDEgMjQuODQ1MiAwLjg5Njk2MSAyNC40OTU4QzEuMjQ2NDggMjQuMTQ2MiAxLjcyMDU1IDIzLjk0OTggMi4yMTQ4NSAyMy45NDk4QzIuNzA5MTUgMjMuOTQ5OCAzLjE4MzIyIDI0LjE0NjIgMy41MzI3NCAyNC40OTU4QzMuODgyMjYgMjQuODQ1MiA0LjA3ODYzIDI1LjMxOTQgNC4wNzg2MyAyNS44MTM2QzQuMDc4NjMgMjguNjM5NiA0LjkxNjY2IDMxLjQwMjIgNi40ODY3NSAzMy43NTIxQzguMDU2ODUgMzYuMTAxOSAxMC4yODg1IDM3LjkzMzQgMTIuODk5NCAzOS4wMTQ5QzE1LjUxMDMgNDAuMDk2NCAxOC4zODM1IDQwLjM3OTQgMjEuMTU1MyAzOS44MjhDMjMuOTI3MSAzOS4yNzY4IDI2LjQ3MyAzNy45MTU3IDI4LjQ3MTUgMzUuOTE3NUMzMC40Njk3IDMzLjkxOTEgMzEuODMwOCAzMS4zNzMxIDMyLjM4MTkgMjguNjAxM0MzMi45MzM0IDI1LjgyOTUgMzIuNjUwMyAyMi45NTYzIDMxLjU2ODggMjAuMzQ1NkMzMC40ODczIDE3LjczNDUgMjguNjU1OSAxNS41MDI5IDI2LjMwNiAxMy45MzI4QzIzLjk1NjIgMTIuMzYyNyAyMS4xOTM2IDExLjUyNDcgMTguMzY3NiAxMS41MjQ3SDEyLjE1NUMxMS42NjA3IDExLjUyNDcgMTEuMTg2NiAxMS4zMjgzIDEwLjgzNzEgMTAuOTc4OEMxMC40ODc2IDEwLjYyOTMgMTAuMjkxMiAxMC4xNTUyIDEwLjI5MTIgOS42NjA5QzEwLjI5MTIgOS4xNjY2IDEwLjQ4NzYgOC42OTI1MyAxMC44MzcxIDguMzQzMDFDMTEuMTg2NiA3Ljk5MzQ5IDExLjY2MDcgNy43OTcxMiAxMi4xNTUgNy43OTcxMkgxOC4zNjc2QzIzLjE0NTggNy43OTcxMiAyNy43Mjg1IDkuNjk1MjkgMzEuMTA3MSAxMy4wNzRDMzQuNDg2IDE2LjQ1MjggMzYuMzg0MSAyMS4wMzU0IDM2LjM4NDEgMjUuODEzNkMzNi4zODQxIDMwLjU5MTkgMzQuNDg2IDM1LjE3NDUgMzEuMTA3MSAzOC41NTMyQzI3LjcyODUgNDEuOTMyMSAyMy4xNDU4IDQzLjgzMDEgMTguMzY3NiA0My44MzAxWiIgZmlsbD0id2hpdGUiLz4NCjxwYXRoIGQ9Ik0xOC4zNjc1IDE4Ljk3OThDMTguMTIyNyAxOC45ODEgMTcuODc5OSAxOC45MzMzIDE3LjY1MzggMTguODM5NEMxNy40Mjc3IDE4Ljc0NTQgMTcuMjIyNyAxOC42MDczIDE3LjA1MDQgMTguNDMzMUw5LjU5NTM2IDEwLjk3OEM5LjI0NjM0IDEwLjYyODYgOS4wNTAyOSAxMC4xNTQ5IDkuMDUwMjkgOS42NjA5NkM5LjA1MDI5IDkuMTY3MDYgOS4yNDYzNCA4LjY5MzM2IDkuNTk1MzYgOC4zNDM4OUwxNy4wNTA0IDAuODg4Nzg5QzE3LjIyMTIgMC43MDU2NjcgMTcuNDI2OSAwLjU1ODgwMSAxNy42NTU1IDAuNDU2OTM5QzE3Ljg4NDIgMC4zNTUwNzggMTguMTMwOSAwLjMwMDMwOCAxOC4zODEyIDAuMjk1ODg0QzE4LjYzMTQgMC4yOTE0NjEgMTguODc5OSAwLjMzNzUwOCAxOS4xMTIgMC40MzEyNDRDMTkuMzQ0MSAwLjUyNDk3OSAxOS41NTQ5IDAuNjY0NDg5IDE5LjczMTggMC44NDE0NzNDMTkuOTA5IDEuMDE4NDYgMjAuMDQ4NCAxLjIyOTI5IDIwLjE0MjEgMS40NjEzNEMyMC4yMzYgMS42OTM0MiAyMC4yODIgMS45NDIgMjAuMjc3NSAyLjE5MjI0QzIwLjI3MyAyLjQ0MjUxIDIwLjIxODQgMi42ODkzIDIwLjExNjUgMi45MTc5MkMyMC4wMTQ2IDMuMTQ2NTQgMTkuODY3NyAzLjM1MjMgMTkuNjg0NiAzLjUyMjkzTDEzLjU0NjUgOS42NjA5NkwxOS42ODQ2IDE1Ljc5OUMyMC4wMzM3IDE2LjE0ODUgMjAuMjI5OCAxNi42MjIyIDIwLjIyOTggMTcuMTE2QzIwLjIyOTggMTcuNjEgMjAuMDMzNyAxOC4wODM3IDE5LjY4NDYgMTguNDMzMUMxOS41MTI2IDE4LjYwNzMgMTkuMzA3MyAxOC43NDU0IDE5LjA4MTIgMTguODM5NEMxOC44NTUxIDE4LjkzMzMgMTguNjEyNSAxOC45ODEgMTguMzY3NSAxOC45Nzk4WiIgZmlsbD0id2hpdGUiLz4NCjwvc3ZnPg0K",onUndo:null,...r},r.styles&&typeof r.styles=="object"){const s=r.styles;s.backgroundColor&&(this.config.colors.background=s.backgroundColor),s.buttonColor&&(this.config.colors.button=s.buttonColor),s.popupBackgroundColor&&(this.config.colors.popup=s.popupBackgroundColor),typeof s.borderRadius=="number"&&(this.config.borderRadius=s.borderRadius),typeof s.buttonSize=="number"&&(this.config.buttonSize=s.buttonSize),typeof s.mainFontSize=="number"&&(this.config.mainFontSize=s.mainFontSize),typeof s.inputFontSize=="number"&&(this.config.inputFontSize=s.inputFontSize),typeof s.menuFontSize=="number"&&(this.config.menuFontSize=s.menuFontSize),typeof s.inputWidth=="number"&&(this.config.inputWidth=s.inputWidth),typeof s.padding=="number"&&(this.config.padding=s.padding),typeof s.spacing=="number"&&(this.config.spacing=s.spacing)}r.backgroundColor&&(this.config.colors.background=r.backgroundColor),r.popupBackgroundColor&&(this.config.colors.popup=r.popupBackgroundColor),!!(r.popupBackgroundColor||r.styles&&r.styles.popupBackgroundColor)||(this.config.colors.popup=this.config.colors.background),this.state={activePopup:null,selectedOperation:"+",inputValue:""},this.elements={},this._render(),this._updateApplyButtonState()}_render(){this.elements.toolbarGroup=new Oe,this.parentContainer.addChild(this.elements.toolbarGroup),(this.config.x||this.config.y)&&this.elements.toolbarGroup.setPosition(this.config.x||0,this.config.y||0),this.elements.toolbarGroup.svgObject.style.userSelect="none",this.elements.background=new yt,this.elements.background.setWidthAndHeight(362,this.config.height),this.elements.background.setCornerRadius(this.config.borderRadius),this.elements.background.setFillColor(this.config.colors.background),this.elements.toolbarGroup.addChild(this.elements.background),this.elements.leftButton=this._createButton({text:this.state.selectedOperation,callback:()=>this._togglePopup("operations")}),this.elements.toolbarGroup.addChild(this.elements.leftButton),this.elements.middleInputButton=this._createButton({width:this.config.inputWidth,text:this.state.inputValue,fontSize:this.config.inputFontSize,cornerRadius:10,callback:()=>this._togglePopup("input")}),this.elements.toolbarGroup.addChild(this.elements.middleInputButton);const e='<svg width="43" height="33" viewBox="0 0 43 33" xmlns="http://www.w3.org/2000/svg"><rect x="9.86" y="28.63" width="40.04" height="5.74" transform="rotate(-45 9.86 28.63)" fill="black"/><rect x="13.9" y="32.69" width="19.64" height="5.74" transform="rotate(-135 13.9 32.69)" fill="black"/></svg>';this.elements.rightButton=this._createButton({svg:e,callback:()=>this._applyOperation()}),this.elements.toolbarGroup.addChild(this.elements.rightButton),this.config.showUndoButton&&(this.elements.undoButton=this._createButton({size:this.config.buttonSize,iconUrl:this.config.undoIconUrl,callback:()=>this._handleUndo()}),this.elements.undoButton.setFillColor(this.config.colors.undo||"#87D143"),this.elements.toolbarGroup.addChild(this.elements.undoButton)),this._updateToolbarLayout()}_bringToFront(e){try{const t=e==null?void 0:e.svgObject,r=t==null?void 0:t.parentNode;t&&r&&r.appendChild(t)}catch{}}_togglePopup(e){if(this.state.activePopup&&this.state.activePopup.type===e){this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null;return}this.state.activePopup&&(this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null);let t;e==="operations"?t=this._renderOperationsMenu():e==="input"&&(t=this.state.selectedOperation==="f"?this._renderFunctionMenu():this._renderDigitGrid()),t&&(this.elements.toolbarGroup.addChild(t),this.state.activePopup={type:e,group:t},this._bringToFront(this.elements.toolbarGroup),this._bringToFront(t))}_renderPopup(e,t){const r=new Oe;r.svgObject&&(r.svgObject.style.pointerEvents="auto");const i=e(),s=i.width+16,a=i.height+16,o=new yt;o.setWidthAndHeight(s,a),o.setCornerRadius(this.config.borderRadius),o.setFillColor(this.config.colors.popup),r.addChild(o),i.setPosition(8,8),r.addChild(i),r.width=s,r.height=a;const l=t.xpos+t.width/2-s/2,c=String(this.config.popupDirection||"below")==="above"?t.ypos-a-this.config.spacing:t.ypos+t.height+this.config.spacing;return r.setPosition(Math.round(l),Math.round(c)),r}_renderOperationsMenu(){const e=["f","÷","×","–","+"];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=this._createButton({text:r,fontSize:this.config.menuFontSize,callback:()=>this._selectOperation(r)});t.addChild(i)}),t.doVerticalLayout(),t},this.elements.leftButton)}_renderFunctionMenu(){const e=["sqrt","cos","sin","tan","ln"];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=this._createButton({width:80,height:48,cornerRadius:10,text:r,fontSize:this.config.inputFontSize,callback:()=>this._handleFunctionClick(r)});t.addChild(i)}),t.doVerticalLayout(),t},this.elements.middleInputButton)}_renderDigitGrid(){const e=[["1","2","3"],["4","5","6"],["7","8","9"],["←","0","x"]];return this._renderPopup(()=>{const t=new qr({spacer:this.config.spacing});return e.forEach(r=>{const i=new qr({spacer:this.config.spacing});r.forEach(s=>{const a=this._createButton({text:s,fontSize:this.config.inputFontSize,callback:()=>this._handleDigitClick(s)});i.addChild(a)}),i.doHorizontalLayout(),t.addChild(i)}),t.doVerticalLayout(),t},this.elements.middleInputButton)}_handleFunctionClick(e){this.setInputText(e),this._togglePopup("input")}_handleDigitClick(e){e==="←"?this.state.inputValue=this.state.inputValue.slice(0,-1):this.state.inputValue+=e,this.setInputText(this.state.inputValue)}setInputText(e){this.state.inputValue=e;const t=this.elements.middleInputButton;t.setText(e),t.buttonText.setFontSize(this.config.inputFontSize),this._updateApplyButtonState()}_selectOperation(e){var t;(this.state.selectedOperation==="f"||e==="f")&&this.setInputText(""),this.state.selectedOperation=e,this.elements.leftButton.setText(e),this._togglePopup("operations"),e==="f"&&((t=this.state.activePopup)==null?void 0:t.type)==="input"&&(this._togglePopup("input"),this._togglePopup("input"))}_applyOperation(){const e=this.state.selectedOperation,t=this.state.inputValue;if(!(!this.sequence||t==="")){if(e==="f")this.sequence.applyEquationFunction(t);else{const i={"÷":"divide","×":"multiply","–":"subtract","+":"add"}[e];let s,a=!1;const o=parseFloat(t);if(!isNaN(o)&&String(o)===t.trim())s=o,a=!0;else if(typeof window.math<"u"&&window.math.parse)try{s=window.math.parse(t),a=!0}catch{a=!1}i&&a&&this.sequence.applyEquationOperation(s,i)}this.setInputText(""),this.state.activePopup&&(this.elements.toolbarGroup.removeChild(this.state.activePopup.group),this.state.activePopup=null);try{typeof window<"u"&&(typeof window.refreshDisplayAndFilters=="function"&&window.refreshDisplayAndFilters(),typeof window.onOMDOperationApplied=="function"&&window.onOMDOperationApplied(this.sequence))}catch{}}}_createButton({width:e,height:t,size:r,text:i,svg:s,iconUrl:a,fontSize:o,cornerRadius:l,callback:u}){const c=new Xn,h=e||r||this.config.buttonSize,f=t||r||this.config.buttonSize;if(c.setWidthAndHeight(h,f),c.setCornerRadius(l!==void 0?l:h/2),c.setFillColor(this.config.colors.button),c.setText(i||""),c.setFontSize(o||this.config.mainFontSize),c.setFontFamily(this.config.fontFamily),c.buttonText.setFontWeight(this.config.fontWeight),c.buttonText.setPosition(h/2,f/2+(o||this.config.mainFontSize)/3),s){const d="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(s);c.addImage(d,this.config.checkMarkSize,this.config.checkMarkSize)}else if(a){const d=this.config.checkMarkSize;c.addImage(a,d,d)}return c.setClickCallback(u),c}_updateApplyButtonState(){const e=this.elements.rightButton;this.state.inputValue.length>0?(e.setOpacity(1),e.setClickCallback(()=>this._applyOperation())):(e.setOpacity(.5),e.setClickCallback(null))}_updateToolbarLayout(){const e=this.config.buttonSize*2+this.config.inputWidth+this.config.spacing*2+this.config.padding*2;this.elements.background.setWidth(e);const t=this.config.padding;let r=this.config.padding;if(this.elements.leftButton.setPosition(r,t),r+=this.elements.leftButton.width+this.config.spacing,this.elements.middleInputButton.setPosition(r,t),r+=this.elements.middleInputButton.width+this.config.spacing,this.elements.rightButton.setPosition(r,t),this.elements.undoButton){const i=this.elements.background.width+this.config.spacing;this.elements.undoButton.setPosition(i,t)}}_handleUndo(){if(typeof this.config.onUndo=="function"){try{this.config.onUndo(this.sequence)}catch{}return}try{typeof window<"u"&&typeof window.onOMDToolbarUndo=="function"&&window.onOMDToolbarUndo(this.sequence)}catch{}}}class xE extends Oe{constructor(e=[],t={}){var s,a,o,l,u,c;if(super(),this.options={...t},this.toolbarOptions=null,typeof t.toolbar=="object"?this.toolbarOptions={enabled:!0,...t.toolbar}:t.toolbar===!0?this.toolbarOptions={enabled:!0}:t.toolbar===!1&&(this.toolbarOptions={enabled:!1}),this.stylingOptions=t.styling||null,t.stepVisualizer){const h=((s=this.stylingOptions)==null?void 0:s.stepVisualizer)||{};this.sequence=new Go(e,h)}else this.sequence=new jo(e);if((a=this.stylingOptions)!=null&&a.equationBackground&&this.sequence.setDefaultEquationBackground(this.stylingOptions.equationBackground),t.stepVisualizer&&((o=this.stylingOptions)!=null&&o.stepVisualizerBackground)&&typeof this.sequence.setBackgroundStyle=="function"&&this.sequence.setBackgroundStyle(this.stylingOptions.stepVisualizerBackground),(l=this.toolbarOptions)!=null&&l.enabled){const h={...this.toolbarOptions};h.showUndoButton&&!h.onUndo&&(h.onUndo=()=>{if(typeof window<"u"&&typeof window.onOMDToolbarUndo=="function")try{window.onOMDToolbarUndo(this.sequence)}catch{}}),this.toolbar=new bE(this,this.sequence,h)}this.overlayPadding=typeof((u=this.toolbarOptions)==null?void 0:u.overlayPadding)=="number"?this.toolbarOptions.overlayPadding:34,this.layoutGroup=new qr,this.layoutGroup.setSpacer(16),this.layoutGroup.addChild(this.sequence),this._overlayChildren=[];const r=((c=this.toolbarOptions)==null?void 0:c.position)||this.options.toolbarPosition,i=r==="bottom"||r==="overlay-bottom";this.toolbar&&(i?this.addChild(this.toolbar.elements.toolbarGroup):this.layoutGroup.addChild(this.toolbar.elements.toolbarGroup)),this.addChild(this.layoutGroup),this.updateLayout()}updateLayout(){var r;this.sequence.updateLayout(),this.layoutGroup.doVerticalLayout();const e=((r=this.toolbarOptions)==null?void 0:r.position)||this.options.toolbarPosition,t=e==="bottom"||e==="overlay-bottom";if(this.toolbar&&!t){const i=this.sequence.width,s=this.toolbar.elements.background.width,a=this.toolbar.elements.toolbarGroup;a.setPosition((i-s)/2,a.ypos)}this.width=this.layoutGroup.width,this.height=this.layoutGroup.height}initialize(){this.sequence&&typeof this.sequence.initialize=="function"?this.sequence.initialize():this.sequence&&(typeof this.sequence.computeDimensions=="function"&&this.sequence.computeDimensions(),typeof this.sequence.updateLayout=="function"&&this.sequence.updateLayout()),this.updateLayout()}setFontSize(e){this.sequence&&typeof this.sequence.setFontSize=="function"&&this.sequence.setFontSize(e),this.updateLayout()}closeActiveDot(){this.sequence&&typeof this.sequence.closeActiveDot=="function"&&this.sequence.closeActiveDot()}closeAllTextBoxes(){this.sequence&&typeof this.sequence.closeAllTextBoxes=="function"?this.sequence.closeAllTextBoxes():this.sequence&&typeof this.sequence.closeActiveDot=="function"&&this.sequence.closeActiveDot()}forceCloseAll(){this.sequence&&typeof this.sequence.forceCloseAll=="function"?this.sequence.forceCloseAll():this.closeAllTextBoxes()}getSequence(){return this.sequence}getOverlayPadding(){return this.overlayPadding}getToolbarVisualHeight(){return this.toolbar&&this.toolbar.elements&&this.toolbar.elements.background&&this.toolbar.elements.background.height||0}isToolbarOverlay(){var t;const e=((t=this.toolbarOptions)==null?void 0:t.position)||this.options.toolbarPosition;return!!(this.toolbar&&(e==="bottom"||e==="overlay-bottom"))}positionToolbarOverlay(e,t,r=16){var y;if(!this.toolbar||!this.isToolbarOverlay())return;const i=this.toolbar.elements.toolbarGroup,s=this.toolbar.elements.background.width,a=this.toolbar.elements.background.height,o=this.xpos||0,l=this.ypos||0,u=typeof this.scale=="number"&&this.scale>0?this.scale:1,c=typeof r=="number"?r:this.overlayPadding;let h=(e-s)/2,f=t-a-c;h=Math.round(h),f=Math.round(f);const d=(h-o)/u,p=(f-l)/u;let m=i.svgObject;for(;m&&m.tagName!=="svg"&&m.parentElement;)m=m.parentElement;(y=m==null?void 0:m.getAttribute)!=null&&y.call(m,"viewBox"),typeof i.setScale=="function"&&i.setScale(1/u),i.setPosition(d,p),i.svgObject&&(i.svgObject.style.display="block",i.svgObject.style.zIndex="1000");try{this.updateOverlayChildren(e,t,r)}catch{}}addOverlayChild(e,t,r,i={}){var g,b,w,x;const{anchor:s="toolbar-center",offsetX:a=0,offsetY:o=0,padding:l=16,counterScale:u=!0,addToStack:c=!0,customCoords:h=null}=i||{};if(!e||typeof t!="number"||typeof r!="number")return null;const f=this.xpos||0,d=this.ypos||0,p=typeof this.scale=="number"&&this.scale>0?this.scale:1;let m=0,y=0;if(s==="custom"&&h&&typeof h.x=="number"&&typeof h.y=="number")m=Math.round(h.x),y=Math.round(h.y);else if(s.startsWith("toolbar")){if(!this.toolbar)return null;const N=((b=(g=this.toolbar.elements)==null?void 0:g.background)==null?void 0:b.width)||0,D=((x=(w=this.toolbar.elements)==null?void 0:w.background)==null?void 0:x.height)||0,C=(t-N)/2,A=C+N,E=C+N/2;y=Math.round(r-D-(typeof l=="number"?l:this.overlayPadding)),s==="toolbar-center"?m=Math.round(E):s==="toolbar-left"?m=Math.round(C):s==="toolbar-right"?m=Math.round(A):m=Math.round(E)}else if(s.startsWith("top")){const N=Math.round(typeof l=="number"?l:16),D=Math.round(typeof l=="number"?l:16),C=Math.round(t-(typeof l=="number"?l:16));y=N,s==="top-left"?m=D:s==="top-center"?m=Math.round(t/2):s==="top-right"?m=C:m=D}else m=Math.round(t/2),y=Math.round(r/2);m=Math.round(m+(a||0)),y=Math.round(y+(o||0));const v=(m-f)/p,S=(y-d)/p;if(u&&e&&typeof e.setScale=="function")try{e.setScale(1/p)}catch{}if(e&&typeof e.setPosition=="function")try{e.setPosition(v,S)}catch{}if(c)try{this.addChild(e)}catch{try{this.layoutGroup.addChild(e)}catch{}}try{const N={anchor:s,offsetX:a,offsetY:o,padding:l,counterScale:u,addToStack:c,customCoords:h};this._overlayChildren.push({child:e,opts:N})}catch{}if(e&&e.svgObject){try{e.svgObject.style.zIndex="1001"}catch{}try{e.svgObject.style.display="block"}catch{}}return e}updateOverlayChildren(e,t,r=16){var o,l,u,c;if(!Array.isArray(this._overlayChildren)||this._overlayChildren.length===0)return;const i=this.xpos||0,s=this.ypos||0,a=typeof this.scale=="number"&&this.scale>0?this.scale:1;for(const h of this._overlayChildren){if(!h||!h.child)continue;const f=h.child,d=h.opts||{},p=d.anchor||"toolbar-center",m=d.offsetX||0,y=d.offsetY||0,v=typeof d.padding=="number"?d.padding:r,S=typeof d.counterScale=="boolean"?d.counterScale:!0,g=d.customCoords||null;let b=0,w=0;if(p==="custom"&&g&&typeof g.x=="number"&&typeof g.y=="number")b=Math.round(g.x+m),w=Math.round(g.y+y);else if(p.startsWith("toolbar")){if(!this.toolbar)continue;const D=((l=(o=this.toolbar.elements)==null?void 0:o.background)==null?void 0:l.width)||0,C=((c=(u=this.toolbar.elements)==null?void 0:u.background)==null?void 0:c.height)||0,A=(e-D)/2,E=A+D,F=A+D/2;w=Math.round(t-C-v+y),p==="toolbar-center"?b=Math.round(F+m):p==="toolbar-left"?b=Math.round(A+m):p==="toolbar-right"?b=Math.round(E+m):b=Math.round(F+m)}else if(p.startsWith("top")){const D=Math.round(v),C=Math.round(v),A=Math.round(e-v);w=D+y,p==="top-left"?b=C+m:p==="top-center"?b=Math.round(e/2)+m:p==="top-right"?b=A+m:b=C+m}else b=Math.round(e/2+m),w=Math.round(t/2+y);const x=(b-i)/a,N=(w-s)/a;if(S&&f&&typeof f.setScale=="function")try{f.setScale(1/a)}catch{}if(f&&typeof f.setPosition=="function")try{f.setPosition(x,N)}catch{}}}removeOverlayChild(e){if(!e||!Array.isArray(this._overlayChildren))return!1;let t=-1;for(let r=0;r<this._overlayChildren.length;r++)if(this._overlayChildren[r].child===e){t=r;break}if(t===-1)return!1;this._overlayChildren.splice(t,1);try{this.removeChild(e)}catch{}return!0}getToolbar(){return this.toolbar}undoLastOperation(){const e=this.sequence;if(!e||!Array.isArray(e.steps)||e.steps.length===0)return!1;let t=-1;for(let i=e.steps.length-1;i>=0;i--){const s=e.steps[i];if(s instanceof ut||(s==null?void 0:s.type)==="omdEquationNode"){t=i;break}}if(t===-1)return!1;let r=t;for(let i=t;i>=0;i--){const s=e.steps[i];if(s instanceof Bs||(s==null?void 0:s.type)==="omdOperationDisplayNode"){r=i;break}}for(let i=e.steps.length-1;i>=r;i--){const s=e.steps[i];try{e.removeChild(s)}catch{}}if(e.steps.splice(r),e.argumentNodeList.steps=e.steps,Array.isArray(e.stepDescriptions)&&(e.stepDescriptions.length=e.steps.length),Array.isArray(e.importanceLevels)&&(e.importanceLevels.length=e.steps.length),typeof e.currentStepIndex=="number"&&e.currentStepIndex>=e.steps.length&&(e.currentStepIndex=Math.max(0,e.steps.length-1)),typeof e.rebuildNodeMap=="function"&&e.rebuildNodeMap(),typeof e.computeDimensions=="function"&&e.computeDimensions(),typeof e.updateLayout=="function"&&e.updateLayout(),typeof e.rebuildVisualizer=="function")try{e.highlighting&&typeof e.highlighting.clearAllExplainHighlights=="function"&&e.highlighting.clearAllExplainHighlights(),e.rebuildVisualizer()}catch{}else if(typeof e._initializeVisualElements=="function")try{e.highlighting&&typeof e.highlighting.clearAllExplainHighlights=="function"&&e.highlighting.clearAllExplainHighlights(),e._initializeVisualElements(),typeof e.computeDimensions=="function"&&e.computeDimensions(),typeof e.updateLayout=="function"&&e.updateLayout()}catch{}try{const i=a=>a instanceof ut||(a==null?void 0:a.type)==="omdEquationNode",s=Array.isArray(e.steps)?e.steps.filter(i).length:0;if(Array.isArray(e.stepDots)&&e.visualContainer){const a=new Set(e.steps.filter(i)),o=[];for(const l of e.stepDots)if(!l||!l.equationRef||!a.has(l.equationRef))try{e.visualContainer.removeChild(l)}catch{}else o.push(l);e.stepDots=o}if(e.visualContainer&&Array.isArray(e.visualContainer.childList)){const a=new Set([...e.stepDots||[],...e.stepLines||[]]),o=[];e.visualContainer.childList.forEach(l=>{a.has(l)||o.push(l)}),o.forEach(l=>{try{e.visualContainer.removeChild(l)}catch{}})}if(Array.isArray(e.stepDots)&&e.visualContainer)for(;e.stepDots.length>s;){const a=e.stepDots.pop();try{e.visualContainer.removeChild(a)}catch{}}if(Array.isArray(e.stepLines)&&e.visualContainer){const a=Math.max(0,s-1);for(;e.stepLines.length>a;){const o=e.stepLines.pop();try{e.visualContainer.removeChild(o)}catch{}}}if(e.layoutManager)try{e.layoutManager.updateVisualLayout(!0),e.layoutManager.updateVisualVisibility(),e.layoutManager.updateAllLinePositions()}catch{}}catch{}return this.updateLayout(),!0}getSvg(){return this.svgObject}}class Vq{constructor(e,t={}){this.container=e;const{stepVisualizer:r=!1,stackOptions:i=null,math:s=typeof window<"u"&&window.math?window.math:null,...a}=t||{};this.options={fontSize:32,centerContent:!0,topMargin:40,bottomMargin:16,observeResize:!0,expandViewboxToFitContent:!0,fitToContent:!0,autoScale:!1,maxScale:1,edgePadding:16,autoCloseStepVisualizer:!0,stepVisualizer:r,stackOptions:i,math:s,...a},this.svg=new j0,this.node=null,this._suppressResizeObserver=!1,this._lastViewbox=null,this._lastContentExtents=null,this._viewboxLocked=!1,this._viewboxLockThreshold=8,this._setupSVG()}_setupSVG(){const e=this.container.offsetWidth||800,t=this.container.offsetHeight||600;this.svg.setViewbox(e,t),this.svg.svgObject.style.width="100%",this.svg.svgObject.style.height="100%",this.svg.svgObject.style.verticalAlign="middle",this.svg.svgObject.style.overflow="hidden",this.container.appendChild(this.svg.svgObject);try{const r="http://www.w3.org/2000/svg";this._contentGroup=document.createElementNS(r,"g"),this._contentGroup.setAttribute("id","omd-content-root"),this.svg.svgObject.appendChild(this._contentGroup),this._contentOffsetX=0,this._contentOffsetY=0}catch{this._contentGroup=null}this.options.observeResize&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this._handleResize()}),this.resizeObserver.observe(this.container))}_handleResize(){if(this._suppressResizeObserver)return;const e=this.container.offsetWidth,t=this.container.offsetHeight;this._lastContainerWidth===e&&this._lastContainerHeight===t||(this._lastContainerWidth=e,this._lastContainerHeight=t,this.svg.setViewbox(e,t),this.options.centerContent&&this.node&&this.centerNode(),this._repositionOverlayToolbar(),this.options.debugExtents&&this._drawDebugOverlays())}_syncViewboxToContainer(e=this.container.offsetWidth||0,t=this.container.offsetHeight||0){!e||!t||(this.svg.setViewbox(e,t),this.svg.setWidthAndHeight(e,t),this._lastViewbox=`0 0 ${e} ${t}`)}_ensureViewboxFits(e,t){if(!this.node)return;const r=10;let i=null;try{const C=this._collectNodeExtents(this.node);C&&(i={minX:C.minX,minY:C.minY,maxX:C.maxX,maxY:C.maxY})}catch{i=null}if(i||(i=this._computeNodeExtents(this.node)),!i)return;const s=Math.floor(i.minX-r),a=Math.floor(i.minY-r),o=Math.ceil(i.maxX+r),l=Math.ceil(i.maxY+r),u=this.svg.svgObject.getAttribute("viewBox")||"";let c=0,h=0,f=0,d=0;if(u){const C=u.split(/\s+/).map(Number).filter(A=>!isNaN(A));C.length===4&&(c=C[0],h=C[1],f=C[2],d=C[3])}const p=c,m=h,y=Math.max(c+f,o),v=Math.max(h+d,l),S=Math.max(f,y-p),g=Math.max(d,v-m),b=Math.abs(S-f),w=Math.abs(g-d),x=1e4;if(S>x||g>x){console.warn("omdDisplay: viewBox growth capped to prevent runaway expansion",S,g);return}if(b<.5&&w<.5)return;const N=`${s},${a},${o},${l}`;if(this._lastContentExtents===N&&w>0&&g>d)return;if(this._viewboxLocked){const C=S-f,A=g-d;if(C<this._viewboxLockThreshold&&A<this._viewboxLockThreshold)return}const D=`${p} ${m} ${S} ${g}`;if(this._lastViewbox!==D){this._suppressResizeObserver=!0;try{this.svg.svgObject.setAttribute("viewBox",D)}finally{setTimeout(()=>{this._suppressResizeObserver=!1},0)}this._lastViewbox=D,this._lastContentExtents=N,w<2&&b<2&&!this._viewboxLocked&&(this._viewboxLocked=!0)}}_computeNodeExtents(e){if(!e)return null;const t=new Set,r=[{node:e,absX:e.xpos||0,absY:e.ypos||0}];let i=1/0,s=1/0,a=-1/0,o=-1/0;for(;r.length;){const{node:l,absX:u,absY:c}=r.pop();if(!l||t.has(l))continue;t.add(l);const h=l.width||0,f=l.height||0,d=u,p=c;if(i=Math.min(i,d),s=Math.min(s,p),a=Math.max(a,d+h),o=Math.max(o,p+f),Array.isArray(l.childList))for(const m of l.childList){if(!m)continue;const y=(m.xpos||0)+d,v=(m.ypos||0)+p;r.push({node:m,absX:y,absY:v})}if(l.argumentNodeList){for(const m of Object.values(l.argumentNodeList))if(Array.isArray(m))for(const y of m){if(!y)continue;const v=(y.xpos||0)+d,S=(y.ypos||0)+p;r.push({node:y,absX:v,absY:S})}else if(m){const y=(m.xpos||0)+d,v=(m.ypos||0)+p;r.push({node:m,absX:y,absY:v})}}}return i===1/0?null:{minX:i,minY:s,maxX:a,maxY:o}}_collectNodeExtents(e){if(!e)return null;const t=new Set,r=[{node:e,absX:e.xpos||0,absY:e.ypos||0,parent:null}],i=[];let s=1/0,a=1/0,o=-1/0,l=-1/0;for(;r.length;){const{node:u,absX:c,absY:h,parent:f}=r.pop();if(!u||t.has(u))continue;t.add(u);let d=c,p=h,m=d,y=p,v=d,S=p;try{if(u.svgObject&&typeof u.svgObject.getBBox=="function"&&typeof u.svgObject.getCTM=="function"){const g=u.svgObject.getBBox(),b=u.svgObject.getCTM(),x=[{x:g.x,y:g.y},{x:g.x+g.width,y:g.y},{x:g.x,y:g.y+g.height},{x:g.x+g.width,y:g.y+g.height}].map(N=>({x:b.a*N.x+b.c*N.y+b.e,y:b.b*N.x+b.d*N.y+b.f}));m=Math.min(...x.map(N=>N.x)),y=Math.min(...x.map(N=>N.y)),v=Math.max(...x.map(N=>N.x)),S=Math.max(...x.map(N=>N.y)),d=m,p=y}else{const g=u.width||0,b=u.height||0;d=c,p=h,m=d,y=p,v=d+g,S=p+b}}catch{const b=u.width||0,w=u.height||0;d=c,p=h,m=d,y=p,v=d+b,S=p+w}if(i.push({node:u,minX:m,minY:y,maxX:v,maxY:S,parent:f}),s=Math.min(s,m),a=Math.min(a,y),o=Math.max(o,v),l=Math.max(l,S),Array.isArray(u.childList))for(const g of u.childList){if(!g)continue;const b=(g.xpos||0)+d,w=(g.ypos||0)+p;r.push({node:g,absX:b,absY:w,parent:u})}if(u.argumentNodeList){for(const g of Object.values(u.argumentNodeList))if(Array.isArray(g))for(const b of g){if(!b)continue;const w=(b.xpos||0)+d,x=(b.ypos||0)+p;r.push({node:b,absX:w,absY:x,parent:u})}else if(g){const b=(g.xpos||0)+d,w=(g.ypos||0)+p;r.push({node:g,absX:b,absY:w,parent:u})}}}return s===1/0?null:{nodes:i,minX:s,minY:a,maxX:o,maxY:l}}_clearDebugOverlays(){if(!this.svg||!this.svg.svgObject)return;const e=this.svg.svgObject.querySelector("#omd-debug-overlays");e&&e.remove()}_drawDebugOverlays(){if(!this.options.debugExtents||!this.svg||!this.svg.svgObject||!this.node)return;this._clearDebugOverlays();const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"g");t.setAttribute("id","omd-debug-overlays"),t.setAttribute("pointer-events","none");const r=this._collectNodeExtents(this.node);if(!r)return;const{nodes:i,minX:s,minY:a,maxX:o,maxY:l}=r,u=document.createElementNS(e,"rect");u.setAttribute("x",String(s)),u.setAttribute("y",String(a)),u.setAttribute("width",String(o-s)),u.setAttribute("height",String(l-a)),u.setAttribute("fill","none"),u.setAttribute("stroke","blue"),u.setAttribute("stroke-dasharray","6 4"),u.setAttribute("stroke-width","0.8"),t.appendChild(u);const c=this.svg.svgObject.getAttribute("viewBox")||"";if(c){const f=c.split(/\s+/).map(Number).filter(d=>!isNaN(d));if(f.length===4){const[d,p,m,y]=f,v=document.createElementNS(e,"rect");v.setAttribute("x",String(d)),v.setAttribute("y",String(p)),v.setAttribute("width",String(m)),v.setAttribute("height",String(y)),v.setAttribute("fill","none"),v.setAttribute("stroke","orange"),v.setAttribute("stroke-width","1"),v.setAttribute("opacity","0.9"),t.appendChild(v)}}const h=[];for(const f of i){const d=document.createElementNS(e,"rect");d.setAttribute("x",String(f.minX)),d.setAttribute("y",String(f.minY)),d.setAttribute("width",String(Math.max(0,f.maxX-f.minX))),d.setAttribute("height",String(Math.max(0,f.maxY-f.minY))),d.setAttribute("fill","none"),d.setAttribute("stroke-width","0.6");let p="green";if(f.parent){const m=(f.parent.xpos||0)+(f.parent._absX||0),y=(f.parent.ypos||0)+(f.parent._absY||0),v=i.find(x=>x.node===f.parent),S=v?v.minX:m,g=v?v.minY:y,b=v?v.maxX:S+(f.parent.width||0),w=v?v.maxY:g+(f.parent.height||0);(f.minX<S||f.minY<g||f.maxX>b||f.maxY>w)&&(p="red",h.push({node:f.node,bounds:f}))}d.setAttribute("stroke",p),d.setAttribute("opacity",p==="red"?"0.9":"0.6"),t.appendChild(d)}h.length&&console.warn("omdDisplay: debugExtents found overflowing nodes:",h.map(f=>{var d;return{type:(d=f.node)==null?void 0:d.type,bounds:f.bounds}})),this.svg.svgObject.appendChild(t)}centerNode(){if(!this.node)return;if(this._centerCallCount||(this._centerCallCount=0),this._centerCallCount++,this._centerCallCount>500){console.warn("omdDisplay: excessive centerNode calls detected; halting further centering to prevent loop");return}const e=this.container.offsetWidth||0,t=this.container.offsetHeight||0;if(this.options.autoCloseStepVisualizer&&this.node)try{typeof this.node.forceCloseAll=="function"?this.node.forceCloseAll():typeof this.node.closeAllTextBoxes=="function"?this.node.closeAllTextBoxes():typeof this.node.closeActiveDot=="function"&&this.node.closeActiveDot()}catch{}let r=this.node.width||0,i=this.node.height||0;if(this.node.getSequence){const m=this.node.getSequence();if(m&&(m.width&&m.height&&(r=m.sequenceWidth||m.width,i=m.sequenceHeight||m.height),m.getCurrentStep)){const y=m.getCurrentStep();if(y&&y.width&&y.height){const v=m.sequenceWidth||y.width,S=m.sequenceHeight||y.height;r=Math.max(r,v),i=Math.max(i,S)}}}let s=1;if(this.options.autoScale&&r>0&&i>0){if(this.options.autoCloseStepVisualizer&&this.node)try{typeof this.node.closeActiveDot=="function"?this.node.closeActiveDot():typeof this.node.closeAllTextBoxes=="function"&&this.node.closeAllTextBoxes()}catch{}let m=!1;if(this.node&&(m=this.node.type==="omdStepVisualizer"||typeof Go<"u"&&this.node instanceof Go),m){const y=this.node&&typeof this.node.scale=="number"?this.node.scale:void 0;s=y&&y>0?y:1}else{const y=this.options.edgePadding||0,v=this.options.topMargin||0;let g=this.options.bottomMargin||0;if(this.node&&typeof this.node.isToolbarOverlay=="function"&&this.node.isToolbarOverlay()){const C=typeof this.node.getToolbarVisualHeight=="function"?this.node.getToolbarVisualHeight():0;g+=C+(this.node.getOverlayPadding?this.node.getOverlayPadding():16)}const b=Math.max(0,e-y*2),w=Math.max(0,t-(v+g)),x=b>0?b/r:1,N=w>0?w/i:1,D=typeof this.options.maxScale=="number"?this.options.maxScale:1;s=Math.min(x,N,D),(!isFinite(s)||s<=0)&&(s=1)}}typeof this.node.setScale=="function"&&this.node.setScale(s);let a;if(this.node.type==="omdEquationSequenceNode"&&this.node.alignPointX!==void 0)a=e/2-this.node.alignPointX*s;else{const m=r*s;a=(e-m)/2}const o=r*s,l=i*s,u=Math.max(0,t-(this.options.topMargin||0)-(this.options.bottomMargin||0)),c=(this.options.topMargin||0)+Math.max(0,(u-l)/2),h=l+(this.options.topMargin||0)+(this.options.bottomMargin||0),f=o>e,d=h>t,p=`${r}x${i}x${s}`;if(this._lastCenterSignature===p&&!f&&!d){this.node.setPosition&&this.node.setPosition(a,c);return}f||d?(this.node.setScale&&this.node.setScale(s),this.options.expandViewboxToFitContent!==!1?this._ensureViewboxFits(r,i):this._syncViewboxToContainer(e,t),this._repositionOverlayToolbar(),d?(this.container.style.overflowY="auto",this.container.style.overflowX="hidden"):this.container.style.overflow="hidden",this.options.debugExtents&&this._drawDebugOverlays()):(this.node.setPosition(a,c),this._repositionOverlayToolbar(),this.options.expandViewboxToFitContent!==!1?this._ensureViewboxFits(r,i):this._syncViewboxToContainer(e,t),h>t?(this.container.style.overflowY="auto",this.container.style.overflowX="hidden"):this.container.style.overflow="hidden",this.options.debugExtents&&this._drawDebugOverlays()),this._lastCenterSignature=p}_getMathInstance(){return this.options.math?this.options.math:typeof window<"u"&&window.math?window.math:null}_createNodeFromSegment(e,t){try{if(e.includes("="))return ut.fromString(e);if(!t||typeof t.parse!="function")throw new Error("math.js parser is unavailable");const r=t.parse(e),i=_t(r);return new i(r)}catch(r){const i=(r==null?void 0:r.message)||String(r);throw new Error(`Failed to parse expression "${e}": ${i}`,{cause:r})}}_createNodesFromString(e){const t=(e||"").split(";").map(i=>i.trim()).filter(Boolean);if(!t.length)throw new Error("omdDisplay.render() received an empty expression string.");const r=this._getMathInstance();return t.map(i=>this._createNodeFromSegment(i,r))}_buildStackOptions(){const e={};return typeof this.options.stepVisualizer=="boolean"&&(e.stepVisualizer=this.options.stepVisualizer),this.options.styling&&(e.styling=this.options.styling),Object.prototype.hasOwnProperty.call(this.options,"toolbar")&&(e.toolbar=this.options.toolbar),this.options.stackOptions&&typeof this.options.stackOptions=="object"?{...e,...this.options.stackOptions}:e}_createStackFromSteps(e){if(!e||!e.length)throw new Error("omdDisplay.render() received no steps to render.");return new xE(e,this._buildStackOptions())}fitToContent(){if(!this.node)return;let e=0,t=0,r=0,i=0,s=0,a=0;if(this.node.getSequence){const c=this.node.getSequence();if(c&&c.width&&c.height){if(r=c.sequenceWidth||c.width,i=c.sequenceHeight||c.height,c.getCurrentStep){const h=c.getCurrentStep();h&&h.width&&h.height&&(s=c.sequenceWidth||h.width,a=c.sequenceHeight||h.height)}e=Math.max(r,s),t=Math.max(i,a)}}(e===0||t===0)&&this.node.width&&this.node.height&&(e=this.node.width,t=this.node.height),(e===0||t===0)&&(e=200,t=60);const o=10,l=e+o*2,u=t+o*2;this.node&&this.node.setPosition&&this.node.setPosition(o,o),this.svg.setViewbox(l,u),this.svg.setWidthAndHeight(l,u),this.container.style.width=`${l}px`,this.container.style.height=`${u}px`,this.options.debugExtents?this._drawDebugOverlays():this._clearDebugOverlays()}render(e){if(this.node&&this.removeChild(this.node),typeof e=="string"){const r=this._createNodesFromString(e);this.node=this._createStackFromSteps(r)}else if(Array.isArray(e)){const r=e.flatMap(i=>typeof i=="string"?this._createNodesFromString(i):i).filter(Boolean);this.node=this._createStackFromSteps(r)}else this.node=e;if(!this.node)throw new Error("omdDisplay.render() was unable to create a node from the provided expression.");const t=this.node.getSequence?this.node.getSequence():null;if(t&&(t.setFontSize(this.options.fontSize),t.updateStepsVisibility(r=>(r.stepMark??0)===t.getFilterLevel())),this._contentGroup&&this.node&&this.node.svgObject)try{this._contentGroup.appendChild(this.node.svgObject)}catch{this.svg.addChild(this.node)}else this.svg.addChild(this.node);if(this.options.fontFamily&&this.setFont(this.options.fontFamily,this.options.fontWeight||"400"),this.options.fitToContent?this.fitToContent():this.options.centerContent&&this.centerNode(),this._repositionOverlayToolbar(),this.options.expandViewboxToFitContent!==!1){const r=this.node&&this.node.width?this.node.width:0,i=this.node&&this.node.height?this.node.height:0;this._ensureViewboxFits(r,i)}else this._syncViewboxToContainer();return this.options.debugExtents?this._drawDebugOverlays():this._clearDebugOverlays(),typeof window<"u"&&!window.refreshDisplayAndFilters&&(window.refreshDisplayAndFilters=()=>{try{const r=this.getCurrentNode(),i=r!=null&&r.getSequence?r.getSequence():null;i&&(typeof i.simplifyAll=="function"&&i.simplifyAll(),typeof i.updateStepsVisibility=="function"&&i.updateStepsVisibility(s=>(s.stepMark??0)===0),typeof r.updateLayout=="function"&&r.updateLayout()),this.options.centerContent&&this.centerNode()}catch{}}),this.node}addChild(e){if(this._contentGroup&&e&&e.svgObject)try{this._contentGroup.appendChild(e.svgObject)}catch{this.svg.addChild(e)}else this.svg.addChild(e);return this.options.centerContent&&this.centerNode(),e}removeChild(e){if(this.svg){try{e&&e.svgObject?this._contentGroup&&this._contentGroup.contains(e.svgObject)?this._contentGroup.removeChild(e.svgObject):this.svg.svgObject&&this.svg.svgObject.contains(e.svgObject)?this.svg.svgObject.removeChild(e.svgObject):typeof this.svg.removeChild=="function"&&this.svg.removeChild(e):typeof this.svg.removeChild=="function"&&this.svg.removeChild(e)}catch{}this.node===e&&(this.node=null)}}update(e){if(this.node&&(this._contentGroup&&this.node&&this.node.svgObject&&this._contentGroup.contains(this.node.svgObject)?this._contentGroup.removeChild(this.node.svgObject):typeof this.svg.removeChild=="function"&&this.svg.removeChild(this.node)),this.node=e,this.node.setFontSize(this.options.fontSize),this.node.initialize(),this._contentGroup&&this.node&&this.node.svgObject)try{this._contentGroup.appendChild(this.node.svgObject)}catch{this.svg.addChild(this.node)}else this.svg.addChild(this.node);this.options.centerContent&&this.centerNode(),this._repositionOverlayToolbar()}setFontSize(e){this.options.fontSize=e,this.node&&(this.node.getSequence&&typeof this.node.getSequence=="function"?this.node.getSequence().setFontSize(e):this.node.setFontSize&&typeof this.node.setFontSize=="function"&&this.node.setFontSize(e),this.node.initialize(),this.options.centerContent&&this.centerNode())}setFont(e,t="400"){var r;if((r=this.svg)!=null&&r.svgObject){const i=s=>{s.style&&(s.style.fontFamily=e,s.style.fontWeight=t),Array.from(s.children||[]).forEach(i)};i(this.svg.svgObject),this.options.fontFamily=e,this.options.fontWeight=t}}clear(){this.node&&(this.removeChild(this.node),this.node=null)}destroy(){this.clear(),this.resizeObserver&&this.resizeObserver.disconnect(),this.container.contains(this.svg.svgObject)&&this.container.removeChild(this.svg.svgObject)}_repositionOverlayToolbar(){const e=this.container.offsetWidth||0,t=this.container.offsetHeight||0,r=this.node;if(!r)return;if(typeof r.isToolbarOverlay=="function"&&typeof r.positionToolbarOverlay=="function"&&r.isToolbarOverlay()){const s=typeof r.getOverlayPadding=="function"?r.getOverlayPadding():16;r.positionToolbarOverlay(e,t,s)}}getCurrentNode(){return this.node}getSVG(){return this.svg.svgObject}}class Wq{constructor(e,t,r={}){this.targetNode=e,this.parentElement=t,this.options={editable:!0,animationDuration:200,...r},this.popup=null,this.popupBackground=null,this.popupTextInput=null,this.penCanvas=null,this.penCanvasCleanup=null,this.currentMode="text",this.popupAnimationId=null,this.penButton=null,this.textButton=null,this.clearButton=null,this.submitButton=null,this.onValidateCallback=null,this.onClearCallback=null,this.popupWidth=400,this.buttonSize=18,this.margin=10,this.buttonSpacing=4,this.canvasMinWidth=100,this.canvasMinHeight=60,this.popupHeightMultiplier=2,this.targetNodeDefaultHeight=40,this.canvasTopOffset=this.margin,this.canvasLeftOffset=this.margin}show(e,t){return this.popup?this.hide().then(()=>this.show(e,t)):(this._createPopup(),this._positionPopup(e,t),this.parentElement.addChild(this.popup),this.popup.setOpacity(0),this._animateOpacity(0,1,this.options.animationDuration))}hide(){var a,o;if(!this.popup)return Promise.resolve();const e=this.popup.opacity,t=((o=(a=this.popupTextInput)==null?void 0:a.div)==null?void 0:o.style.opacity)||"1";this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.display="block"),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.opacity=t);const r=this.options.animationDuration||300,i=performance.now(),s=l=>{const u=l-i,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e*(1-h);this.popup&&this.popup.setOpacity(f),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.opacity=f),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.opacity=f),c<1?this.popupAnimationId=requestAnimationFrame(s):(this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.display="none",this.penCanvas.container.style.opacity="1"),this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="none"),this._cleanup())};return this.popupAnimationId=requestAnimationFrame(s),new Promise(l=>{setTimeout(l,r)})}toggle(e,t){return this.popup&&this.popup.visible?this.hide():this.show(e,t)}setValidationCallback(e){this.onValidateCallback=e}setClearCallback(e){this.onClearCallback=e}getValue(){if(this.transcribedText){const e=this.transcribedText;return this.transcribedText=null,e}return this.currentMode==="text"&&this.popupTextInput?this.popupTextInput.getText():""}setValue(e){this.currentMode==="text"&&this.popupTextInput&&this.popupTextInput.setText(e)}switchToMode(e){this.currentMode===e||!this.popup||(this.currentMode=e,e==="pen"?this._showPenMode():this._showTextMode(),this._updateButtonStates())}_createPopup(){var t;const e=(((t=this.targetNode)==null?void 0:t.height)||this.targetNodeDefaultHeight)*this.popupHeightMultiplier;this.popup=new qr,this.popupBackground=new yt,this.popupBackground.setWidthAndHeight(this.popupWidth,e),this.popupBackground.setFillColor("white"),this.popupBackground.setStrokeColor("black"),this.popupBackground.setStrokeWidth(2),this.popupBackground.setCornerRadius(8),this.popup.addChild(this.popupBackground),this._createButtons(this.popupWidth,e,this.buttonSize,this.margin,this.buttonSpacing),this._createTextInput(this.popupWidth,e,this.margin),this.currentMode="text",this._updateButtonStates()}_createButtons(e,t,r,i,s){const a=e-r-i,o=t-r*2-i-s;this.clearButton=new Xn,this.clearButton.setText("C"),this.clearButton.setWidthAndHeight(r,r),this.clearButton.setFillColor("#E65423"),this.clearButton.setFontColor("white"),this.clearButton.buttonText.setFontWeight("bold"),this.clearButton.setPosition(a,o),this.clearButton.setClickCallback(()=>{this.currentMode==="pen"&&this.penCanvas?this.penCanvas.clear():this.currentMode==="text"&&this.popupTextInput&&this.popupTextInput.setText(""),this.onClearCallback&&this.onClearCallback()}),this.popup.addChild(this.clearButton);const l=t-r-i;this.submitButton=new Xn,this.submitButton.setText("✓"),this.submitButton.setWidthAndHeight(r,r),this.submitButton.setFillColor("#2ECC71"),this.submitButton.setFontColor("white"),this.submitButton.buttonText.setFontWeight("bold"),this.submitButton.setPosition(a,l),this.submitButton.setClickCallback(()=>{this.currentMode==="pen"&&this.penCanvas?(this._setSubmitButtonLoading(!0),this._downloadCanvasAsBitmap()):this.onValidateCallback&&this.onValidateCallback()}),this.popup.addChild(this.submitButton);const u=i;this.textButton=new Xn,this.textButton.setText("T"),this.textButton.setWidthAndHeight(r,r),this.textButton.setFillColor("#28a745"),this.textButton.setFontColor("white"),this.textButton.buttonText.setFontWeight("bold"),this.textButton.setPosition(u,o),this.textButton.setClickCallback(()=>{this.switchToMode("text")}),this.popup.addChild(this.textButton),this.penButton=new Xn,this.penButton.setText(""),this.penButton.setWidthAndHeight(r,r),this.penButton.setFillColor("#007bff"),this.penButton.setPosition(u,l),this.penButton.setClickCallback(()=>this.switchToMode("pen"));const h="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(`<svg width="12" height="12" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
91
91
  <path d="M13.3658 4.68008C13.7041 4.34179 13.8943 3.88294 13.8943 3.40447C13.8944 2.926 13.7044 2.4671 13.3661 2.12872C13.0278 1.79035 12.5689 1.60022 12.0905 1.60016C11.612 1.6001 11.1531 1.79011 10.8147 2.1284L2.27329 10.6718C2.12469 10.8199 2.0148 11.0023 1.95329 11.203L1.10785 13.9882C1.09131 14.0436 1.09006 14.1024 1.10423 14.1584C1.11841 14.2144 1.14748 14.2655 1.18836 14.3063C1.22924 14.3471 1.28041 14.3761 1.33643 14.3902C1.39246 14.4043 1.45125 14.403 1.50657 14.3863L4.29249 13.5415C4.49292 13.4806 4.67532 13.3713 4.82369 13.2234L13.3658 4.68008Z" stroke="white" stroke-width="1.28" stroke-linecap="round" stroke-linejoin="round"/>
92
92
  <path d="M9.41443 3.52039L11.9744 6.08039" stroke="white" stroke-width="1.28" stroke-linecap="round" stroke-linejoin="round"/>
93
- </svg>`);this.penButton.addImage(h,12,12),this.popup.addChild(this.penButton)}_createTextInput(e,t,r){const i=this.buttonSize*2+r*2+this.margin,s=e-i-r*2,a=t-r*2,o=this.buttonSize+r*2,l=r;this.popupTextInput=new hE,this.popupTextInput.setWidthAndHeight(s,a),this.popupTextInput.setPosition(o,l),this.popupTextInput.setFillColor("transparent"),this.popupTextInput.setStrokeColor("transparent"),this.popupTextInput.setStrokeWidth(0),this.popupTextInput.setPlaceholderText(""),this.popupTextInput.div&&(this.popupTextInput.div.style.border="none",this.popupTextInput.div.style.outline="none",this.popupTextInput.div.style.background="transparent",this.popupTextInput.div.style.textAlign="center",this.popupTextInput.div.style.fontSize="48px",this.popupTextInput.div.style.fontFamily="Albert Sans, Arial, sans-serif",this.popupTextInput.div.style.resize="none",this.popupTextInput.div.style.width="100%",this.popupTextInput.div.style.height="100%",this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.alignItems="center",this.popupTextInput.div.style.justifyContent="center",this.popupTextInput.div.style.boxSizing="border-box"),this.popup.addChild(this.popupTextInput)}_createPenCanvas(){var f;const e=this.popupWidth,t=(((f=this.targetNode)==null?void 0:f.height)||this.targetNodeDefaultHeight)*this.popupHeightMultiplier,r=this.buttonSize,i=2*this.buttonSize+this.buttonSpacing,s=Math.max(e-r-i,this.canvasMinWidth),a=this.buttonSize*2+this.buttonSpacing+this.margin*2,o=t-a,l=Math.max(o,this.canvasMinHeight),u=r;let c,h=null;this.parentElement&&this.parentElement.element&&this.parentElement.element.namespaceURI==="http://www.w3.org/2000/svg"?(h=document.createElementNS("http://www.w3.org/2000/svg","foreignObject"),h.setAttribute("width",s),h.setAttribute("height",l),h.setAttribute("x",u),h.setAttribute("y",this.canvasTopOffset),c=document.createElement("div"),c.style.width=`${s}px`,c.style.height=`${l}px`,c.style.border="1px solid #ddd",c.style.borderRadius="4px",c.style.backgroundColor="#f8f9fa",c.style.margin="0",c.style.padding="0",h.appendChild(c)):(c=document.createElement("div"),c.style.width=`${s}px`,c.style.height=`${l}px`,c.style.position="absolute",c.style.left=`${u}px`,c.style.top=`${this.canvasTopOffset}px`,c.style.border="none",c.style.borderRadius="0px",c.style.backgroundColor="#ffffff",c.style.zIndex="1000",c.style.pointerEvents="auto",c.style.cursor="crosshair"),Promise.resolve().then(()=>p9).then(({createCanvas:d})=>{const p=s,m=l;this.penCanvas=d(c,{width:p-this.buttonSize,height:m,showToolbar:!1,showGrid:!1,backgroundColor:"#ffffff",strokeWidth:3,strokeColor:"#000000"}),this.penCanvas.container=c,this.penCanvas.foreignObject=h,this.penCanvas.toolManager.setActiveTool("pencil"),this.penCanvas.on("strokeStarted",y=>{}),this.penCanvas.on("strokeCompleted",y=>{}),c.addEventListener("pointerdown",y=>{}),c.addEventListener("click",y=>{}),this.penCanvasCleanup=()=>{this.penCanvas&&this.penCanvas.destroy(),h&&h.parentNode?h.parentNode.removeChild(h):c&&c.parentNode&&c.parentNode.removeChild(c),this._removeStepVisualizerListeners()},this._setupStepVisualizerListeners(),this.currentMode==="pen"&&this.popup&&this._addCanvasToParent(h||c)}).catch(console.error)}_showPenMode(){if(this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="none",this.popupTextInput.div.style.visibility="hidden"),!this.penCanvas)this._createPenCanvas();else{const e=this.penCanvas.foreignObject||this.penCanvas.container;e&&(e.style.display="block",e.style.opacity="1"),this._addCanvasToParent()}}_showTextMode(){if(this.penCanvas){const e=this.penCanvas.foreignObject||this.penCanvas.container;e&&e.parentNode&&e.parentNode.removeChild(e)}this.popupTextInput&&this.popup&&(this.popupTextInput.div&&(this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.visibility="visible",this.popupTextInput.div.style.opacity="1"),this.popup.addChild(this.popupTextInput),setTimeout(()=>{this.popupTextInput.div&&this.popupTextInput.div.focus()},100))}_addCanvasToParent(e=null){if(!e&&this.penCanvas&&this.penCanvas.container){this.penCanvas.container.parentNode&&this.penCanvas.container.parentNode.removeChild(this.penCanvas.container),document.body.appendChild(this.penCanvas.container),this._updateCanvasPosition();return}if(this.penCanvas&&this.popup&&this.parentElement){const t=this.popup.xpos||0,r=this.popup.ypos||0;if(e)if(e.namespaceURI==="http://www.w3.org/2000/svg")e.setAttribute("x",t+this.canvasLeftOffset),e.setAttribute("y",r+this.canvasTopOffset),this.parentElement.element?this.parentElement.element.appendChild(e):this.parentElement.appendChild&&this.parentElement.appendChild(e);else{const i=this.popup.svgObject?this.popup.svgObject.getBoundingClientRect():null;if(i){const s=this.buttonSize+this.margin*2,a=this.buttonSize*2+this.margin*2+this.margin,o=i.left+s,l=i.top+this.margin;e.style.left=`${o}px`,e.style.top=`${l}px`,e.style.position="fixed",e.style.zIndex="9999",e.style.pointerEvents="auto";const u=i.width-s-a;e.style.width=`${u}px`,this.penCanvas.popupRect=i,this._setupResizeObserver()}else{const s=(window.innerWidth-280)/2,a=(window.innerHeight-60)/2;e.style.left=`${s}px`,e.style.top=`${a}px`,e.style.position="fixed",e.style.zIndex="9999",e.style.pointerEvents="auto"}document.body.appendChild(e)}}}_updateButtonStates(){!this.penButton||!this.textButton||(this.currentMode==="pen"?(this.penButton.setFillColor("#2980B9"),this.textButton.setFillColor("#9B59B6")):(this.penButton.setFillColor("#3498DB"),this.textButton.setFillColor("#8E44AD")))}_positionPopup(e,t){this.popup&&this.popup.setPosition(e,t)}_animateOpacity(e,t,r){return new Promise(i=>{if(!this.popup){i();return}this.popupAnimationId&&cancelAnimationFrame(this.popupAnimationId);const s=performance.now(),a=t-e,o=l=>{const u=l-s,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e+a*h;this.popup.setOpacity(f),this.penCanvas&&this.penCanvas.container&&this.currentMode==="pen"&&(this.penCanvas.container.style.opacity=f),c<1?this.popupAnimationId=requestAnimationFrame(o):(this.popupAnimationId=null,this.penCanvas&&this.penCanvas.container&&this.currentMode==="pen"&&(this.penCanvas.container.style.opacity="1"),i())};this.popupAnimationId=requestAnimationFrame(o)})}flashValidation(e){if(!this.popupBackground)return;const t=e?"#E8F5E8":"#FFE6E6";this._flashAllElements(t)}_flashAllElements(e){this.popupBackground.setFillColor(e),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.backgroundColor=e),this.penCanvas&&this.penCanvas.svg&&(this.penCanvas.svg.style.backgroundColor=e),setTimeout(()=>{this.popupBackground.setFillColor("white"),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.backgroundColor="white"),this.penCanvas&&this.penCanvas.svg&&(this.penCanvas.svg.style.backgroundColor="white")},300)}areExpressionsEquivalent(e,t){if(!window.math||!window.math.simplify||!window.math.parse)return!1;try{const r=e.trim(),i=t.trim(),s=window.math.simplify(r),a=window.math.simplify(i);if(s.equals(a))return!0;const o=u=>{const c=window.math.parse(u),h=new Set;return c.traverse(f=>{f.isSymbolNode&&h.add(f.name)}),Array.from(h)},l=Array.from(new Set([...o(r),...o(i)]));if(l.length===0)return s.evaluate()===a.evaluate();for(let u=0;u<100;u++){const c={};for(const d of l)c[d]=Math.floor(Math.random()*1e3+1);const h=s.evaluate(c),f=a.evaluate(c);if(Math.abs(h-f)>1e-9)return!1}return!0}catch{return!1}}_cleanup(){this.popup&&this.parentElement&&this.parentElement.removeChild(this.popup),this.penCanvas&&(this.penCanvas.foreignObject&&this.penCanvas.foreignObject.parentNode&&this.penCanvas.foreignObject.parentNode.removeChild(this.penCanvas.foreignObject),this.penCanvas.container&&this.penCanvas.container.parentNode&&this.penCanvas.container.parentNode.removeChild(this.penCanvas.container)),this.penCanvasCleanup&&(this.penCanvasCleanup(),this.penCanvasCleanup=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this._removeStepVisualizerListeners(),this.popupAnimationId&&(cancelAnimationFrame(this.popupAnimationId),this.popupAnimationId=null),this.popup=null,this.popupBackground=null,this.popupTextInput=null,this.penCanvas=null,this.penButton=null,this.textButton=null,this.clearButton=null,this.submitButton=null}destroy(){return this.hide()}debugCanvasPosition(){if(this.penCanvas&&this.penCanvas.container){const e=this.penCanvas.container;e.style.border="3px solid #00ff00",setTimeout(()=>{e.style.border="2px solid #ff0000"},1e3)}}centerCanvas(){if(this.penCanvas&&this.penCanvas.container){const e=this.penCanvas.container,t=(window.innerWidth-280)/2,r=(window.innerHeight-60)/2;e.style.left=`${t}px`,e.style.top=`${r}px`}}_setupResizeObserver(){!this.penCanvas||!this.popup||!this.popup.svgObject||(this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this._updateCanvasPosition()}),this.resizeObserver.observe(this.popup.svgObject),this.parentElement&&this.parentElement.svgObject&&this.resizeObserver.observe(this.parentElement.svgObject),this.resizeObserver.observe(document.body))}_setupStepVisualizerListeners(){this.penCanvas&&(this._stepVisualizerUpdateHandler=()=>{console.log("[Step Visualizer Debug] Layout change detected, updating canvas position"),setTimeout(()=>this._updateCanvasPosition(),50)},document.addEventListener("click",this._stepVisualizerUpdateHandler),window.addEventListener("resize",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&this.parentElement.element.addEventListener("stepVisualizerChanged",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&(this._mutationObserver=new MutationObserver(e=>{let t=!1;for(const r of e){if(r.type==="attributes"&&(r.attributeName==="style"||r.attributeName==="class"||r.attributeName==="transform")){console.log("[Step Visualizer Debug] Mutation detected:",r.attributeName,r.target),t=!0;break}if(r.type==="childList"&&(r.addedNodes.length>0||r.removedNodes.length>0)){console.log("[Step Visualizer Debug] Child list mutation detected"),t=!0;break}}t&&setTimeout(()=>this._updateCanvasPosition(),10)}),this._mutationObserver.observe(this.parentElement.element,{childList:!0,attributes:!0,subtree:!0,attributeFilter:["style","class","transform","viewBox"]})))}_removeStepVisualizerListeners(){this._stepVisualizerUpdateHandler&&(document.removeEventListener("click",this._stepVisualizerUpdateHandler),window.removeEventListener("resize",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&this.parentElement.element.removeEventListener("stepVisualizerChanged",this._stepVisualizerUpdateHandler),this._stepVisualizerUpdateHandler=null),this._mutationObserver&&(this._mutationObserver.disconnect(),this._mutationObserver=null)}_updateCanvasPosition(){var r,i;if(!this.penCanvas||!this.penCanvas.container||!this.popup)return;const e=this.penCanvas.container,t=this.popup.svgObject?this.popup.svgObject.getBoundingClientRect():null;if(console.log("[Canvas Position Debug] Update triggered:",{hasCanvas:!!this.penCanvas,hasContainer:!!e,strokeCount:((i=(r=this.penCanvas)==null?void 0:r.strokes)==null?void 0:i.size)||0,popupRect:t?`${t.width}x${t.height}`:"null"}),t&&t.width>0&&t.height>0){const s=this.buttonSize+this.margin*2,a=this.buttonSize*2+this.margin*2+this.margin,o=Math.max(t.width-s-a,this.canvasMinWidth),l=Math.max(t.height-this.margin*2-this.buttonSize*2-this.buttonSpacing,this.canvasMinHeight),u=t.left+s,c=t.top+this.margin,h=t.width-s-a,f=t.height-this.margin*2-this.buttonSize*2-this.buttonSpacing,d=Math.min(Math.max(o,this.canvasMinWidth),h),p=Math.min(Math.max(l,this.canvasMinHeight),f);console.log("[Canvas Position Debug] Moving canvas:",{from:`${e.style.left}, ${e.style.top}`,to:`${u}px, ${c}px`,size:`${d}x${p}`}),e.style.left=`${u}px`,e.style.top=`${c}px`,e.style.width=`${d}px`,e.style.height=`${p}px`,setTimeout(()=>{var m,y;console.log("[Canvas Position Debug] After move stroke count:",((y=(m=this.penCanvas)==null?void 0:m.strokes)==null?void 0:y.size)||0)},50)}}async _downloadCanvasAsBitmap(){if(this.penCanvas)try{const e=this.penCanvas.svg;if(!e)return;const t=document.createElement("canvas"),r=t.getContext("2d"),i=e.getBoundingClientRect();t.width=i.width,t.height=i.height;const s=new XMLSerializer().serializeToString(e),a=new Blob([s],{type:"image/svg+xml;charset=utf-8"}),o=URL.createObjectURL(a),l=new Image;l.onload=async()=>{r.drawImage(l,0,0),t.toBlob(async u=>{URL.revokeObjectURL(o),await this._transcribeCanvas(u)},"image/png")},l.src=o}catch{}}async _transcribeCanvas(e){try{const{omdTranscriptionService:t}=await Promise.resolve().then(()=>Gq),r=new t({defaultProvider:"gemini"});if(!r.isAvailable())return;const i=await r.transcribeWithFallback(e,{prompt:"Transcribe this handwritten mathematical expression. Return ONLY the pure mathematical expression with no formatting, no LaTeX, no dollar signs, no explanations. Use ^ for powers (e.g., 3^2), use / for fractions (e.g., (2x+1)/(x-3)), use * for multiplication, use + and - for addition/subtraction. Return only the expression."});i.text?(this._setSubmitButtonLoading(!1),this.flashValidation(!0),this.transcribedText=i.text,this.onValidateCallback&&this.onValidateCallback()):this._setSubmitButtonLoading(!1)}catch{this.flashValidation(!1),this._setSubmitButtonLoading(!1)}}_setSubmitButtonLoading(e){this.submitButton&&(e?this._startBlinkingAnimation():(this._stopBlinkingAnimation(),this.submitButton.setText("✓"),this.submitButton.setFillColor("#2ECC71"),this.submitButton.setFontColor("white")))}_startBlinkingAnimation(){if(!this.submitButton)return;let e=!0;const t=()=>{e?this.submitButton.setFillColor("#FFA500"):this.submitButton.setFillColor("#2ECC71"),e=!e,this.blinkAnimationId=setTimeout(t,300)};t()}_stopBlinkingAnimation(){this.blinkAnimationId&&(clearTimeout(this.blinkAnimationId),this.blinkAnimationId=null)}repositionCanvasRelativeToPopup(){this._updateCanvasPosition()}}class ey extends Oe{constructor(e={}){super(),this.options={fillColor:"white",strokeColor:"black",strokeWidth:2,opacity:1,padding:0,cornerRadius:4,overlayType:"rectangle",animated:!1,animationDuration:300,text:"",editable:!1,...e},this.targetNode=null,this.overlayElement=null,this.textElement=null,this.isVisible=!1,this.animationId=null,this.clickLayer=null,this.savedHandlers=[],this.omdPopup=null,this._createOverlayElement()}_createOverlayElement(){switch(this.options.overlayType){case"rectangle":this.overlayElement=new yt,this.options.cornerRadius>0&&this.overlayElement.setCornerRadius(this.options.cornerRadius);break;case"ellipse":this.overlayElement=new jsvgEllipse;break;case"text":this._createTextOverlay();return;default:this.overlayElement=new yt}this.overlayElement.setFillColor(this.options.fillColor),this.overlayElement.setStrokeColor(this.options.strokeColor),this.overlayElement.setStrokeWidth(this.options.strokeWidth),this.overlayElement.setOpacity(this.options.opacity),this.addChild(this.overlayElement),this.setOpacity(0)}_createTextOverlay(){this.overlayElement=new yt,this.options.cornerRadius>0&&this.overlayElement.setCornerRadius(this.options.cornerRadius),this.overlayElement.setFillColor(this.options.fillColor),this.overlayElement.setStrokeColor(this.options.strokeColor),this.overlayElement.setStrokeWidth(this.options.strokeWidth),this.overlayElement.setOpacity(this.options.opacity),this.addChild(this.overlayElement),this.options.editable&&(this.clickLayer=new yt,this.clickLayer.setWidthAndHeight(this.overlayElement.width,this.overlayElement.height),this.clickLayer.setPosition(0,0),this.clickLayer.setFillColor("transparent"),this.clickLayer.setStrokeColor("transparent"),this.addChild(this.clickLayer),this.clickLayer.setClickCallback(()=>{this.togglePopup()})),this.options.editable?this.textElement=null:(this.textElement=new jsvgTextLine,this.textElement.setText(this.options.text),this.textElement.setTextAnchor("middle"),this.textElement.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(this.textElement)),this.setOpacity(0)}coverNode(e){if(!e)return console.warn("omdNodeOverlay: Cannot cover null or undefined node"),this;this.targetNode=e,this.savedHandlers=[];let t=this.targetNode;for(;t;)t.svgObject&&typeof t.svgObject.onmouseenter=="function"&&(this.savedHandlers.push({element:t.svgObject,onmouseenter:t.svgObject.onmouseenter,onmouseleave:t.svgObject.onmouseleave}),t.svgObject.onmouseenter=null,t.svgObject.onmouseleave=null),t=t.parent;return this.targetNode.parent&&e.parent.addChild(this),this._updateOverlayPosition(),this}setCoverArea(e,t,r,i,s=!0){s&&(this.targetNode=null);const a=this.options.padding||0,o=e-a,l=t-a,u=r+a*2,c=i+a*2;return this.setPosition(o,l),this.overlayElement.setWidthAndHeight(u,c),this.clickLayer&&this.clickLayer.setWidthAndHeight(u,c),this.options.overlayType==="text"&&this.textElement&&this.textElement.setPosition(u/2,c/2),this}_updateOverlayPosition(){if(!this.targetNode)return;let e;this.parent===this.targetNode.parent?e={x:this.targetNode.xpos||this.targetNode.x||0,y:this.targetNode.ypos||this.targetNode.y||0}:e=this._getGlobalPosition(this.targetNode);let t=this.targetNode.width||0,r=this.targetNode.height||0;this.targetNode.backRect&&(t=this.targetNode.backRect.width||t,r=this.targetNode.backRect.height||r),this.setCoverArea(e.x,e.y,t,r,!1)}_matchNodeProperties(){if(this.targetNode){if(this.options.overlayType==="rectangle"&&this.overlayElement.setCornerRadius){let e=0;if(this.targetNode.backRect&&this.targetNode.backRect.cornerRadius!==void 0)e=this.targetNode.backRect.cornerRadius;else if(this.targetNode.svgObject){const t=this.targetNode.svgObject.getAttribute("rx"),r=this.targetNode.svgObject.getAttribute("ry");e=parseFloat(t||r||0)}else if(this.targetNode.svgObject&&this.targetNode.svgObject.tagName==="rect"){const t=this.targetNode.svgObject.getAttribute("rx"),r=this.targetNode.svgObject.getAttribute("ry");e=parseFloat(t||r||0)}e>0&&(this.overlayElement.setCornerRadius(e),this.options.cornerRadius=e)}if(this.options.overlayType==="text"&&this.textElement&&this._matchFontProperties(),this.targetNode.svgObject&&!this.options.preserveStrokeWidth){const e=this.targetNode.svgObject.getAttribute("stroke-width");if(e){const t=parseFloat(e);t>0&&this.overlayElement.setStrokeWidth(t)}}}}_matchFontProperties(){if(!this.targetNode||!this.textElement)return;let e=32;if(this.targetNode.getFontSize&&typeof this.targetNode.getFontSize=="function"?e=this.targetNode.getFontSize():this.targetNode.fontSize&&(e=this.targetNode.fontSize),this.textElement.setFontSize(e),this.targetNode.textElement){const t=this.targetNode.textElement.svgObject;if(t){const r=t.style.fontFamily||"Arial, Helvetica, sans-serif";this.textElement.setFontFamily(r);const i=t.style.fill||t.getAttribute("fill")||"black";this.textElement.setFontColor?this.textElement.setFontColor(i):this.textElement.div&&(this.textElement.div.style.color=i);const s=t.style.fontWeight;s&&this.textElement.setFontWeight?this.textElement.setFontWeight(s):s&&this.textElement.div&&(this.textElement.div.style.fontWeight=s)}}}_getGlobalPosition(e){if(e.svgObject&&e.svgObject.getCTM)try{const s=e.svgObject.getCTM();if(s)return{x:s.e,y:s.f}}catch{}let t=e.xpos||e.x||0,r=e.ypos||e.y||0,i=e.parent;for(;i&&i.xpos!==void 0;)t+=i.xpos||i.x||0,r+=i.ypos||i.y||0,i=i.parent;return{x:t,y:r}}_createPopup(){!this.options.editable||this.omdPopup||(this.omdPopup=new Wq(this.targetNode,this.parent,{animationDuration:this.options.animationDuration}),this.omdPopup.setValue(this.options.text),this.omdPopup.setValidationCallback(()=>{const e=this.omdPopup.getValue();if(this.targetNode){const t=this.targetNode.text||this.targetNode.toString()||"";this.omdPopup.areExpressionsEquivalent(e.trim(),t.trim())?(this.omdPopup.flashValidation(!0),setTimeout(()=>{this.destroy()},500)):this.omdPopup.flashValidation(!1)}}),this.omdPopup.setClearCallback(()=>{this.omdPopup.setValue("")}))}togglePopup(){if(!this.options.editable)return Promise.resolve();this.omdPopup||this._createPopup();const e=this.xpos||this.x||0,t=this.ypos||this.y||0,r=this.overlayElement.width||this.targetNode.width||100,i=this.overlayElement.height||this.targetNode.height||40,a=e+r/2-400/2,o=t+i+10;return this.omdPopup.toggle(a,o)}_hidePopup(){this.omdPopup&&(this.omdPopup.destroy(),this.omdPopup=null)}show(e=this.options.animated){return new Promise(t=>{if(this.isVisible){t();return}this.isVisible=!0,e?this._animateOpacity(0,this.options.opacity,this.options.animationDuration).then(t):(this.setOpacity(this.options.opacity),t())})}_animateOpacity(e,t,r){return new Promise(i=>{this.animationId&&cancelAnimationFrame(this.animationId);const s=performance.now(),a=t-e,o=l=>{const u=l-s,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e+a*h;this.setOpacity(f),c<1?this.animationId=requestAnimationFrame(o):(this.animationId=null,i())};this.animationId=requestAnimationFrame(o)})}destroy(e=this.options.animated){return new Promise(t=>{e&&this.isVisible?this._animateOpacity(this.options.opacity,0,this.options.animationDuration).then(()=>{this._performDestroy(),t()}):(this._performDestroy(),t())})}_performDestroy(){this.animationId&&cancelAnimationFrame(this.animationId),this.savedHandlers.forEach(({element:e,onmouseenter:t,onmouseleave:r})=>{e&&(e.onmouseenter=t,e.onmouseleave=r)}),this._hidePopup(),this.targetNode=null,this.isVisible=!1,this.parent&&this.parent.removeChild(this)}getIsVisible(){return this.isVisible}getTargetNode(){return this.targetNode}setText(e){return this.textElement&&(this.textElement.setText(e),this.options.text=e),this}getText(){return this.textElement?this.textElement.getText():this.options.text}}class jq{static createHidingOverlay(e=!1,t=null){const r={fillColor:"white",strokeColor:"black",strokeWidth:2,padding:1,animated:!0};return e&&(r.overlayType="text",r.text=t||"",r.editable=!0,r.fillColor="white",r.strokeColor="black",r.strokeWidth=2),new ey(r)}static createHighlightOverlay(e="#ffff00"){return new ey({fillColor:"none",strokeColor:e,strokeWidth:3,padding:2,cornerRadius:4,animated:!0})}}class wE{constructor(e={}){this.options={endpoint:e.endpoint||this._getDefaultEndpoint(),defaultProvider:e.defaultProvider||"openai",defaultModel:e.defaultModel||"gpt-4o",...e}}_getDefaultEndpoint(){return"/.netlify/functions/transcribe"}async _blobToBase64(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>{const s=i.result.split(",")[1];t(s)},i.onerror=r,i.readAsDataURL(e)})}async transcribe(e,t={}){try{const r=await this._blobToBase64(e),i=await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({imageBase64:r,prompt:t.prompt||"Please transcribe the handwritten mathematical expression in this image. Return only the mathematical expression in pure format (no LaTeX, no dollar signs). For powers use ^, for fractions use /, for square roots use sqrt().",model:t.model||this.options.defaultModel,provider:t.provider||this.options.defaultProvider})});if(!i.ok)throw new Error(`Transcription API error: ${i.status} ${i.statusText}`);const s=await i.json();return{text:(s.text||"").trim(),provider:s.provider||this.options.defaultProvider,model:s.model||t.model||this.options.defaultModel,confidence:s.confidence||1}}catch(r){throw console.error("Transcription error:",r),r}}async transcribeWithFallback(e,t={}){return this.transcribe(e,t)}isAvailable(){return!0}getAvailableProviders(){return["openai"]}isProviderAvailable(e){return e==="openai"}}const Gq=Object.freeze(Object.defineProperty({__proto__:null,omdTranscriptionService:wE},Symbol.toStringTag,{value:"Module"}));class ty extends Oe{constructor(){super(),this.type="omdTable",this.equation="",this.data=[],this.headers=["x","y"],this.xMin=-5,this.xMax=5,this.stepSize=1,this.title="",this.fontSize=14,this.headerFontSize=16,this.fontFamily="Albert Sans",this.headerFontFamily="Albert Sans",this.cellHeight=35,this.headerHeight=40,this.minCellWidth=80,this.maxCellWidth=300,this.padding=10,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=15,this.backgroundOpacity=1,this.showBackground=!0,this.alternatingRowColors=[Fe.mediumGray,Fe.lightGray],this.headerBackgroundColor=Fe.lightGray,this.cellBackgroundColor="white",this.evenRowColor="rgba(255,255,255,0.5)",this.oddRowColor="transparent",this.alternatingRowOpacity=1,this.updateLayout()}estimateTitleWidth(){if(!this.title||this.title.length===0)return 0;const e=this.headerFontSize+2,t=40,r=200,i=Math.round(this.title.length*(e*.6))+t;return Math.max(r,i)}loadFromJSON(e){typeof e.equation<"u"&&(this.equation=e.equation),typeof e.data<"u"&&(this.data=e.data),typeof e.headers<"u"&&(this.headers=e.headers),typeof e.xMin<"u"&&(this.xMin=e.xMin),typeof e.xMax<"u"&&(this.xMax=e.xMax),typeof e.stepSize<"u"&&(this.stepSize=e.stepSize),typeof e.title<"u"&&(this.title=e.title),typeof e.fontSize<"u"&&(this.fontSize=e.fontSize),typeof e.headerFontSize<"u"&&(this.headerFontSize=e.headerFontSize),typeof e.fontFamily<"u"&&(this.fontFamily=e.fontFamily),typeof e.headerFontFamily<"u"&&(this.headerFontFamily=e.headerFontFamily),typeof e.cellHeight<"u"&&(this.cellHeight=e.cellHeight),typeof e.headerHeight<"u"&&(this.headerHeight=e.headerHeight),typeof e.minCellWidth<"u"&&(this.minCellWidth=e.minCellWidth),typeof e.maxCellWidth<"u"&&(this.maxCellWidth=e.maxCellWidth),typeof e.padding<"u"&&(this.padding=e.padding),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.backgroundCornerRadius<"u"&&(this.backgroundCornerRadius=e.backgroundCornerRadius),typeof e.backgroundOpacity<"u"&&(this.backgroundOpacity=e.backgroundOpacity),typeof e.showBackground<"u"&&(this.showBackground=e.showBackground),typeof e.alternatingRowColors<"u"&&(this.alternatingRowColors=e.alternatingRowColors,console.log("LoadFromJSON - Setting alternatingRowColors to:",this.alternatingRowColors)),typeof e.evenRowColor<"u"&&(this.evenRowColor=e.evenRowColor),typeof e.oddRowColor<"u"&&(this.oddRowColor=e.oddRowColor),typeof e.alternatingRowOpacity<"u"&&(this.alternatingRowOpacity=e.alternatingRowOpacity),this.updateLayout()}setEquation(e){this.equation=e,this.updateLayout()}setData(e,t){this.data=e,t&&(this.headers=t),this.updateLayout()}calculateOptimalCellWidth(e){let t=(this.headers[e]??"").toString().length;for(let i of this.data){const s=i[e];s!=null&&(t=Math.max(t,s.toString().length))}const r=Math.max(t*8+this.padding*2,this.minCellWidth);return Math.min(r,this.maxCellWidth)}generateDataFromEquation(){if(!this.equation||this.equation.trim().length===0)return;this.data=[],this.headers=["x","y"];let e=this.equation;e=e.replace(/^\s*y\s*=\s*/i,"").replace(/\s*=\s*y\s*$/i,"");try{if(typeof math<"u"&&math.compile){const t=math.compile(e);for(let r=this.xMin;r<=this.xMax;r+=this.stepSize)try{let i=t.evaluate({x:r});i=Math.round(i*100)/100,this.data.push([r,i])}catch{}return}}catch(t){console.warn("math.js evaluation failed, falling back to simple parser:",t)}e=e.replace(/(\d)([a-z])/gi,"$1*$2").replace(/([a-z])(\d)/gi,"$1*$2").replace(/\^/g,"**");try{const t=new Function("x",`return ${e};`);for(let r=this.xMin;r<=this.xMax;r+=this.stepSize){let i=t(r);i=Math.round(i*100)/100,this.data.push([r,i])}}catch(t){console.error("Error generating table data from equation:",t)}}updateLayout(){console.log("updateLayout called - alternatingRowColors:",this.alternatingRowColors),console.log("alternatingRowColors type:",typeof this.alternatingRowColors),console.log("alternatingRowColors isArray:",Array.isArray(this.alternatingRowColors)),this.removeAllChildren(),this.equation&&this.equation.length>0&&this.generateDataFromEquation();const e=this.headers.length,t=this.data.length;let r=[],i=0;for(let S=0;S<e;S++){const g=this.calculateOptimalCellWidth(S);r.push(g),i+=g}this.width=i;const s=this.title&&this.title.length>0?30:0,a=this.headerHeight+t*this.cellHeight,o=s+a;this.height=o;const l=this.estimateTitleWidth(),u=Math.max(this.width,l),c=Math.max(0,(u-this.width)/2);let h;if(this.backgroundCornerRadius>0){const S=new Ho(this.width,a,this.backgroundCornerRadius);if(S.setPosition(c,s),this.addChild(S),h=S,this.showBackground){const g=new yt;g.setWidthAndHeight(this.width,a),g.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&g.setOpacity(this.backgroundOpacity),g.setStrokeWidth(0),g.setPosition(0,0),h.addChild(g)}}else{if(this.showBackground){const S=new yt;S.setWidthAndHeight(this.width,a),S.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&S.setOpacity(this.backgroundOpacity),S.setStrokeWidth(0),S.setPosition(c,s),this.addChild(S)}h=this}this.equation&&this.equation.length>0&&this.generateDataFromEquation();let f=0;if(this.title&&this.title.length>0){var d=new Bt;d.setWidthAndHeight(l,25),d.setText(this.title),d.setFontFamily(this.headerFontFamily),d.setFontColor("black"),d.setFontSize(this.headerFontSize+2),d.setAlignment("center"),d.setVerticalCentering();const S=Math.max(0,(u-l)/2);d.setPosition(S,f),d.setFontWeight(600),this.addChild(d),f+=30}let p=0;const m=0;if(this.alternatingRowColors&&Array.isArray(this.alternatingRowColors)&&this.alternatingRowColors.length>0){console.log("Creating header background with color:",this.alternatingRowColors[0]);const S=new yt;S.setWidthAndHeight(this.width,this.headerHeight),S.setFillColor(this.alternatingRowColors[0]),S.setCornerRadius(0),S.setStrokeWidth(0),S.setPosition(0,m),h.addChild(S)}else console.log("NOT creating header background - alternatingRowColors:",this.alternatingRowColors);for(let S=0;S<e;S++){const g=r[S];if(!this.alternatingRowColors||!Array.isArray(this.alternatingRowColors)||this.alternatingRowColors.length===0){var y=new yt;y.setWidthAndHeight(g,this.headerHeight),y.setFillColor(this.headerBackgroundColor||Fe.lightGray),y.setCornerRadius(0),y.setStrokeWidth(0),y.setPosition(p,m),h.addChild(y)}const b=this.createHeaderTextBox(g,this.headerHeight,this.headers[S]||`Col ${S+1}`);b.setPosition(p,m),h.addChild(b),p+=g}f+=this.headerHeight;for(let S=0;S<t;S++){const g=this.data[S];let b=0;const w=this.headerHeight+S*this.cellHeight;if(this.alternatingRowColors&&Array.isArray(this.alternatingRowColors)&&this.alternatingRowColors.length>0){const x=(S+1)%this.alternatingRowColors.length,N=this.alternatingRowColors[x];console.log(`Creating row ${S} background with color:`,N,"at position:",0,w);var v=new yt;v.setWidthAndHeight(this.width,this.cellHeight),v.setFillColor(N),this.backgroundOpacity<1&&v.setOpacity(this.backgroundOpacity),v.setCornerRadius(0),v.setStrokeWidth(0),v.setPosition(0,w),h.addChild(v)}else console.log(`Row ${S}: No alternating colors - alternatingRowColors:`,this.alternatingRowColors);for(let x=0;x<e;x++){const N=r[x],D=this.createBodyTextBox(N,this.cellHeight,""),C=g[x];D.setText((C??"").toString()),D.setPosition(b,w),h.addChild(D),b+=N}f+=this.cellHeight}if(e>1){let S=0;for(let g=0;g<e-1;g++){S+=r[g];const b=new yt;b.setWidthAndHeight(1,Math.max(0,a-1)),b.setFillColor("black"),b.setCornerRadius(0),b.setOpacity(.5),b.setStrokeWidth(0),b.setPosition(S,0),h.addChild(b)}}this.setWidthAndHeight(u,o),this.svgObject.setAttribute("viewBox",`0 0 ${u} ${o}`)}createHeaderTextBox(e,t,r){const i=new Bt;return i.setWidthAndHeight(e,t),i.setText(r),i.setFontFamily(this.headerFontFamily),i.setFontColor("black"),i.setFontSize(this.headerFontSize),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(600),i}createBodyTextBox(e,t,r){const i=new Bt;return i.setWidthAndHeight(e,t),i.setText(r),i.setFontFamily(this.fontFamily),i.setFontColor("black"),i.setFontSize(this.fontSize),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(400),i}addRow(e){this.data.push(e),this.updateLayout()}setHeaders(e){this.headers=e,this.updateLayout()}setFont(e,t){this.fontFamily=e,t?this.headerFontFamily=t:this.headerFontFamily=e,this.updateLayout()}clearData(){this.data=[],this.updateLayout()}setBackgroundColor(e){this.backgroundColor=e,this.updateLayout()}setBackgroundCornerRadius(e){this.backgroundCornerRadius=e,this.updateLayout()}setBackgroundOpacity(e){this.backgroundOpacity=Math.max(0,Math.min(1,e)),this.updateLayout()}setShowBackground(e){this.showBackground=e,this.updateLayout()}setBackgroundStyle(e={}){e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.cornerRadius!==void 0&&(this.backgroundCornerRadius=e.cornerRadius),e.opacity!==void 0&&(this.backgroundOpacity=Math.max(0,Math.min(1,e.opacity))),e.show!==void 0&&(this.showBackground=e.show),this.updateLayout()}setAlternatingRowColors(e){console.log("setAlternatingRowColors called with:",e),this.alternatingRowColors=e,console.log("alternatingRowColors set to:",this.alternatingRowColors),this.updateLayout()}setHeaderBackgroundColor(e){this.headerBackgroundColor=e,this.updateLayout()}setCellBackgroundColor(e){this.cellBackgroundColor=e,this.updateLayout()}}class Oa extends Oe{constructor(){super(),this.type="omdBalanceHanger",this.leftValues=[],this.rightValues=[],this.tilt="none",this.fontFamily="Albert Sans",this.fontSize=18,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=5,this.backgroundOpacity=1,this.showBackground=!0,this.updateLayout()}loadFromJSON(e){typeof e.leftValues<"u"&&(this.leftValues=e.leftValues),typeof e.rightValues<"u"&&(this.rightValues=e.rightValues),typeof e.tilt<"u"&&(this.tilt=e.tilt),typeof e.fontFamily<"u"&&(this.fontFamily=e.fontFamily),typeof e.fontSize<"u"&&(this.fontSize=e.fontSize),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.backgroundCornerRadius<"u"&&(this.backgroundCornerRadius=e.backgroundCornerRadius),typeof e.backgroundOpacity<"u"&&(this.backgroundOpacity=e.backgroundOpacity),typeof e.showBackground<"u"&&(this.showBackground=e.showBackground),this.updateLayout()}setLeftAndRightValues(e,t){this.leftValues=e,this.rightValues=t}updateLayout(){this.removeAllChildren();var e=Math.max(this.leftValues.length,this.rightValues.length),t=50,r=0;this.tilt=="left"&&(r=-10),this.tilt=="right"&&(r=10);var i=20,s=e>0?(e-1)*40+30:0,a=t*2,o=Math.abs(r)+i+s;this.line=new Ut,this.line.setStrokeColor("black"),this.line.setStrokeWidth(1),this.line.setEndpoints(-t,r,t,-r),this.addChild(this.line);var l=new Ut;l.setStrokeColor("black"),l.setStrokeWidth(1),l.setEndpoints(-t,r,-t,r+i+40*(this.leftValues.length-1)),this.addChild(l);var u=new Ut;u.setStrokeColor("black"),u.setStrokeWidth(1),u.setEndpoints(t,-r,t,-r+i+40*(this.rightValues.length-1)),this.addChild(u);var c=new Tr;c.setWidthAndHeight(10,10),c.setFillColor("black"),c.setPosition(0,0),this.addChild(c),this.makeValueStack(this.leftValues,-t,r+i),this.makeValueStack(this.rightValues,t,-r+i);const h=40,f=Math.max(300,a+h),d=Math.max(200,o+h);this.setWidthAndHeight(f,d),this.svgObject.setAttribute("viewBox",`${-f/2} ${-d/2} ${f} ${d}`)}makeValueStack(e,t,r){for(var i=0;i<e.length;i++){var s=e[i],a=30;typeof s=="string"?a=20+s.length*10:a=30;var o;typeof s=="string"?(o=new Tr,o.setWidthAndHeight(a,30),o.setPosition(t-a/2+a/2,r+i*40+15)):(o=new yt,o.setWidthAndHeight(a,30),o.setCornerRadius(5),o.setPosition(t-a/2,r+i*40)),this.showBackground?(o.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&o.setOpacity(this.backgroundOpacity)):o.setFillColor("transparent"),this.backgroundCornerRadius>0&&o.setCornerRadius&&o.setCornerRadius(this.backgroundCornerRadius),this.addChild(o);var l=new Bt;l.setWidthAndHeight(a,30),l.setText(this.name),l.setFontFamily(this.fontFamily),l.setFontColor("black"),l.setFontSize(this.fontSize),l.setAlignment("center"),l.setVerticalCentering(),l.setText(s),l.setPosition(t-a/2,r+i*40),this.addChild(l)}}setFont(e,t){this.fontFamily=e,t&&(this.fontSize=t),this.updateLayout()}}const Xq=10,Yq=38;function ry(n){return n?Yq:Xq}function Jq(n){const e=Array.isArray(n==null?void 0:n.points)?n.points:[];if(e.length<=1)return e.slice();const t=e[0],r=e[e.length-1];return t.x===r.x&&t.y===r.y?e.slice(0,-1):e.slice()}function Zq(n){if(!n.length)return{x:0,y:0};let e=0,t=0;for(const r of n)e+=r.x,t+=r.y;return{x:e/n.length,y:t/n.length}}class ks extends Oe{constructor(){super(),this.type="omdRightTriangle",this.horizontalLeg=5,this.verticalLeg=10,this.angleA=0,this.angleB=0,this.hypotenuse=0,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){if(typeof e.horizontalLeg<"u"&&(this.horizontalLeg=e.horizontalLeg),typeof e.verticalLeg<"u"&&(this.verticalLeg=e.verticalLeg),typeof e.angleA<"u"&&(this.angleA=e.angleA),typeof e.angleB<"u"&&(this.angleB=e.angleB),typeof e.hypotenuse<"u"&&(this.hypotenuse=e.hypotenuse),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.angleA&&this.hypotenuse){var t=Math.PI*this.angleA/180;this.horizontalLeg=Math.cos(t)*this.hypotenuse,this.verticalLeg=Math.sin(t)*this.hypotenuse}this.updateLayout()}updateLayout(){const e=ry(this.showLabels),t=e,r=this.unitScale*this.verticalLeg+e;if(this.shapePath.clearPoints(),this.shapePath.addPoint(t,r),this.shapePath.addPoint(t+this.unitScale*this.horizontalLeg,r),this.shapePath.addPoint(t+this.unitScale*this.horizontalLeg,r-this.unitScale*this.verticalLeg),this.shapePath.addPoint(t,r),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var i=new Xo,s=this.horizontalLeg.toString(),a=this.verticalLeg.toString(),o="";i.initializeWithShapePath(this.shapePath,[s,a,o]),this.labelsHolder.addChild(i)}this.width=this.unitScale*this.horizontalLeg+e*2,this.height=this.unitScale*this.verticalLeg+e*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Ps extends Oe{constructor(){super(),this.type="omdIsoscelesTriangle",this.triangleBase=5,this.triangleHeight=10,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.base<"u"&&(this.triangleBase=e.base),typeof e.height<"u"&&(this.triangleHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){this.shapePath.clearPoints();const e=this.unitScale*this.triangleBase,t=this.unitScale*this.triangleHeight,r=ry(this.showLabels),i=r,s=t+r;if(this.shapePath.addPoint(i,s),this.shapePath.addPoint(i+e,s),this.shapePath.addPoint(i+e*.5,s-t),this.shapePath.addPoint(i,s),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var a=new Xo;a.initializeWithShapePath(this.shapePath),this.labelsHolder.addChild(a)}this.width=this.unitScale*this.triangleBase+r*2,this.height=this.unitScale*this.triangleHeight+r*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class zs extends Oe{constructor(){super(),this.type="omdRectangle",this.rectWidth=10,this.rectHeight=10,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.width<"u"&&(this.rectWidth=e.width),typeof e.height<"u"&&(this.rectHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=ry(this.showLabels),t=e,r=this.unitScale*this.rectHeight+e;if(this.shapePath.clearPoints(),this.shapePath.addPoint(t,r),this.shapePath.addPoint(t+this.unitScale*this.rectWidth,r),this.shapePath.addPoint(t+this.unitScale*this.rectWidth,r-this.unitScale*this.rectHeight),this.shapePath.addPoint(t,r-this.unitScale*this.rectHeight),this.shapePath.addPoint(t,r),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var i=new Xo,s=this.rectWidth.toString(),a=this.rectHeight.toString();i.initializeWithShapePath(this.shapePath,[s,a,"",""]),this.labelsHolder.addChild(i)}this.width=this.unitScale*this.rectWidth+e*2,this.height=this.unitScale*this.rectHeight+e*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Rs extends Oe{constructor(){super(),this.type="omdEllipse",this.rectWidth=10,this.rectHeight=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Tr,this.shapePath.setWidthAndHeight(this.rectWidth*this.unitScale,this.rectHeight*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.width<"u"&&(this.rectWidth=e.width),typeof e.height<"u"&&(this.rectHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=this.rectWidth*this.unitScale,t=this.rectHeight*this.unitScale;if(this.shapePath.setWidthAndHeight(e,t),this.shapePath.setPosition(e*.5+10,t*.5+10),this.labelsHolder.removeAllChildren(),this.showLabels){const r=new si;r.setAlignment("center"),r.setFontFamily("Albert Sans"),r.setFontColor("black"),r.setFontSize(12),r.setPosition(e*.5+10,t*.5+14),r.setText(`${this.rectWidth} × ${this.rectHeight}`),this.labelsHolder.addChild(r)}this.width=this.rectWidth*this.unitScale+20,this.height=this.rectHeight*this.unitScale+20,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Ls extends Oe{constructor(){super(),this.type="omdCircle",this.radius=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Tr,this.shapePath.setWidthAndHeight(this.radius*this.unitScale,this.radius*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.radius<"u"&&(this.radius=e.radius),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=2*this.radius*this.unitScale,t=this.radius*this.unitScale,r=t+10,i=t+10;if(this.shapePath.setWidthAndHeight(e,e),this.shapePath.setPosition(r,i),this.labelsHolder.removeAllChildren(),this.showLabels){const s=-Math.PI/6,a=r+Math.cos(s)*t*.82,o=i+Math.sin(s)*t*.82,l=new Ut;l.setStrokeColor("black"),l.setStrokeWidth(1.5),l.setEndpoints(r,i,a,o),this.labelsHolder.addChild(l);const u=new si;u.setAlignment("center"),u.setFontFamily("Albert Sans"),u.setFontColor("black"),u.setFontSize(12),u.svgObject.setAttribute("dominant-baseline","middle"),u.setRotation(s*180/Math.PI),u.setPosition((r+a)*.5+3,(i+o)*.5-4),u.setText(`r=${this.radius}`),this.labelsHolder.addChild(u)}this.width=2*this.radius*this.unitScale+20,this.height=2*this.radius*this.unitScale+20,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Is extends Oe{constructor(){super(),this.type="omdRegularPolygon",this.radius=5,this.numberOfSides=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setWidthAndHeight(this.radius*this.unitScale,this.radius*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.radius<"u"&&(this.radius=e.radius),typeof e.numberOfSides<"u"&&(this.numberOfSides=e.numberOfSides),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){this.shapePath.clearPoints();const e=this.radius*this.unitScale,t=this.showLabels?48:14,r=e+t,i=e+t;var s=0;this.numberOfSides%2==1&&(s=Math.PI/this.numberOfSides*.5,(this.numberOfSides-1)/2%2==0&&(s*=-1));for(var a=0;a<=this.numberOfSides;a++){var o=-2*Math.PI/this.numberOfSides*a;o+=s;var l=r+Math.cos(o)*e,u=i+Math.sin(o)*e;this.shapePath.addPoint(l,u)}if(this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var c=new Xo,h=2*this.radius*Math.sin(Math.PI/this.numberOfSides),o=h.toFixed(2);c.initializeWithShapePath(this.shapePath,[o]),this.labelsHolder.addChild(c)}this.width=2*e+t*2,this.height=2*e+t*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Xo extends Oe{constructor(){super()}initializeWithShapePath(e,t=[]){const r=Jq(e),i=Zq(r);for(let s=0;s<r.length;s++){if(s>=t.length)continue;const a=t[s],o=String(a??"");if(o.length===0)continue;const l=r[s],u=l.x,c=l.y,h=r[(s+1)%r.length],f=h.x,d=h.y;let p=f-u,m=d-c;const y=Math.sqrt(p*p+m*m);p/=y,m/=y;const v=(u+f)/2,S=(c+d)/2;let g=-1*m,b=p;const w=v-i.x,x=S-i.y;w*g+x*b<0&&(g*=-1,b*=-1);const N=new Ut,D=u+g*10,C=c+b*10,A=f+g*10,E=d+b*10;N.setEndpoints(D,C,A,E),this.addChild(N);let F=Math.atan2(m,p)*180/Math.PI;(F>90||F<-90)&&(F+=180);const O=v+g*18,k=S+b*18,B=new si;B.setAlignment("center"),B.setFontFamily("Albert Sans"),B.setFontColor("black"),B.setFontSize(12),B.setPosition(O,k),B.setRotation(F),B.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(B),B.setText(o)}}}class $s extends Oe{constructor(){super();const t=document.createElementNS("http://www.w3.org/2000/svg","svg");this.svgObject&&this.svgObject.parentNode&&this.svgObject.parentNode.replaceChild(t,this.svgObject),this.svgObject=t,this.svgObject.setAttribute("overflow","hidden"),this.graphEquations=[],this.lineSegments=[],this.dotValues=[],this.shapeSet=[],this.xMin=-5,this.xMax=5,this.yMin=-5,this.yMax=5,this.xLabel="",this.yLabel="",this.axisLabelOffsetPx=20,this.size="medium",this.tickInterval=1,this.forceAllTickLabels=!0,this.tickLabelOffsetPx=5,this.showTickLabels=!0,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=15,this.backgroundOpacity=1,this.showBackground=!0,this.interactive=!1,this.variables=[],this.basePaddingBottom=30,this.interactivePaddingBottom=0,this.customPaddingTop=null,this.customPaddingRight=null,this.customPaddingBottom=null,this.customPaddingLeft=null,this.renderedFunctionEntries=[],this.sliderControlRows=[],this.calculatePadding(),this.updateLayout()}loadFromJSON(e){this.graphEquations=e.graphEquations||[],this.lineSegments=e.lineSegments||[],this.dotValues=e.dotValues||[],this.shapeSet=e.shapeSet||[],this.xMin=e.xMin!==void 0?e.xMin:this.xMin,this.xMax=e.xMax!==void 0?e.xMax:this.xMax,this.yMin=e.yMin!==void 0?e.yMin:this.yMin,this.yMax=e.yMax!==void 0?e.yMax:this.yMax,this.xLabel=e.xLabel!==void 0?e.xLabel:this.xLabel,this.yLabel=e.yLabel!==void 0?e.yLabel:this.yLabel,this.axisLabelOffsetPx=e.axisLabelOffsetPx!==void 0?e.axisLabelOffsetPx:this.axisLabelOffsetPx,this.size=e.size!==void 0?e.size:this.size,this.tickInterval=e.tickInterval!==void 0?e.tickInterval:this.tickInterval,this.tickLabelOffsetPx=e.tickLabelOffsetPx!==void 0?e.tickLabelOffsetPx:this.tickLabelOffsetPx,this.forceAllTickLabels=e.forceAllTickLabels!==void 0?e.forceAllTickLabels:this.forceAllTickLabels,this.showTickLabels=e.showTickLabels!==void 0?e.showTickLabels:this.showTickLabels,typeof e.graphPadding=="number"?(this.customPaddingTop=e.graphPadding,this.customPaddingRight=e.graphPadding,this.customPaddingBottom=e.graphPadding,this.customPaddingLeft=e.graphPadding):e.graphPadding&&typeof e.graphPadding=="object"&&(typeof e.graphPadding.top=="number"&&(this.customPaddingTop=e.graphPadding.top),typeof e.graphPadding.right=="number"&&(this.customPaddingRight=e.graphPadding.right),typeof e.graphPadding.bottom=="number"&&(this.customPaddingBottom=e.graphPadding.bottom),typeof e.graphPadding.left=="number"&&(this.customPaddingLeft=e.graphPadding.left)),typeof e.paddingTop=="number"&&(this.customPaddingTop=e.paddingTop),typeof e.paddingRight=="number"&&(this.customPaddingRight=e.paddingRight),typeof e.paddingBottom=="number"&&(this.customPaddingBottom=e.paddingBottom),typeof e.paddingLeft=="number"&&(this.customPaddingLeft=e.paddingLeft),this.backgroundColor=e.backgroundColor||this.backgroundColor,this.backgroundCornerRadius=e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:this.backgroundCornerRadius,this.backgroundOpacity=e.backgroundOpacity!==void 0?e.backgroundOpacity:this.backgroundOpacity,this.showBackground=e.showBackground!==void 0?e.showBackground:this.showBackground,this.interactive=e.interactive===!0||e.interactive==="true",this.variables=this.normalizeInteractiveVariables(e.variables||e.interactiveVariables||[]),this.calculatePadding(),this.updateLayout()}updateLayout(){this.removeAllChildren(),this.calculateGraphDimensions();const e=this.width,t=this.height,r=new Ho(e,t,15);this.addChild(r);const i=new yt;i.setWidthAndHeight(e,t),this.showBackground?(i.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&i.setOpacity(this.backgroundOpacity)):i.setFillColor("transparent"),i.setStrokeWidth(0),i.setCornerRadius&&this.backgroundCornerRadius>0&&i.setCornerRadius(this.backgroundCornerRadius),r.addChild(i);const s=new Oe;s.setPosition(0,0),r.addChild(s),this.setWidthAndHeight(e,t),this.svgObject.setAttribute("viewBox",`0 0 ${e} ${t}`);const a=new Oe;s.addChild(a),this.makeGrid(a);const o=new Ho(this.graphWidth,this.graphHeight,0);o.setPosition(this.paddingLeft,this.paddingTop),s.addChild(o);const l=new Oe;o.addChild(l),this.graphMultipleFunctions(l);const u=new Oe;o.addChild(u),this.drawLineSegments(u);const c=new Oe;o.addChild(c),this.plotDots(c);const h=new Oe;o.addChild(h),this.addShapes(h),this.sliderControlRows=[],this.shouldShowInteractiveControls()&&this.createInteractiveControls(this.svgObject)}createAxisGrid(e,t){const r=this.tickInterval||1,i=t?this.xMin:this.yMin,s=t?this.xMax:this.yMax,a=Math.ceil(i),o=Math.floor(s);let l=r;if(!this.forceAllTickLabels){const c=t?this.xMax-this.xMin:this.yMax-this.yMin;let f=Math.floor(c/10)*10/6,d=Math.round(f/5)*5;d===0&&(d=1),l=d}let u=!1;for(let c=a;c<=o;c+=r){const h=this.computeAxisPos(t,c),f=new Ut;this.setAxisLineEndpoints(t,f,h),f.setStrokeColor("black"),f.setOpacity(c===0?1:.15),e.addChild(f),c===0&&(u=!0);let d=!1;this.showTickLabels&&(this.forceAllTickLabels?d=!0:d=((y,v)=>Math.abs(y/v-Math.round(y/v))<1e-9)(c,l)),d&&(this.addTickLabel(e,t,h,c),t?Math.max(20,Math.min(h,this.width-20)):Math.max(15,Math.min(h,this.height-7.5)))}if(0>=i&&0<=s&&!u){const c=this.computeAxisPos(t,0),h=new Ut;this.setAxisLineEndpoints(t,h,c),h.setStrokeColor("black"),h.setOpacity(1),e.addChild(h)}}createAxisLabels(e){if(this.xLabel){const t=Math.max(60,this.xLabel.length*10),r=20,i=new Bt;i.setWidthAndHeight(t,r),i.setText(this.xLabel),i.setFontSize(14),i.setFontColor("black"),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(600);const s=this.paddingLeft+this.graphWidth/2-t/2,a=Math.max(5,Math.min(s,this.width-t-5));i.setPosition(a,this.height-this.paddingBottom+this.axisLabelOffsetPx),e.addChild(i)}if(this.yLabel){const r=Math.max(15,this.paddingLeft-(this.axisLabelOffsetPx+10)),i=this.paddingTop+this.graphHeight/2,s=new Oe,a=new si;a.setText(this.yLabel),a.setFontSize(14),a.setFontColor("black"),a.setPosition(0,0),a.svgObject.setAttribute("text-anchor","middle"),a.svgObject.setAttribute("dominant-baseline","middle"),a.setFontWeight(600),s.addChild(a),s.svgObject.setAttribute("transform",`translate(${r}, ${i}) rotate(-90)`),e.addChild(s)}}makeGrid(e){this.createAxisGrid(e,!0),this.createAxisGrid(e,!1),this.createAxisLabels(e)}calculatePadding(){const e=this.yLabel?50:30,t=this.xLabel?50:30,r=25,i=25;this.paddingLeft=typeof this.customPaddingLeft=="number"?this.customPaddingLeft:e,this.basePaddingBottom=typeof this.customPaddingBottom=="number"?this.customPaddingBottom:t,this.interactivePaddingBottom=this.shouldShowInteractiveControls()?this.getInteractiveControlHeight():0,this.paddingBottom=this.basePaddingBottom+this.interactivePaddingBottom,this.paddingTop=typeof this.customPaddingTop=="number"?this.customPaddingTop:r,this.paddingRight=typeof this.customPaddingRight=="number"?this.customPaddingRight:i}computeAxisPos(e,t){return e?this.paddingLeft+(t-this.xMin)*this.xSpacer:this.height-this.paddingBottom-(t-this.yMin)*this.ySpacer}setAxisLineEndpoints(e,t,r){e?t.setEndpoints(r,this.paddingTop,r,this.height-this.paddingBottom):t.setEndpoints(this.paddingLeft,r,this.width-this.paddingRight,r)}addTickLabel(e,t,r,i){const s=this.createNumericLabel(i);if(t){const a=Math.max(10,Math.min(r-10,this.width-30));s.setPosition(a,this.height-this.paddingBottom+this.tickLabelOffsetPx)}else{const a=Math.max(5,this.paddingLeft-(this.tickLabelOffsetPx+20)),o=Math.max(7.5,Math.min(r-7.5,this.height-15));s.setPosition(a,o)}e.addChild(s)}toGraphPixelX(e){return(e-this.xMin)*this.xSpacer}toGraphPixelY(e){return this.graphHeight-(e-this.yMin)*this.ySpacer}createNumericLabel(e){const t=new Bt;return t.setWidthAndHeight(20,15),t.setText(String(e)),t.setFontSize(9),t.setFontColor(this.getAllowedColor("black")),t.setAlignment("center"),t.setVerticalCentering(),t}getAllowedColor(e){if(!e)return"black";const t=String(e).trim();return Fe[t.toLowerCase()]||t||"black"}assignFromData(e,t){for(const[r,i]of Object.entries(t))typeof e[r]===i&&(this[r]=e[r])}calculateGraphDimensions(){let e=200,t=8;this.size==="large"?(e=300,t=12):this.size==="small"&&(e=100,t=6),this.dotSize=t,this.xSpan=this.xMax-this.xMin,this.ySpan=this.yMax-this.yMin;const r=Math.min(e/this.xSpan,e/this.ySpan);this.graphWidth=r*this.xSpan,this.graphHeight=r*this.ySpan,this.width=this.graphWidth+this.paddingLeft+this.paddingRight,this.height=this.graphHeight+this.paddingTop+this.paddingBottom,this.xSpacer=r,this.ySpacer=r,this.originX=this.paddingLeft-this.xMin*this.xSpacer,this.originY=this.height-this.paddingBottom+this.yMin*this.ySpacer}graphMultipleFunctions(e){this.renderedFunctionEntries=[];for(const t of this.graphEquations)try{const r=this.compileFunctionExpression(t.equation),i=new Ni;i.setStrokeColor(this.getAllowedColor(t.color)),i.setStrokeWidth(t.strokeWidth),this.graphFunctionWithDomain(i,t.domain,r),e.addChild(i);const s={functionConfig:t,compiledExpression:r,path:i,label:null};t.label&&(s.label=this.addFunctionLabel(e,t,r)),this.renderedFunctionEntries.push(s)}catch(r){console.warn(`Failed to graph equation: ${t.equation}`,r)}}_extractExpression(e){let t=String(e).trim();return t=t.replace(/^\s*y\s*=\s*/i,"").replace(/\s*=\s*y\s*$/i,""),t}compileFunctionExpression(e){return math.compile(this._extractExpression(e))}graphFunctionWithDomain(e,t,r){e.clearPoints();const i=t&&typeof t.min=="number"?t.min:this.xMin,s=t&&typeof t.max=="number"?t.max:this.xMax,a=this.shouldShowInteractiveControls()?400:1e3,o=s-i;for(let l=0;l<=a;l++){const u=i+o*l/a,c=r.evaluate(this.getEvaluationScope({x:u}));Number.isFinite(c)&&e.addPoint(this.toGraphPixelX(u),this.toGraphPixelY(c))}e.updatePath()}addFunctionLabel(e,t,r){const i=String(t.label),s=12,a=6,o=Math.max(40,i.length*(s*.6)),l=s+a,u=new Bt;return u.setWidthAndHeight(o,l),u.setText(i),u.setFontSize(s),u.setFontColor(this.getAllowedColor(t.color||"black")),u.setAlignment("center"),u.setVerticalCentering(),u.setFontWeight(500),this.updateFunctionLabelPosition(u,t,r),e.addChild(u),u}updateFunctionLabelPosition(e,t,r){const i=typeof t.labelAtX=="number"?t.labelAtX:this.xMin+(this.xMax-this.xMin)*.1;let s=this.yMin+(this.yMax-this.yMin)*.1;s=r.evaluate(this.getEvaluationScope({x:i}));const o=this.toGraphPixelX(i),l=this.toGraphPixelY(s),u=(t.labelPosition||"below").toLowerCase(),c=10;let h=o,f=l;switch(u){case"above":f=l-c;break;case"below":f=l+c;break;case"left":h=o-c;break;case"right":h=o+c;break;default:f=l+c}e.setPosition(h,f)}drawLineSegments(e){for(const t of this.lineSegments){const r=this.toGraphPixelX(t.point1[0]),i=this.toGraphPixelY(t.point1[1]),s=this.toGraphPixelX(t.point2[0]),a=this.toGraphPixelY(t.point2[1]),o=new Ut;o.setEndpoints(r,i,s,a),o.setStrokeColor(this.getAllowedColor(t.color||"blue")),o.setStrokeWidth(t.strokeWidth||2),e.addChild(o)}}plotDots(e){for(const t of this.dotValues){const r=this.toGraphPixelX(t[0]),i=this.toGraphPixelY(t[1]),s=new Tr;s.setWidthAndHeight(this.dotSize,this.dotSize),s.setPosition(r,i),s.setFillColor(this.getAllowedColor(t.length>=3?t[2]:"black")),e.addChild(s)}}addShapes(e){e.setPosition(-this.xMin*this.xSpacer,this.graphHeight+this.yMin*this.ySpacer);const t={rightTriangle:ks,isoscelesTriangle:Ps,rectangle:zs,ellipse:Rs,circle:Ls,regularPolygon:Is};for(const r of this.shapeSet){const i=t[r.omdType];if(!i)continue;r.unitScale=this.xSpacer;const s=new i;s.loadFromJSON(r),s.shapePath&&s.shapePath.setFillColor("none"),e.addChild(s)}}shouldShowInteractiveControls(){return this.interactive===!0&&this.variables.length>0}getInteractiveControlHeight(){return 18+this.variables.length*38}normalizeInteractiveVariables(e){return Array.isArray(e)?e.map((t,r)=>this.normalizeInteractiveVariable(t,r)).filter(Boolean):[]}normalizeInteractiveVariable(e,t){const r=typeof e=="string"?{name:e}:e&&typeof e=="object"?e:null;if(!r)return null;const i=String(r.name??r.variable??r.id??"").trim();if(!i)return null;let s=Number.isFinite(r.min)?r.min:-10,a=Number.isFinite(r.max)?r.max:10;if(a<s){const c=s;s=a,a=c}a===s&&(a=s+1);const o=Number.isFinite(r.step)&&r.step>0?r.step:.1,l=s<=0&&a>=0?0:s,u=this.clampInteractiveValue(Number.isFinite(r.value)?r.value:l,s,a);return{name:i,label:String(r.label??i),min:s,max:a,step:o,value:u,color:r.color??null,graphIndex:Number.isInteger(r.graphIndex)?r.graphIndex:Number.isInteger(r.equationIndex)?r.equationIndex:null,order:t}}clampInteractiveValue(e,t,r){return Math.max(t,Math.min(r,e))}snapInteractiveValue(e,t){const r=t.step||.1,i=t.min+Math.round((e-t.min)/r)*r,s=this.getStepPrecision(r),a=Number(i.toFixed(s));return this.clampInteractiveValue(a,t.min,t.max)}getStepPrecision(e){const t=String(e);return t.includes(".")?t.split(".")[1].length:0}getInteractiveVariableValue(e){return e?Number.isFinite(e.currentValue)?e.currentValue:Number.isFinite(e.value)?e.value:0:0}getEvaluationScope(e={}){const t={...e};for(const r of this.variables)t[r.name]=this.getInteractiveVariableValue(r);return t}createInteractiveControls(e){const t=this.createSvgElement("g",{"data-omd-interactive-controls":"true"}),i=this.paddingTop+this.graphHeight+this.basePaddingBottom+8,s=this.paddingLeft,a=this.width-this.paddingRight,o=this.paddingLeft+36,l=this.width-this.paddingRight-56,u=Math.max(40,l-o);this.sliderControlRows=this.variables.map((c,h)=>{const f=this.resolveInteractiveVariableColor(c),d=i+h*38,p=this.createSvgElement("g",{transform:`translate(0, ${d})`,"data-omd-variable":c.name}),m=this.createSvgElement("text",{x:s,y:4,fill:f,"font-size":13,"font-weight":700,"dominant-baseline":"middle"});m.textContent=c.label;const y=this.createSvgElement("line",{x1:o,y1:0,x2:o+u,y2:0,stroke:"#d1d5db","stroke-width":6,"stroke-linecap":"round"}),v=this.createSvgElement("line",{x1:o,y1:0,x2:o,y2:0,stroke:f,"stroke-width":6,"stroke-linecap":"round"}),S=this.createSvgElement("circle",{cx:o,cy:0,r:8,fill:f,stroke:"#ffffff","stroke-width":2}),g=this.createSvgElement("text",{x:a,y:4,fill:f,"font-size":12,"font-weight":600,"dominant-baseline":"middle","text-anchor":"end"}),b=this.createSvgElement("rect",{x:o-10,y:-14,width:u+20,height:28,fill:"transparent","pointer-events":"all",rx:14});b.style.cursor="pointer",p.appendChild(m),p.appendChild(y),p.appendChild(v),p.appendChild(S),p.appendChild(g),p.appendChild(b),t.appendChild(p);const w={variable:c,color:f,label:m,track:y,activeTrack:v,thumb:S,valueText:g,hitArea:b,trackStart:o,trackEnd:o+u};return this.attachSliderInteraction(w),this.updateSliderRow(w),w}),e.appendChild(t)}attachSliderInteraction(e){const t=r=>{const s=(this.clientToLocalSvgX(r.clientX)-e.trackStart)/(e.trackEnd-e.trackStart),a=e.variable.min+s*(e.variable.max-e.variable.min),o=this.snapInteractiveValue(a,e.variable);e.variable.currentValue=o,e.variable.value=o,this.refreshInteractiveElements()};e.hitArea.addEventListener("pointerdown",r=>{var a,o;r.preventDefault(),r.stopPropagation(),t(r),(o=(a=e.hitArea).setPointerCapture)==null||o.call(a,r.pointerId);const i=l=>{l.preventDefault(),l.stopPropagation(),t(l)},s=l=>{var u,c,h,f;(u=l==null?void 0:l.preventDefault)==null||u.call(l),(c=l==null?void 0:l.stopPropagation)==null||c.call(l),e.hitArea.removeEventListener("pointermove",i),e.hitArea.removeEventListener("pointerup",s),e.hitArea.removeEventListener("pointercancel",s);try{(f=(h=e.hitArea).releasePointerCapture)==null||f.call(h,r.pointerId)}catch{}};e.hitArea.addEventListener("pointermove",i),e.hitArea.addEventListener("pointerup",s),e.hitArea.addEventListener("pointercancel",s)})}refreshInteractiveElements(){var e;for(const t of this.renderedFunctionEntries)try{this.graphFunctionWithDomain(t.path,t.functionConfig.domain,t.compiledExpression),t.label&&this.updateFunctionLabelPosition(t.label,t.functionConfig,t.compiledExpression)}catch(r){console.warn(`Failed to refresh equation: ${(e=t.functionConfig)==null?void 0:e.equation}`,r)}for(const t of this.sliderControlRows)this.updateSliderRow(t)}updateSliderRow(e){const t=this.getInteractiveVariableValue(e.variable),r=(t-e.variable.min)/(e.variable.max-e.variable.min),i=Math.max(0,Math.min(1,r)),s=e.trackStart+(e.trackEnd-e.trackStart)*i;e.activeTrack.setAttribute("x2",String(s)),e.thumb.setAttribute("cx",String(s)),e.valueText.textContent=this.formatInteractiveValue(t,e.variable.step)}formatInteractiveValue(e,t){const r=Math.min(4,Math.max(0,this.getStepPrecision(t)));return`${Number(e.toFixed(r))}`}resolveInteractiveVariableColor(e){var i;if(e.color)return this.getAllowedColor(e.color);const t=e.graphIndex;if(Number.isInteger(t)&&((i=this.graphEquations[t])!=null&&i.color))return this.getAllowedColor(this.graphEquations[t].color);const r=this.graphEquations.find(s=>this.equationContainsVariable(s==null?void 0:s.equation,e.name));return r!=null&&r.color?this.getAllowedColor(r.color):this.getAllowedColor("#2563eb")}equationContainsVariable(e,t){if(!e||!t)return!1;const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_])${r}([^A-Za-z0-9_]|$)`).test(String(e))}createSvgElement(e,t={}){const r=document.createElementNS("http://www.w3.org/2000/svg",e);for(const[i,s]of Object.entries(t))s!=null&&r.setAttribute(i,String(s));return r}clientToLocalSvgX(e){const t=this.svgObject.getBoundingClientRect(),r=(this.svgObject.getAttribute("viewBox")||"0 0 0 0").split(/\s+/).map(Number),[i=0,,s=0]=r;return!t.width||!s?0:i+(e-t.left)/t.width*s}setBackgroundColor(e){this.backgroundColor=e,this.updateLayout()}setBackgroundCornerRadius(e){this.backgroundCornerRadius=e,this.updateLayout()}setBackgroundOpacity(e){this.backgroundOpacity=Math.max(0,Math.min(1,e)),this.updateLayout()}setShowBackground(e){this.showBackground=e,this.updateLayout()}setBackgroundStyle(e={}){e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.cornerRadius!==void 0&&(this.backgroundCornerRadius=e.cornerRadius),e.opacity!==void 0&&(this.backgroundOpacity=Math.max(0,Math.min(1,e.opacity))),e.show!==void 0&&(this.showBackground=e.show),this.updateLayout()}}class Qq extends Oe{constructor(){super(),this.startValue=1,this.endValue=3,this.startIndex=0,this.endIndex=1,this.label="label",this.showBelow=!1,this.unitWidth=30,this.indexPositions=[],this.startPos=0,this.endPos=0,this.updateLayout()}setIndexPositions(e){this.indexPositions=e}loadFromJSON(e){if(!e||typeof e!="object")return;const{startIndex:t,endIndex:r,label:i,showBelow:s}=e;t!==void 0&&(this.startIndex=t,t>=0&&t<=this.indexPositions.length&&(this.startPos=this.indexPositions[t])),r!==void 0&&(this.endIndex=r,r>=0&&r<=this.indexPositions.length&&(this.endPos=this.indexPositions[r])),i!==void 0&&(this.label=i),s!==void 0&&(this.showBelow=s),this.updateLayout()}updateLayout(){this.removeAllChildren();var e=this.startPos,t=this.endPos,r=t-e;this.line=new Ut,this.line.setEndpoints(e,0,t,0),this.addChild(this.line);var i=new Ut;i.setEndpoints(e,-3,e,3),this.addChild(i),i=new Ut,i.setEndpoints(t,-3,t,3),this.addChild(i);var s=new Bt;s.setWidthAndHeight(r,30),s.setText(this.name),s.setFontFamily("Albert Sans"),s.setFontColor("black"),s.setFontSize(14),s.setAlignment("center"),s.setText(this.label),this.showBelow?s.setPosition(e,5):s.setPosition(e,-20),this.addChild(s);var a=Math.max(r,t),o=this.showBelow?35:30;this.setWidthAndHeight(a,o),this.svgObject.setAttribute("viewBox",`0 ${this.showBelow?-5:-25} ${a} ${o}`)}}class mn extends Oe{constructor(){super(),this.type="omdTapeDiagram",this.title="",this.values=[],this.labelSet=[],this.totalWidth=300,this.updateLayout()}loadFromJSON(e){typeof e.title<"u"&&(this.title=e.title),typeof e.values<"u"&&(this.values=e.values),typeof e.labelSet<"u"&&(this.labelSet=e.labelSet),typeof e.totalWidth<"u"&&(this.totalWidth=e.totalWidth),this.updateLayout()}setValues(e){this.values=e,this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.title?80:20,t=20,r=70;if(this.title){const g=new Bt;g.setWidthAndHeight(r,30),g.setFontFamily("Albert Sans"),g.setFontColor("black"),g.setFontSize(12),g.setAlignment("left"),g.setText(this.title),g.setPosition(5,5),this.addChild(g)}const i=[];let s=0;for(const g of this.values){let b="",w=!0,x=Fe.lightGray,N=1;typeof g=="object"&&g!==null?(b=g.value||"",w=g.showLabel!==void 0?g.showLabel:!0,x=g.color||Fe.lightGray):b=g.toString();const D=b.match(/^([0-9.]+)?([a-zA-Z]*)$/);if(D){const C=D[1]?parseFloat(D[1]):(D[2],1);D[2],N=C}i.push({value:b,showLabel:w,color:x,numericValue:N}),s+=N}var a=e,o=[];for(const g of i){o.push(a);const b=s>0?g.numericValue/s:1/i.length,w=this.totalWidth*b;var l=new yt;if(l.setWidthAndHeight(w,30),l.setCornerRadius(5),l.setStrokeColor("white"),l.setStrokeWidth(1),l.setFillColor(g.color),l.setPosition(a,0),this.addChild(l),g.showLabel){var u=new Bt;u.setWidthAndHeight(w,30),u.setFontFamily("Albert Sans"),u.setFontColor("black"),u.setFontSize(18),u.setAlignment("center"),u.setVerticalCentering(),u.setText(g.value),u.setPosition(a,0),this.addChild(u)}a+=w}o.push(a);var c=a-e,h=30,f=0,d=0;const p=this.labelSet.slice().map((g,b)=>({data:g,span:(g.endIndex||0)-(g.startIndex||0)})).sort((g,b)=>g.span-b.span),m=[],y=[];for(const g of p){const b=g.data,w=new Qq;if(w.setIndexPositions(o),w.loadFromJSON(b),w.showBelow){let x=0;const N=b.startIndex||0,D=b.endIndex||0;for(;x<y.length&&y[x].some(E=>!(D<=E.start||N>=E.end));)x++;x===y.length&&y.push([]),y[x].push({start:N,end:D});const C=40+x*35;w.setPosition(0,C),d=Math.max(d,C+30)}else{let x=0;const N=b.startIndex||0,D=b.endIndex||0;for(;x<m.length&&m[x].some(E=>!(D<=E.start||N>=E.end));)x++;x===m.length&&m.push([]),m[x].push({start:N,end:D});const C=-10-x*35;w.setPosition(0,C),f=Math.max(f,(x+1)*35)}this.addChild(w)}this.width=e+c+t,this.height=f+h+d;const v=-f,S=this.height;this.svgObject.setAttribute("viewBox",`0 ${v} ${this.width} ${S}`),this.svgObject.setAttribute("viewBox",`0 ${-f} ${this.width} ${this.height}`)}}class iy extends Oe{constructor(){super(),this.type="omdDoubleTapeDiagram",this.topTapeDiagram=new mn,this.bottomTapeDiagram=new mn,this.spacing=30,this.updateLayout()}loadFromJSON(e){typeof e.spacing<"u"&&(this.spacing=e.spacing),typeof e.topTapeDiagram<"u"&&this.topTapeDiagram.loadFromJSON(e.topTapeDiagram),typeof e.bottomTapeDiagram<"u"&&this.bottomTapeDiagram.loadFromJSON(e.bottomTapeDiagram),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.calculateTotalValue(this.topTapeDiagram),t=this.calculateTotalValue(this.bottomTapeDiagram),r=Math.max(e,t),i=300,s=r>0?i/r:i;this.topTapeDiagram.totalWidth=e*s,this.bottomTapeDiagram.totalWidth=t*s,this.topTapeDiagram.updateLayout(),this.bottomTapeDiagram.updateLayout();const a=this.topTapeDiagram.title?80:20,o=this.bottomTapeDiagram.title?80:20,l=Math.max(a,o),u=l-a;this.topTapeDiagram.setPosition(u,0),this.addChild(this.topTapeDiagram);const c=l-o,h=this.topTapeDiagram.height+this.spacing;this.bottomTapeDiagram.setPosition(c,h),this.addChild(this.bottomTapeDiagram);const f=Math.max(this.topTapeDiagram.width+u,this.bottomTapeDiagram.width+c);this.width=f,this.height=this.topTapeDiagram.height+this.spacing+this.bottomTapeDiagram.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}calculateTotalValue(e){let t=0;for(const r of e.values){let i="";typeof r=="object"&&r!==null?i=r.value||"":i=r.toString();const s=i.match(/^([0-9.]+)?([a-zA-Z]*)$/);if(s){const a=s[1]?parseFloat(s[1]):(s[2],1);t+=a}else t+=1}return t}}class $i extends Oe{constructor(){super(),this.type="omdNumberLine",this.value=1,this.size="large",this.dotsPerColumn=10,this.backgroundColor=Fe.lightGray,this.dotColor="black",this.updateLayout()}loadFromJSON(e){typeof e.value<"u"&&(this.value=e.value),typeof e.size<"u"&&(this.size=e.size),typeof e.dotsPerColumn<"u"&&(this.dotsPerColumn=Math.max(1,Number(e.dotsPerColumn))),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.dotColor<"u"&&(this.dotColor=e.dotColor),this.updateLayout()}setValue(e){this.value=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}updateLayout(){this.removeAllChildren();const e=Math.max(0,Number(this.value)||0),t=Math.max(1,Number(this.dotsPerColumn)||1);let r;this.size==="large"?r=15:this.size==="medium"?r=12:r=5;const i=Math.max(2,Math.round(r*.6)),s=Math.max(3,Math.round(r*.8)),a=Math.ceil(e/t),o=Math.min(t,e);this._dotSize=r,this._pad=s;const l=a>0?a*r+(a-1)*i:0,u=o>0?o*r+(o-1)*i:0,c=l+2*s,h=u+2*s,f=new yt;f.setWidthAndHeight(c,h);const d=a>1?Math.round(r):Math.min(c,h)/2;f.setCornerRadius(d),f.setFillColor(this.backgroundColor||Fe.lightGray),this.addChild(f),this.width=f.width,this.height=f.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);for(let p=0;p<e;p++){const m=Math.floor(p/t),y=p%t,v=s+m*(r+i)+r/2,S=s+y*(r+i)+r/2,g=new Tr;g.setFillColor(this.dotColor||"black"),g.setWidthAndHeight(r,r),g.setPosition(v,S),this.addChild(g)}}getTopDotCenterY(){const e=this._pad??0,t=this._dotSize??0;return e+t/2}}class ny extends Oe{constructor(){super(),this.type="omdTileEquation",this.left=[],this.right=[],this.equation=null,this.tileSize=28,this.tileGap=6,this.rowGap=10,this.equalGap=24,this.tileRadius=6,this.showLabels=!0,this.fontFamily="Albert Sans",this.fontSize=16,this.plusColor="#79BBFD",this.equalsColor="#FF6B6B",this.xPillColor=Fe.lightGray,this.numberTileDefaults={backgroundColor:Fe.lightGray,dotColor:"black"},this.updateLayout()}loadFromJSON(e){!e||typeof e!="object"||(Array.isArray(e.left)&&(this.left=e.left),Array.isArray(e.right)&&(this.right=e.right),typeof e.equation=="string"?this.equation=this._parseEquationString(e.equation):e.equation&&typeof e.equation=="object"?this.equation=e.equation:typeof e.equationString=="string"&&(this.equation=this._parseEquationString(e.equationString)),typeof e.tileSize=="number"&&(this.tileSize=e.tileSize),typeof e.tileGap=="number"&&(this.tileGap=e.tileGap),typeof e.equalGap=="number"&&(this.equalGap=e.equalGap),typeof e.tileRadius=="number"&&(this.tileRadius=e.tileRadius),typeof e.showLabels=="boolean"&&(this.showLabels=e.showLabels),typeof e.fontFamily=="string"&&(this.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(this.fontSize=e.fontSize),typeof e.plusColor=="string"&&(this.plusColor=e.plusColor),typeof e.equalsColor=="string"&&(this.equalsColor=e.equalsColor),e.xPill&&typeof e.xPill.color=="string"&&(this.xPillColor=e.xPill.color),typeof e.xPillColor=="string"&&(this.xPillColor=e.xPillColor),e.numberTileDefaults&&typeof e.numberTileDefaults=="object"&&(this.numberTileDefaults={backgroundColor:e.numberTileDefaults.backgroundColor??this.numberTileDefaults.backgroundColor,dotColor:e.numberTileDefaults.dotColor??this.numberTileDefaults.dotColor}),this.updateLayout())}_parseEquationString(e){try{const r=String(e||"").replace(/\s+/g,"").split("=");if(r.length!==2)return null;const i=r[0],s=r[1],a=c=>{const h=String(c||"").replace(/[\s−–]/g,y=>y===" "?"":"-"),f=/([+-]?\d*[a-zA-Z])|([+-]?\d+)/g;let d=null;const p=[];return(h.match(f)||[]).forEach(y=>{if(/[a-zA-Z]/.test(y)){const v=y.match(/^([+-]?)(\d*)([a-zA-Z])$/),S=(v[1]||"+")==="-"?"-":"+",g=v[2]?parseInt(v[2],10):1;d=d||v[3],p.push({kind:"x",count:Math.max(1,g),sign:S})}else{const v=y[0]==="-"?"-":"+",S=Math.abs(parseInt(y,10));p.push({kind:"const",value:Math.max(0,S),sign:v})}}),{varLabel:d,tokens:p}},o=a(i),l=a(s),u=o.varLabel||l.varLabel||"X";return{leftTokens:o.tokens,rightTokens:l.tokens,xLabel:u}}catch{return null}}updateLayout(){if(this.removeAllChildren(),this.equation){const o=this._renderEquation(this.equation);this.setWidthAndHeight(o.width,o.height),this.svgObject.setAttribute("viewBox",`0 0 ${o.width} ${o.height}`);return}const e=new Oe,t=new Oe;this.addChild(e),this.addChild(t);const r=this._renderSide(e,this.left),i=this._renderSide(t,this.right);t.setPosition(r.width+this.equalGap,0);const s=r.width+this.equalGap+i.width,a=Math.max(r.height,i.height);this.setWidthAndHeight(s,a),this.svgObject.setAttribute("viewBox",`0 0 ${s} ${a}`)}_renderSide(e,t){let r=0,i=0,s=0;return t.forEach(a=>{const o=(a==null?void 0:a.kind)||"var",l=(a==null?void 0:a.color)||(o==="var"?"#79BBFD":"#FFA26D"),u=Math.max(1,Number((a==null?void 0:a.count)||1));if(o==="text"){const p=new Bt;p.setWidthAndHeight(this.fontSize*(String(a.value).length*.7)+8*2,this.fontSize+6*2),p.setFontFamily(this.fontFamily),p.setFontSize(this.fontSize),p.setFontColor("black"),p.setAlignment("center"),p.setVerticalCentering(),p.setText(String(a.value));const v=new yt;v.setWidthAndHeight(p.width,p.height),v.setCornerRadius(Math.min(this.tileRadius,p.height/2)),v.setFillColor(Fe.lightGray);const S=new Oe;S.setPosition(r,i),S.addChild(v),S.addChild(p),e.addChild(S),r+=p.width+this.tileGap,s=Math.max(s,p.height);return}const c=new Oe;c.setPosition(r,i),e.addChild(c);const h=!!a.stack;let f=0,d=0;for(let p=0;p<u;p++){const m=new yt;m.setWidthAndHeight(this.tileSize,this.tileSize),m.setCornerRadius(Math.min(this.tileRadius,this.tileSize/2)),m.setFillColor(l);const y=h?0:p*(this.tileSize+this.tileGap),v=h?p*(this.tileSize+this.rowGap):0;m.setPosition(y,v),c.addChild(m),f=Math.max(f,y+this.tileSize),d=Math.max(d,v+this.tileSize)}r+=f+this.tileGap,s=Math.max(s,d)}),{width:r>0?r-this.tileGap:0,height:s}}_renderEquation(e){const t=Array.isArray(e.leftTokens)&&Array.isArray(e.rightTokens),r=t?e.leftTokens:[],i=t?e.rightTokens:[],s=Math.max(0,Number(e.leftX??e.x??0)),a=Array.isArray(e.leftUnitList)?e.leftUnitList:Number.isFinite(e.leftUnits??e.units)?[Math.max(0,Number(e.leftUnits??e.units))]:[],o=Math.max(0,Number(e.rightX??0)),l=Array.isArray(e.rightUnitList)?e.rightUnitList:Number.isFinite(e.rightUnits??e.total)?[Math.max(0,Number(e.rightUnits??e.total))]:[],u=String(e.xLabel||"X"),c=this.xPillColor||Fe.lightGray,f=.62*this.tileSize,d=Math.max(this.tileSize*1.6,Math.round(5*f)),p=this.tileSize,m=t?r.filter(L=>L.kind==="x").reduce((L,Y)=>L+Y.count,0):s,y=t?i.filter(L=>L.kind==="x").reduce((L,Y)=>L+Y.count,0):o,v=m>0?m*(p+this.rowGap)-this.rowGap:0,S=t?r.filter(L=>L.kind==="const").map(L=>{const Y=new $i;return Y.loadFromJSON({value:L.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}):a.map(L=>{const Y=new $i;return Y.loadFromJSON({value:L,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}),g=t?i.filter(L=>L.kind==="const").map(L=>{const Y=new $i;return Y.loadFromJSON({value:L.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}):l.map(L=>{const Y=new $i;return Y.loadFromJSON({value:L,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}),b=m>0?p/2:0,w=S.length?Math.min(...S.map(L=>L.getTopDotCenterY())):0,x=g.length?Math.min(...g.map(L=>L.getTopDotCenterY())):0,N=Math.max(b,w,x,this.tileSize*.6),D=m>0?N-b:0,C=S.length?N-w:0,A=g.length?N-x:0,E=[];m>0&&E.push(D+v),S.forEach(L=>E.push(C+L.height)),g.forEach(L=>E.push(A+L.height));const F=E.length?Math.max(...E):this.tileSize*2;let O=0;const k=(L,Y)=>{const ee=new si;ee.setText(L),ee.setFontSize(this.tileSize),ee.setFontColor(this.plusColor),ee.setAlignment("center"),ee.svgObject.setAttribute("dominant-baseline","middle"),ee.setPosition(Y+this.equalGap/2,N),this.addChild(ee)},B=()=>{const L=new Oe;for(let Y=0;Y<m;Y++){const ee=Y*(p+this.rowGap),_=new yt;_.setWidthAndHeight(d,p),_.setCornerRadius(p/2),_.setFillColor(c),_.setPosition(0,ee),L.addChild(_);const V=new si;V.setText(u),V.setFontWeight("bold"),V.setFontSize(this.tileSize*.7),V.setFontFamily(this.fontFamily),V.setFontColor("black"),V.setAlignment("center"),V.svgObject.setAttribute("dominant-baseline","middle");const z=p*.06;V.setPosition(d/2,ee+p/2+z),L.addChild(V)}return L},T=(L,Y,ee,_,V)=>{let z=Y,de=!1;return(t?L.slice():[..._>0?[{kind:"x",count:_,sign:"+"}]:[],...(V?a:l).map(oe=>({kind:"const",value:oe,sign:"+"}))]).forEach(oe=>{const $=oe.sign==="-"?"-":"+";if((de||$==="-")&&(k($==="-"?"−":"+",z),z+=this.equalGap),oe.kind==="x"){const H=B();H.setPosition(z,N-b),this.addChild(H),z+=d,de=!0}else{const H=new $i;H.loadFromJSON({value:oe.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),H.setPosition(z,ee),this.addChild(H),z+=H.width,de=!0}}),z};(t?r.length>0:m>0||S.length)&&(new Oe().setPosition(0,0),O=T(r,O,C,m,!0)),O+=this.equalGap,this.tileSize*1.2;const I=new si;I.setText("="),I.setFontSize(this.tileSize*1.1),I.setFontColor(this.equalsColor),I.setAlignment("center"),I.svgObject.setAttribute("dominant-baseline","middle");const U=O-this.equalGap/2;return I.setPosition(U,N),this.addChild(I),O=T(i,O,A,y,!1),{width:O,height:F}}}class Zn extends Oe{constructor(){super(),this.type="omdNumberLine",this.valueA=1,this.valueB=2,this.size="large",this.renderType="pie",this.updateLayout()}loadFromJSON(e){typeof e.valueA<"u"&&(this.valueA=e.valueA),typeof e.numerator<"u"&&(this.valueA=e.numerator),typeof e.valueB<"u"&&(this.valueB=e.valueB),typeof e.denominator<"u"&&(this.valueA=e.numerator,this.valueB=e.denominator-e.numerator),typeof e.renderType<"u"&&(this.renderType=e.renderType),typeof e.size<"u"&&(this.size=e.size),this.updateLayout()}setValues(e,t){this.valueA=e,this.valueB=t,this.updateLayout()}setRenderType(e){this.renderType=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}updateLayout(){this.removeAllChildren(),this.renderType=="pie"&&this.renderAsPie(),(this.renderType=="dots"||this.renderType=="dot"||this.renderType=="tile")&&this.renderAsDots(),this.renderType=="bar"&&this.renderAsBar()}renderAsPie(){var e=120;this.size=="large"&&(e=120),this.size=="medium"&&(e=80),this.size=="small"&&(e=40),this.width=e,this.height=e,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);var t=new Oe;t.setPosition(e/2,e/2),this.addChild(t);var r=new Tr;r.setFillColor(Fe.mediumGray),r.setWidthAndHeight(e,e),t.addChild(r);var i=this.valueA/(this.valueA+this.valueB),s=0,a=360*i,o=new lE;o.createPieSlice(e/2,s,a),o.setFillColor("black"),t.addChild(o);for(var l=this.valueA+this.valueB,u=Math.PI*2/l,c=0;c<l;c++){var h=c*u-Math.PI/2,f=Math.cos(h)*e/2,d=Math.sin(h)*e/2,p=new Ut;p.setStrokeColor("white"),p.setEndpoints(0,0,f,d),t.addChild(p)}}renderAsDots(){if(this.size=="large")var e=120,t=150,r=15,i=e/4;if(this.size=="medium")var e=80,t=100,r=12,i=e/4;if(this.size=="small")var e=40,t=50,r=5,i=e/4;var s=new yt;s.setWidthAndHeight(e*2,t),s.setCornerRadius(r),s.setFillColor(Fe.lightGray),this.addChild(s),this.width=s.width,this.height=s.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);for(var l=i,u=i,a=0;a<this.valueA;a++){var o=new Tr;o.setFillColor("black"),o.setWidthAndHeight(r,r),o.setPosition(l,u),this.addChild(o),l+=i,a!=0&&a%3==2&&(l=i,u+=i)}for(var l=i*5,u=i,a=0;a<this.valueB;a++){var o=new Tr;o.setFillColor("black"),o.setWidthAndHeight(r,r),o.setPosition(l,u),this.addChild(o),l+=i,a!=0&&a%3==2&&(l=i*5,u+=i)}var c=new Ut;c.setEndpoints(i*4,i/2,i*4,t-i/2),this.addChild(c)}renderAsBar(){if(this.size=="large")var e=240;if(this.size=="medium")var e=120;if(this.size=="small")var e=80;var t=this.valueA/(this.valueA+this.valueB);this.width=e,this.height=30,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);var r=new yt;r.setWidthAndHeight(e,30),r.setFillColor(Fe.mediumGray),this.addChild(r);var i=new yt;i.setWidthAndHeight(t*e,30),i.setFillColor("black"),this.addChild(i);for(var s=this.valueA+this.valueB,a=e/s,o=1;o<s;o++){var l=o*a,u=new Ut;u.setStrokeColor("white"),u.setEndpoints(l,0,l,30),this.addChild(u)}}}class Qn extends Oe{constructor(){super(),this.type="omdNumberLine",this.title="",this.min=0,this.max=10,this.increment=1,this.showLeftArrow=!1,this.showRightArrow=!1,this.units="",this.hideDefaultNumbers=!1,this.specialNumbers=[],this.totalWidth=320,this.dotValues=[],this.label="",this.updateLayout()}loadFromJSON(e){typeof e.title<"u"&&(this.title=e.title),typeof e.min<"u"&&(this.min=e.min),typeof e.max<"u"&&(this.max=e.max),typeof e.increment<"u"&&(this.increment=e.increment),typeof e.showLeftArrow<"u"&&(this.showLeftArrow=e.showLeftArrow),typeof e.showRightArrow<"u"&&(this.showRightArrow=e.showRightArrow),typeof e.units<"u"&&(this.units=e.units),typeof e.hideDefaultNumbers<"u"&&(this.hideDefaultNumbers=e.hideDefaultNumbers),typeof e.specialNumbers<"u"&&(this.specialNumbers=e.specialNumbers),typeof e.totalWidth<"u"&&(this.totalWidth=e.totalWidth),typeof e.dotValues<"u"&&(this.dotValues=e.dotValues),typeof e.label<"u"&&(this.label=e.label),this.updateLayout()}setMinAndMax(e,t){this.min=e,this.max=t,this.updateLayout()}addNumberDot(e){this.dotValues.push(e),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.title?80:20,t=20,r=10,i=8,s=this.totalWidth,a=s-(this.showLeftArrow?r:0)-(this.showRightArrow?r:0);if(this.width=e+s+t,this.height=70,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.title){const d=new Bt;d.setWidthAndHeight(70,30),d.setFontFamily("Albert Sans"),d.setFontColor("black"),d.setFontSize(12),d.setAlignment("left"),d.setText(this.title),d.setPosition(5,20),this.addChild(d)}const o=e+(this.showLeftArrow?r:0),l=a;if(this.line=new yt,this.line.setWidthAndHeight(l,5),this.line.setPosition(o,22.5),this.line.setFillColor(Fe.mediumGray),this.line.setCornerRadius(2.5),this.addChild(this.line),this.showLeftArrow){const d=new yt;d.setWidthAndHeight(3,5),d.setPosition(o,22.5),d.setFillColor(Fe.mediumGray),this.addChild(d);const p=new Ni,m=25,y=e;p.addPoint(y+r,m-5),p.addPoint(y,m),p.addPoint(y+r,m+5),p.addPoint(y+r,m-5),p.updatePath(),p.setFillColor(Fe.mediumGray),p.setStrokeWidth(0),p.path.setAttribute("fill",Fe.mediumGray),this.addChild(p)}if(this.showRightArrow){const d=new yt;d.setWidthAndHeight(3,5),d.setPosition(o+l-3,22.5),d.setFillColor(Fe.mediumGray),this.addChild(d);const p=new Ni,m=25,y=e+s-r;p.addPoint(y,m-5),p.addPoint(y+r,m),p.addPoint(y,m+5),p.addPoint(y,m-5),p.updatePath(),p.setFillColor(Fe.mediumGray),p.setStrokeWidth(0),p.path.setAttribute("fill",Fe.mediumGray),this.addChild(p)}const u=new Set;if(!this.hideDefaultNumbers)for(let d=this.min;d<=this.max;d+=this.increment)u.add(d);for(const d of this.specialNumbers)d>=this.min&&d<=this.max&&u.add(d);const c=Array.from(u).sort((d,p)=>d-p),h=o+i,f=a-2*i;for(const d of c){const p=(d-this.min)/(this.max-this.min),m=h+p*f,y=new Ut;y.setStrokeColor("black"),y.setStrokeWidth(1),y.setEndpoints(m,20,m,30),this.addChild(y);const v=new Bt;v.setWidthAndHeight(40,30),v.setFontFamily("Albert Sans"),v.setFontColor("black"),v.setFontSize(10),v.setAlignment("center");const S=this.units?`${d}${this.units}`:d.toString();v.setText(S),v.setPosition(m-20,32),this.addChild(v)}for(const d of this.dotValues){if(d<this.min||d>this.max)continue;const p=(d-this.min)/(this.max-this.min),m=h+p*f,y=new Tr;y.setFillColor("black"),y.setStrokeWidth(0),y.setWidthAndHeight(8,8),y.setPosition(m,25),this.addChild(y)}}}class sy extends Oe{constructor(){super(),this.type="omdDoubleNumberLine",this.topNumberLine=new Qn,this.bottomNumberLine=new Qn,this.spacing=30,this.updateLayout()}loadFromJSON(e){typeof e.spacing<"u"&&(this.spacing=e.spacing),typeof e.topNumberLine<"u"&&this.topNumberLine.loadFromJSON(e.topNumberLine),typeof e.bottomNumberLine<"u"&&this.bottomNumberLine.loadFromJSON(e.bottomNumberLine),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.topNumberLine.title?80:20,t=this.bottomNumberLine.title?80:20,r=Math.max(e,t),i=r-e;this.topNumberLine.setPosition(i,0),this.addChild(this.topNumberLine);const s=r-t;this.bottomNumberLine.setPosition(s,this.spacing),this.addChild(this.bottomNumberLine);const a=Math.max(this.topNumberLine.width+i,this.bottomNumberLine.width+s);this.width=a,this.height=70+this.spacing,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Kn extends kt{constructor(e="+"){super(),this.type="omdOperator",this.operator=e,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.operator),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setOperator(e)}loadFromJSON(e){typeof e.operator<"u"&&this.setOperator(e.operator)}setOperator(e){e=="+"&&(this.operator="+"),e=="-"&&(this.operator="−"),e=="/"&&(this.operator="÷"),e=="÷"&&(this.operator="÷"),e=="x"&&(this.operator="×"),e=="*"&&(this.operator="×"),e=="•"&&(this.operator="×"),e=="×"&&(this.operator="×"),e=="="&&(this.operator="="),this.updateLayout()}updateLayout(){var e=this.operator,t=12+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(e),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class Fr extends kt{constructor(e=1,t="",r=1){super(),this.type="omdTerm",this.coefficient=e,this.variable=t,this.exponent=r,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setValue(e,t,r),this.updateLayout()}loadFromJSON(e){typeof e.coefficient<"u"&&(this.coefficient=e.coefficient),typeof e.variable<"u"&&(this.variable=e.variable),typeof e.exponent<"u"&&(this.exponent=e.exponent),this.updateLayout()}setValue(e,t="",r=1){this.coefficient=e,this.variable=t,this.exponent=r,this.updateLayout()}updateLayout(){var e="";this.variable&&this.variable.length!=0?(e=this.coefficient.toString()+this.variable,this.coefficient==1&&(e=this.variable)):e=this.coefficient.toString(),this.exponent&&(this.exponent==1||(this.exponent==2?e+="²":this.exponent==3?e+="³":e+="<sup>"+this.exponent.toString()+"</sup>"));var t=15+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(e),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class ui extends kt{constructor(e=1){super(),this.type="omdNumber",this.value=e,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.value.toString()),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setValue(e)}loadFromJSON(e){typeof e.value<"u"&&(this.value=e.value),this.updateLayout()}setValue(e){this.value=e,this.updateLayout()}updateLayout(){var e=this.value.toString(),t=10+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(this.value.toString()),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class li extends kt{constructor(e="A"){super(),this.type="omdVariable",this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setName(e)}loadFromJSON(e){typeof e.name<"u"&&(this.name=e.name),this.updateLayout()}setName(e){this.name=e,this.updateLayout()}updateLayout(){var e=15+this.name.length*10;this.backRect.setWidthAndHeight(e,30),this.numText.setWidthAndHeight(e,30),this.numText.setText(this.name),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}function ag(n){const e=String(n||"").replace(/\s+/g,"");if(!e)return null;const t=/([+-]?\d*\.?\d+[a-zA-Z]*)|([+-]?[a-zA-Z]+\^?\d*)|([+\-*/=×÷])/g,r=e.match(t)||[];if(r.length===0)return null;const i=[];for(let o of r){if(/^[+\-*/=×÷]$/.test(o)){i.push({omdType:"operator",operator:o.replace("*","×")});continue}const l=o.match(/^([+-]?)(\d*\.?\d*)([a-zA-Z]?)(?:\^(\d+))?$/);if(l){const u=l[1];let c=u==="-"?-1:1;const h=l[2],f=l[3]||"",d=l[4]?Number(l[4]):1;let p=1;h&&h.length>0&&(p=Number(h));let m=!1;if(u){const y=i.length===0,v=!y&&i[i.length-1].omdType==="operator";!y&&!v&&(m=!0)}m&&(i.push({omdType:"operator",operator:u}),c=1),!f&&h?i.push({omdType:"number",value:c*p}):i.push({omdType:"term",coefficient:c*p,variable:f,exponent:d})}else i.push({omdType:"string",name:o})}const s=[];for(let o=0;o<i.length;o++){const l=i[o];if(l.omdType==="operator"&&(l.operator==="+"||l.operator==="-")){const u=s.length===0,c=!u&&s[s.length-1].omdType==="operator";if(u||c){const h=i[o+1];if(h&&(h.omdType==="term"||h.omdType==="number")){h.omdType==="number"?h.value=l.operator==="-"?-h.value:h.value:h.omdType==="term"&&(h.coefficient=l.operator==="-"?-h.coefficient:h.coefficient),o++,s.push(h);continue}}}s.push(l)}const a=[];for(let o=0;o<s.length;o++)a.push(s[o]);return{termsAndOpers:a}}function Kq(n){const t=String(n||"").split("=");if(t.length!==2)return null;const r=t[0].trim(),i=t[1].trim(),s=ag(r),a=ag(i);return!s||!a?null:{leftExpression:s,rightExpression:a}}class zt extends kt{constructor(){super(),this.type="omdExpression",this.termSet=[],this.operatorSet=[],this.inset=5,this.expressionNode=null,this.expressionStack=new qr,this.expressionStack.setPosition(this.inset,0),this.expressionStack.setSpacer(-6),this.addChild(this.expressionStack)}_renderWithExpressionNode(e,t){if(typeof math>"u"||typeof math.parse!="function")throw new Error("math.js is required to parse expression strings");const r=math.parse(e),i=_t(r),s=new i(r);typeof t=="number"&&s.setFontSize&&s.setFontSize(t),s.hideBackgroundByDefault&&s.hideBackgroundByDefault(),s.computeDimensions&&s.computeDimensions(),s.updateLayout&&s.updateLayout(),typeof this.expressionStack.removeAllChildren=="function"?this.expressionStack.removeAllChildren():this.expressionStack.childList=[],this.expressionStack.addChild(s),this.expressionStack.setSpacer(0),this.expressionNode=s,this.updateLayout()}loadFromJSON(e){if(typeof e=="string"){try{this._renderWithExpressionNode(e,e.fontSize);return}catch(o){console.warn("⚠️ omdExpression math.js render failed, falling back to legacy parsing:",(o==null?void 0:o.message)||o)}const a=ag(e);a&&(e=a)}else if(typeof e=="object"&&e.expression&&typeof e.expression=="string"){try{this._renderWithExpressionNode(e.expression,e.fontSize);return}catch(o){console.warn("⚠️ omdExpression math.js render failed, falling back to legacy parsing:",(o==null?void 0:o.message)||o)}const a=ag(e.expression);a&&(e={...e,...a})}if(typeof e.termsAndOpers<"u")for(var t=0;t<e.termsAndOpers.length;t++){var r=e.termsAndOpers[t];if(r.omdType=="term"){var i=new Fr;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="variable"){var i=new li;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="number"){var i=new ui;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="operator"){var s=new Kn;s.loadFromJSON(r),s.hideBackgroundByDefault(),this.operatorSet.push(s),this.expressionStack.addChild(s)}else if(r.omdType=="string"){var i=new Fr(1,r.name,1);i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}}this.updateLayout()}addTerm(e,t="",r="1"){var i=new Fr(e,t,r);this.termSet.push(i),this.expressionStack.addChild(i),this.updateLayout(),i.hideBackgroundByDefault()}addOperator(e){var t=new Kn(e);this.operatorSet.push(t),this.expressionStack.addChild(t),this.updateLayout(),t.hideBackgroundByDefault()}updateLayout(){if(this.expressionNode){const t=this.expressionNode;t.computeDimensions&&t.computeDimensions(),t.updateLayout&&t.updateLayout(),this.expressionStack.doHorizontalLayout(),this.expressionStack.setPosition(this.inset,this.inset);const r=t.width||this.expressionStack.width,i=t.height||this.expressionStack.height;this.backRect.setWidthAndHeight(r+this.inset*2,i+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height;return}this.expressionStack.doHorizontalLayout();var e=this.expressionStack.width;this.backRect.setWidthAndHeight(e+this.inset*2,30),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height}}class SE extends kt{constructor(e="string"){super(),this.type="omdString",this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setName(e)}setName(e){this.name=e;var t=15+this.name.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(this.name),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}loadFromJSON(e){if(typeof e=="string"){this.setName(e);return}if(e&&typeof e.name=="string"){this.setName(e.name);return}}}class Ba extends kt{constructor(){super(),this.type="omdPowerExpression",this.leftExpression=null,this.rightExpression=null,this.centerEquation=!0,this.inset=5,this.equationStack=new qr,this.equationStack.setSpacer(-7),this.addChild(this.equationStack),this.leftHolder=new Oe,this.equationStack.addChild(this.leftHolder),this.equalSign=new Kn("="),this.equationStack.addChild(this.equalSign),this.rightHolder=new Oe,this.equationStack.addChild(this.rightHolder),this.equationNode=null}loadFromJSON(e){if(typeof e.equation=="string"&&e.equation.trim())try{this._renderWithEquationNode(e.equation,e.fontSize);return}catch(r){console.warn("⚠️ omdEquation math.js render failed, falling back to legacy parsing:",(r==null?void 0:r.message)||r)}function t(r){return r&&r.termsAndOpers&&Array.isArray(r.termsAndOpers)&&r.termsAndOpers.forEach(i=>{i&&i.omdType==="operator"&&i.symbol&&(i.symbol==="−"&&(i.symbol="-"),i.symbol==="+"&&(i.symbol="+"))}),r}if(typeof e.leftExpression<"u"&&e.leftExpression){let r=e.leftExpression;r=t(r),r.omdType=="expression"?this.leftExpression=new zt:r.omdType=="number"?this.leftExpression=new ui:r.omdType=="variable"?this.leftExpression=new li:r.omdType=="term"?this.leftExpression=new Fr:(r.omdType=="string"||typeof r=="string")&&(this.leftExpression=new zt),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&r&&typeof r=="object"&&this.leftExpression.loadFromJSON(r),this.leftExpression&&(this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression))}if(typeof e.rightExpression<"u"&&e.rightExpression){let r=e.rightExpression;r=t(r),r.omdType=="expression"?this.rightExpression=new zt:r.omdType=="number"?this.rightExpression=new ui:r.omdType=="variable"?this.rightExpression=new li:r.omdType=="term"?this.rightExpression=new Fr:(r.omdType=="string"||typeof r=="string")&&(this.rightExpression=new zt),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&r&&typeof r=="object"&&this.rightExpression.loadFromJSON(r),this.rightExpression&&(this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression))}if((!this.leftExpression||!this.rightExpression)&&typeof e.equation=="string"){const r=Kq(e.equation);if(r)this.leftExpression||(this.leftExpression=new zt),this.rightExpression||(this.rightExpression=new zt),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&this.leftExpression.loadFromJSON(r.leftExpression),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&this.rightExpression.loadFromJSON(r.rightExpression),this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression);else{const i=String(e.equation||"").split("="),s=(i[0]||"").trim(),a=(i[1]||"").trim();this.leftExpression||(this.leftExpression=new SE(s||"")),this.rightExpression||(this.rightExpression=new SE(a||"")),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&typeof s=="string"&&this.leftExpression.loadFromJSON(s),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&typeof a=="string"&&this.rightExpression.loadFromJSON(a),this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression)}}this.equalSign&&typeof this.equalSign.hideBackgroundByDefault=="function"&&this.equalSign.hideBackgroundByDefault(),this.leftExpression&&typeof this.leftExpression.hideBackgroundByDefault=="function"&&this.leftExpression.hideBackgroundByDefault(),this.rightExpression&&typeof this.rightExpression.hideBackgroundByDefault=="function"&&this.rightExpression.hideBackgroundByDefault(),this.centerEquation=!1,this.updateLayout()}_renderWithEquationNode(e,t){if(typeof math>"u"||typeof math.parse!="function")throw new Error("math.js is required to parse equation strings");const r=ut.fromString(e);typeof t=="number"&&r.setFontSize&&r.setFontSize(t),r.hideBackgroundByDefault&&r.hideBackgroundByDefault(),r.computeDimensions&&r.computeDimensions(),r.updateLayout&&r.updateLayout(),typeof this.equationStack.removeAllChildren=="function"?this.equationStack.removeAllChildren():this.equationStack.childList=[],this.equationStack.addChild(r),this.equationStack.setSpacer(0),this.equationNode=r,this.leftExpression=null,this.rightExpression=null,this.centerEquation=!1,this.updateLayout()}setLeftAndRightExpressions(e,t){this.leftExpression=e,this.leftHolder.removeAllChildren(),this.leftHolder.addChild(e),this.rightExpression=t,this.rightHolder.removeAllChildren(),this.rightHolder.addChild(t),this.equalSign.hideBackgroundByDefault(),this.leftExpression.hideBackgroundByDefault(),this.rightExpression.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){if(this.equationNode){const i=this.equationNode;i.computeDimensions&&i.computeDimensions(),i.updateLayout&&i.updateLayout(),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,this.inset);const s=i.width||this.equationStack.width,a=i.height||this.equationStack.height;this.backRect.setWidthAndHeight(s+this.inset*2,a+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);return}this.leftHolder.setWidthAndHeight(this.leftExpression.width,this.leftExpression.height),this.rightHolder.setWidthAndHeight(this.rightExpression.width,this.rightExpression.height),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,this.inset);var e=this.equationStack.width,t=this.equationStack.height;if(this.backRect.setWidthAndHeight(e+this.inset*2,t+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.centerEquation){var r=this.leftExpression.width+this.equalSign.width*.5;this.backRect.setPosition(-1*r+this.inset/2,0),this.equationStack.setPosition(-1*r+this.inset+this.inset/2,this.inset)}}}class qs extends kt{constructor(){super(),this.type="omdPowerExpression",this.expression=null,this.exponent=null,this.expressionHolder=new Oe,this.addChild(this.expressionHolder),this.exponentHolder=new Oe,this.addChild(this.exponentHolder)}loadFromJSON(e){typeof e.baseExpression<"u"&&(e.baseExpression.omdType=="expression"&&(this.expression=new zt),e.baseExpression.omdType=="number"&&(this.expression=new ui),e.baseExpression.omdType=="variable"&&(this.expression=new li),e.baseExpression.omdType=="term"&&(this.expression=new Fr),this.expression.loadFromJSON(e.baseExpression),this.expressionHolder.removeAllChildren(),this.expressionHolder.addChild(this.expression)),typeof e.exponentExpression<"u"&&(e.exponentExpression.omdType=="expression"&&(this.exponent=new zt),e.exponentExpression.omdType=="number"&&(this.exponent=new ui),e.exponentExpression.omdType=="variable"&&(this.exponent=new li),e.exponentExpression.omdType=="term"&&(this.exponent=new Fr),this.exponent.loadFromJSON(e.exponentExpression),this.exponentHolder.removeAllChildren(),this.exponentHolder.addChild(this.exponent)),this.updateLayout()}setExpressionAndPower(e,t){this.expression=e,this.expressionHolder.removeAllChildren(),this.expressionHolder.addChild(e),this.exponent=t,this.exponentHolder.removeAllChildren(),this.exponentHolder.addChild(t),this.updateLayout()}updateLayout(){this.expressionHolder.setPosition(0,0),this.exponentHolder.setPosition(this.expression.width-10,-15),this.exponentHolder.setScale(.7)}}class ka extends kt{constructor(){super(),this.type="omdPowerExpression",this.numeratorExpression=null,this.denominatorExpression=null,this.numeratorHolder=new jsvgGroup,this.addChild(this.numeratorHolder),this.denominatorHolder=new jsvgGroup,this.addChild(this.denominatorHolder),this.dividerLine=new jsvgLine,this.setStrokeWidth(2),this.setStrokeColor("black"),this.addChild(this.dividerLine)}loadFromJSON(e){typeof e.numeratorExpression<"u"&&(e.numeratorExpression.omdType=="expression"&&(this.numeratorExpression=new zt),e.numeratorExpression.omdType=="number"&&(this.numeratorExpression=new ui),e.numeratorExpression.omdType=="variable"&&(this.numeratorExpression=new li),e.numeratorExpression.omdType=="term"&&(this.numeratorExpression=new Fr),this.numeratorExpression.loadFromJSON(e.numeratorExpression),this.numeratorHolder.removeAllChildren(),this.numeratorHolder.addChild(this.numeratorExpression)),typeof e.denominatorExpression<"u"&&(e.denominatorExpression.omdType=="expression"&&(this.denominatorExpression=new zt),e.denominatorExpression.omdType=="number"&&(this.denominatorExpression=new ui),e.denominatorExpression.omdType=="variable"&&(this.denominatorExpression=new li),e.denominatorExpression.omdType=="term"&&(this.denominatorExpression=new Fr),this.denominatorExpression.loadFromJSON(e.denominatorExpression),this.denominatorHolder.removeAllChildren(),this.denominatorHolder.addChild(this.denominatorExpression)),this.updateLayout()}setNumeratorAndDenominator(e,t){this.numeratorExpression=e,this.numeratorHolder.removeAllChildren(),this.numeratorHolder.addChild(e),this.denominatorExpression=t,this.denominatorHolder.removeAllChildren(),this.denominatorHolder.addChild(t),this.numeratorExpression.hideBackgroundByDefault(),this.denominatorExpression.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){this.numeratorHolder.setPosition(5,0),this.denominatorHolder.setPosition(5,30);var e=this.numeratorExpression.width;this.denominatorExpression.width>e&&(e=this.denominatorExpression.width);var t=e/2-this.numeratorExpression.width/2+5;this.numeratorHolder.setPosition(t,0),t=e/2-this.denominatorExpression.width/2+5,this.denominatorHolder.setPosition(t,30),this.dividerLine.setEndpoints(5,30,e+5,30),this.backRect.setWidthAndHeight(e+10,60),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class Pa extends kt{constructor(){super(),this.type="omdPowerExpression",this.leftExpression=null,this.rightExpresion=null,this.functionName="f",this.inputVariableArray=[],this.centerEquation=!1,this.inset=5,this.equationStack=new qr,this.equationStack.setSpacer(-7),this.addChild(this.equationStack),this.leftHolder=new Oe,this.equationStack.addChild(this.leftHolder),this.equalSign=new Kn("="),this.equationStack.addChild(this.equalSign),this.rightHolder=new Oe,this.equationStack.addChild(this.rightHolder)}loadFromJSON(e){typeof e.name<"u"&&(this.functionName=e.name),typeof e.inputVariables<"u"&&(this.inputVariableArray=e.inputVariables),typeof e.expression<"u"&&(e.expression.omdType=="expression"&&(this.rightExpresion=new zt),this.rightExpresion.loadFromJSON(e.expression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpresion)),this.leftHolder.removeAllChildren();var t=this.functionName+"("+this.inputVariableArray[0]+")";this.leftExpression=new zt,this.leftExpression.loadFromJSON(t),this.leftHolder.addChild(this.leftExpression),this.updateLayout()}setNameVariableAndExpression(e,t,r){this.leftHolder.removeAllChildren();var i=e+"("+t+")";this.leftExpression=new zt,this.leftExpression.loadFromJSON(i),this.leftHolder.addChild(this.leftExpression),this.rightExpresion=r,this.rightHolder.removeAllChildren(),this.rightHolder.addChild(r),this.equalSign.hideBackgroundByDefault(),this.leftExpression.hideBackgroundByDefault(),this.rightExpresion.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){this.leftHolder.setWidthAndHeight(this.leftExpression.width,this.leftExpression.height),this.rightHolder.setWidthAndHeight(this.rightExpresion.width,this.rightExpresion.height),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,0);var e=this.equationStack.width;if(this.backRect.setWidthAndHeight(e+this.inset*2,30),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.centerEquation){var t=this.leftExpression.width+this.equalSign.width*.5;this.backRect.setPosition(-1*t+this.inset/2,0),this.equationStack.setPosition(-1*t+this.inset+this.inset/2,0)}}}class za extends Oe{constructor(){super(),this.type="omdNumberLine",this.size="medium",this.divisions=5,this.arrowPosition=1,this.updateLayout()}loadFromJSON(e){typeof e.divisions<"u"&&(this.divisions=e.divisions),typeof e.arrowPosition<"u"&&(this.arrowPosition=e.arrowPosition),typeof e.size<"u"&&(this.size=e.size),this.updateLayout()}setDivisions(e){this.divisions=e,this.updateLayout()}setRenderType(e){this.renderType=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}setArrowPosition(e){this.arrowPosition=e,this.updateLayout()}updateLayout(){this.removeAllChildren();var e=new Oe;this.addChild(e);var t=120,r=14;this.size=="large"&&(t=120,r=14),this.size=="medium"&&(t=80,r=12),this.size=="small"&&(t=40,r=10);var i=new Tr;i.setFillColor(Fe.mediumGray),i.setWidthAndHeight(t,t),e.addChild(i),e.setPosition(t/2,t/2);for(var s=this.divisions,a=Math.PI*2/s,o=0;o<s;o++){var d=o*a-Math.PI/2,u=Math.cos(d)*t/2,c=Math.sin(d)*t/2,l=new Ut;l.setStrokeColor("white"),l.setEndpoints(0,0,u,c),e.addChild(l);var d=(o+.5)*a-Math.PI/2,u=Math.cos(d)*t*.4,c=Math.sin(d)*t*.4,h=new Bt;h.setWidthAndHeight(30,30),h.setText((o+1).toString()),h.setFontFamily("Albert Sans"),h.setFontColor("black"),h.setFontSize(r),h.setAlignment("center"),h.setPosition(u-15,c-7),e.addChild(h)}var f=t*.4;this.arrow=new Ni,this.arrow.addPoint(0,0),this.arrow.addPoint(f*.8,f*.1),this.arrow.addPoint(f,0),this.arrow.addPoint(f*.8,f*-.1),this.arrow.addPoint(0,0),this.arrow.updatePath(),this.arrow.setFillColor("black"),this.arrow.setOpacity(.8),e.addChild(this.arrow);var d=-90+360/this.divisions*(this.arrowPosition-.5);this.arrow.setRotation(d),this.width=t,this.height=t,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class e9 extends Oe{constructor(){super(),window.addEventListener("resize",this.onResize.bind(this)),window.addEventListener("keydown",this.onKeydown.bind(this)),this.setPosition(0,-50);var e=new ui(100);e.setPosition(100,100),this.addChild(e);var t=new li("x");t.setPosition(100,150),this.addChild(t);var v=new Fr(3,"x",2);v.setPosition(100,200),this.addChild(v);var S=new Kn("*");S.setPosition(100,250),this.addChild(S);var r=new zt;r.loadFromJSON(expressionSample),r.setPosition(100,300),this.addChild(r);var i=new qs,s=new zt;s.addTerm(7),s.addOperator("-"),s.addTerm(5,"x"),i.setExpressionAndPower(s,new Fr(3,"x",2)),i.setPosition(100,370),this.addChild(i);var a=new ka,o=new zt;o.addTerm(7),o.addOperator("-"),o.addTerm(5,"x");var l=new zt;l.addTerm(3,"x"),l.addOperator("+"),l.addTerm(2),l.addOperator("-"),l.addTerm(3);var u=new qs,c=new zt;c.addTerm("4","x","3"),c.addOperator("x"),c.addTerm("5","y","2"),u.setExpressionAndPower(l,c),a.setNumeratorAndDenominator(l,o),a.setPosition(100,440),this.addChild(a);var h=new Pa,p=new zt;p.addTerm(3,"x"),p.addOperator("+"),p.addTerm(2),h.setNameVariableAndExpression("f","x",p),h.setPosition(100,540),this.addChild(h);var f=new Ba,d=new zt;d.addTerm(7),d.addOperator("-"),d.addTerm(5,"x");var p=new zt;p.addTerm(3,"x"),p.addOperator("+"),p.addTerm(2),f.setLeftAndRightExpressions(d,p),f.setPosition(100,610),this.addChild(f);var m=new Qn;m.loadFromJSON(numberLineSample),m.setPosition(400,100),m.updateLayout(),this.addChild(m);var v=new mn;v.loadFromJSON(tapeDiagramSample),v.setPosition(400,200),this.addChild(v),v=new mn,v.loadFromJSON(tapeDiagramSample2),v.setPosition(400,300),this.addChild(v);var y=new Oa;y.loadFromJSON(balanceHangerSample2),y.setPosition(300,100),this.addChild(y);var v=new $i;v.setValue(8),v.setSize("medium"),v.setPosition(380,620),this.addChild(v);var S=new Zn;S.setValues(3,5),S.setSize("large"),S.setPosition(490,610),S.setRenderType("pie"),this.addChild(S);var S=new Zn;S.setValues(3,5),S.setSize("medium"),S.setPosition(620,620),S.setRenderType("dots"),this.addChild(S);var S=new Zn;S.setValues(3,5),S.setSize("large"),S.setPosition(520,740),S.setRenderType("bar"),this.addChild(S);var g=new $s;g.setPosition(350,380),g.setGraphFunction("1/2/(x)"),g.setDotValues([[1,1],[3,2],[-3,2]]),g.setSize("medium"),this.addChild(g),g=new $s,g.setPosition(570,380),g.loadFromJSON(planeWithShapes),this.addChild(g);var b=new za;b.setPosition(810,610),b.setDivisions(8),b.setArrowPosition(3),b.setSize("large"),this.addChild(b),b=new ks,b.setPosition(340,860),b.loadFromJSON(rightTriangleSample),this.addChild(b),b=new Ps,b.setPosition(420,860),b.loadFromJSON(isoscelesTriangleSample),this.addChild(b),b=new zs,b.setPosition(470,860),b.loadFromJSON(rectangleSample),this.addChild(b),b=new Rs,b.setPosition(650,830),b.loadFromJSON(ellipseSample),this.addChild(b),b=new Ls,b.setPosition(750,830),b.loadFromJSON(circleSample),this.addChild(b),b=new Is,b.setPosition(830,830),b.loadFromJSON(regularPolygonSample),this.addChild(b),this.inputField=new jsvgTextArea,this.inputField.setPlaceholderText("please enter your request here"),this.inputField.setWidthAndHeight(400,100),this.inputField.setPosition(800,100),this.inputField.setFontFamily("Albert Sans"),this.inputField.setFontColor("black"),this.inputField.setFontSize(14),this.inputField.div.style.backgroundColor=Fe.lightGray,this.inputField.div.style.border="0px",this.inputField.div.style.padding="10px",this.addChild(this.inputField),this.inputButton=new jsvgButton,this.inputButton.setText("submit"),this.inputButton.setFillColor(Fe.lightGray),this.inputButton.setPosition(800,220),this.inputButton.setClickCallback(this.handleSubmitClick.bind(this)),this.addChild(this.inputButton),this.responseText=new jsvgTextBox,this.responseText.setText(""),this.responseText.setWidthAndHeight(400,30),this.responseText.setPosition(920,225),this.responseText.setFontFamily("Albert Sans"),this.responseText.setFontColor(Fe.darkGray),this.responseText.setFontSize(14),this.addChild(this.responseText),this.AIholder=new Oe,this.AIholder.setPosition(800,350),this.addChild(this.AIholder),this.onResize()}onKeydown(e){}update(){super.update(),window.equatorScale=1.5}onResize(){}handleSubmitClick(e){this.responseText.setText("working...");var t=this.inputField.getText();console.log(t),this.fetchAI(t)}handleAIResponse(e){this.AIholder.removeAllChildren();var t=null;if(e.omdType=="number")var t=new ui;if(e.omdType=="variable")var t=new li;if(e.omdType=="operator")var t=new Kn;if(e.omdType=="term")var t=new Fr;if(e.omdType=="expression")var t=new zt;if(e.omdType=="powerExpression")var t=new qs;if(e.omdType=="rationalExpression")var t=new ka;if(e.omdType=="function")var t=new Pa;if(e.omdType=="equation")var t=new Ba;if(e.omdType=="numberLine")var t=new Qn;if(e.omdType=="balanceHanger"){var t=new Oa;t.setPosition(150,0)}if(e.omdType=="tapeDiagram")var t=new mn;if(e.omdType=="numberTile")var t=new $i;if(e.omdType=="ratioChart")var t=new Zn;if(e.omdType=="coordinatePlane")var t=new $s;if(e.omdType=="spinner")var t=new za;if(e.omdType=="rightTriangle")var t=new ks;if(e.omdType=="isoscelesTriangle")var t=new Ps;if(e.omdType=="rectangle")var t=new zs;if(e.omdType=="ellipse")var t=new Rs;if(e.omdType=="circle")var t=new Ls;if(e.omdType=="regularPolygon")var t=new Is;t.loadFromJSON(e),this.AIholder.addChild(t)}fetchAI(e){var t="";window.location.hostname.includes("localhost")?t="http://localhost:8888/.netlify/functions/ai-omd-lookup/":t="https://teaching-lab-omd.netlify.app/.netlify/functions/ai-omd-lookup/",t+="?topic='"+e+"'",fetch(t).then(r=>r.text()).then(r=>{var i=r;i=i.replaceAll("`",""),i=i.replaceAll("json","");try{var s=JSON.parse(i);this.responseText.setText(""),this.handleAIResponse(s)}catch{console.log(i),console.log(">>> data not parse-able"),this.responseText.setText("An error occured. Please try again.")}})}}class NE extends Oe{constructor(){super(),this.type="omdProblem",this.theText="",this.problemText=new Bt,this.problemText.setWidthAndHeight(250,30),this.problemText.setText("this it the problem text"),this.problemText.setFontFamily("Albert Sans"),this.problemText.setFontColor("black"),this.problemText.setFontSize(18),this.addChild(this.problemText)}loadFromJSON(e,t=null){if(console.log(e),typeof e.problemText<"u"&&(this.theText=e.problemText),typeof e.visualization<"u"&&(console.log(e),this.visualJSON=e.visualiation,console.log(this.visualJSON),console.log("testing 1 "),e.svgElement))try{let s=function(){let C=document.getElementById("_omd_measuring_svg");return C||(C=document.createElementNS(i,"svg"),C.setAttribute("id","_omd_measuring_svg"),C.style.position="absolute",C.style.left="-9999px",C.style.top="-9999px",C.style.width="1px",C.style.height="1px",C.style.visibility="hidden",document.body.appendChild(C)),C};this.problemText.setText(this.theText);const r=10,i="http://www.w3.org/2000/svg",o=e.svgElement.cloneNode(!0);let l=null;try{const C=o.querySelector&&o.querySelector("clipPath rect");if(C){const A=parseFloat(C.getAttribute("x")||"0"),E=parseFloat(C.getAttribute("y")||"0"),F=parseFloat(C.getAttribute("width")||"0"),O=parseFloat(C.getAttribute("height")||"0");F>0&&O>0&&(l={x:A,y:E,width:F,height:O})}}catch{}if(!l)try{let C=null;if(o.getAttribute&&(C=o.getAttribute("viewBox")),!C){const A=o.querySelector&&o.querySelector("svg");A&&A.getAttribute&&(C=A.getAttribute("viewBox"))}if(C){const A=C.trim().split(/\s+/).map(Number);A.length===4&&(l={x:A[0],y:A[1],width:A[2],height:A[3]})}}catch{}if(!l){const C=s(),A=document.createElementNS(i,"g");A.appendChild(o),C.appendChild(A);try{const E=A.getBBox();console.debug("omdProblem: measured bbox from wrapper",E),E&&E.width>0&&E.height>0&&(l={x:E.x,y:E.y,width:E.width,height:E.height})}catch{}try{C.removeChild(A)}catch{}}l||(l={x:0,y:0,width:250,height:250});const u=e&&typeof e.cropMargin=="number"?e.cropMargin:6;l={x:Math.max(0,l.x-u),y:Math.max(0,l.y-u),width:l.width+u*2,height:l.height+u*2},console.debug("omdProblem: final crop chosen (expanded)",l);const h=document.createElementNS(i,"svg");h.setAttribute("width",String(l.width)),h.setAttribute("height",String(l.height)),h.setAttribute("viewBox",`0 0 ${l.width} ${l.height}`);const f=document.createElementNS(i,"g");f.setAttribute("transform","translate(-55, -80)"),f.appendChild(o),h.appendChild(f);let d=0;try{this.problemText.height?d=this.problemText.height:this.problemText.svgObject&&this.problemText.svgObject.getBBox?d=this.problemText.svgObject.getBBox().height:d=30}catch{d=30}let p=300,m=null,y=8;try{e&&e.containerInfo?(typeof e.containerInfo.width=="number"&&(p=e.containerInfo.width),typeof e.containerInfo.offsetY=="number"&&(m=e.containerInfo.offsetY),typeof e.containerInfo.innerPadding=="number"&&(y=e.containerInfo.innerPadding)):this.width?p=this.width:this.problemText&&this.problemText.width&&(p=Math.max(300,this.problemText.width))}catch{p=300}const v=Math.round(m!==null?m+r:d+r),S=y,g=Math.max(20,p-S*2);let b=1;l.width>g&&(b=g/l.width);const w=Math.round(l.width*b),x=Math.round(l.height*b);h.setAttribute("width",String(w)),h.setAttribute("height",String(x));let N=Math.max(S,Math.round((p-w)/2));console.debug("omdProblem: containerWidth, desiredX, desiredY",{containerWidth:p,desiredX:N,desiredY:v,cropWidth:l.width,cropHeight:l.height,scaledWidth:w,scaledHeight:x,scale:b});const D=document.createElementNS(i,"g");if(D.appendChild(h),D.setAttribute("transform",`translate(${N}, ${v})`),this.svgObject.appendChild(D),e&&e.debugPlacement)try{const C=document.createElementNS(i,"rect");C.setAttribute("x","0"),C.setAttribute("y","0"),C.setAttribute("width",String(w)),C.setAttribute("height",String(x)),C.setAttribute("fill","none"),C.setAttribute("stroke","rgba(255,0,0,0.9)"),C.setAttribute("stroke-width","2"),C.setAttribute("pointer-events","none"),D.appendChild(C)}catch(C){console.warn("omdProblem: failed to add debugPlacement rect",C)}this.updateLayout();return}catch(r){console.warn("omdProblem: svgElement fast-path failed, falling back to regenerate:",r)}this.updateLayout()}setName(e){this.name=e,this.updateLayout()}updateLayout(){this.problemText.setText(this.theText);let e=400,t=130;try{if(this.problemText.width&&(e=this.problemText.width),this.problemText.height)t=this.problemText.height;else if(this.problemText.svgObject&&this.problemText.svgObject.getBBox){const a=this.problemText.svgObject.getBBox();a.width&&(e=a.width),a.height&&(t=a.height)}}catch{}let r=0;try{for(let a=0;a<this.children.length;a++){const o=this.children[a];if(o!==this.problemText&&o&&o.svgObject&&o.svgObject.getBBox){const l=o.svgObject.getBBox();r=Math.max(r,l.height+20)}}}catch{r=0}const i=Math.max(300,e),s=Math.max(200,t+r+20);this.setWidthAndHeight(i,s)}}class t9 extends Oe{constructor(){super(),console.log("canvas!!!"),window.theApp=this,window.addEventListener("resize",this.onResize.bind(this)),window.addEventListener("keydown",this.onKeydown.bind(this)),this.setPosition(0,-50),this.inputField=new fE,this.inputField.setPlaceholderText("please enter your request here"),this.inputField.setWidthAndHeight(600,100),this.inputField.setPosition(100,100),this.inputField.setFontFamily("Albert Sans"),this.inputField.setFontColor("black"),this.inputField.setFontSize(18),this.inputField.div.style.backgroundColor="#FFDD00",this.inputField.div.style.border="0px",this.inputField.div.style.padding="10px",this.addChild(this.inputField),this.inputButton=new Xn,this.inputButton.setText("submit"),this.inputButton.setFillColor(Fe.lightGray),this.inputButton.setPosition(100,220),this.inputButton.setClickCallback(this.handleSubmitClick.bind(this)),this.addChild(this.inputButton),this.responseText=new Bt,this.responseText.setText(""),this.responseText.setWidthAndHeight(400,30),this.responseText.setPosition(100,260),this.responseText.setFontFamily("Albert Sans"),this.responseText.setFontColor(Fe.darkGray),this.responseText.setFontSize(14),this.addChild(this.responseText),this.AIholder=new Oe,this.AIholder.setPosition(100,350),this.addChild(this.AIholder),this.onResize()}onKeydown(e){}update(){super.update(),window.equatorScale=1.5}onResize(){}handleSubmitClick(e){this.responseText.setText("working...");var t=this.inputField.getText();console.log(t),this.fetchAI(t)}handleAIResponse(e){var t=null;if(e.omdType=="number")var t=new ui;if(e.omdType=="variable")var t=new li;if(e.omdType=="operator")var t=new Kn;if(e.omdType=="term")var t=new Fr;if(e.omdType=="expression")var t=new zt;if(e.omdType=="powerExpression")var t=new qs;if(e.omdType=="rationalExpression")var t=new ka;if(e.omdType=="function")var t=new Pa;if(e.omdType=="equation")var t=new Ba;if(e.omdType=="numberLine")var t=new Qn;if(e.omdType=="balanceHanger"){var t=new Oa;t.setPosition(150,0)}if(e.omdType=="tapeDiagram")var t=new mn;if(e.omdType=="numberTile")var t=new $i;if(e.omdType=="ratioChart")var t=new Zn;if(e.omdType=="coordinatePlane")var t=new $s;if(e.omdType=="spinner")var t=new za;if(e.omdType=="rightTriangle")var t=new ks;if(e.omdType=="isoscelesTriangle")var t=new Ps;if(e.omdType=="rectangle")var t=new zs;if(e.omdType=="ellipse")var t=new Rs;if(e.omdType=="circle")var t=new Ls;if(e.omdType=="regularPolygon")var t=new Is;if(e.omdType=="problem")var t=new NE;t.loadFromJSON(e);var r=new r9;return r.addObject(t),this.AIholder.addChild(r),r}fetchAI(e){var t="";window.location.hostname.includes("localhost")?t="http://localhost:8888/.netlify/functions/ai-omd-lookup/":t="https://teaching-lab-omd.netlify.app/.netlify/functions/ai-omd-lookup/",t+="?topic='"+e+"'",fetch(t).then(r=>r.text()).then(r=>{var i=r;i=i.replaceAll("`",""),i=i.replaceAll("json",""),console.log("=== pre-parse ==="),console.log(i);try{var s=JSON.parse(i);console.log("=== parsedData ==="),console.log(s),this.responseText.setText(""),this.handleAIResponse(s)}catch{console.log(i),console.log(">>> data not parse-able"),this.responseText.setText("An error occured. Please try again.")}})}}class r9 extends Oe{constructor(){super(),this.clickRect=new Tr,this.clickRect.setWidthAndHeight(40,40),this.clickRect.setPosition(10,10),this.clickRect.setFillColor("transparent"),this.addChild(this.clickRect),this.clickRect.svgObject.onmousedown=this.handleMouseDown.bind(this),this.clickRect.svgObject.ontouchstart=this.handleMouseDown.bind(this),this.clickRect.svgObject.style.cursor="pointer",this.backRect=new Tr,this.backRect.setWidthAndHeight(20,20),this.backRect.setPosition(10,10),this.backRect.setFillColor("#DDDDDD"),this.addChild(this.backRect),this.backRect.svgObject.onmousedown=this.handleMouseDown.bind(this),this.backRect.svgObject.ontouchstart=this.handleMouseDown.bind(this),this.backRect.svgObject.style.cursor="pointer"}addObject(e){this.theObject=e,e.setPosition(10,10),this.addChild(e)}handleMouseDown(e){if(!this.visible)return;function t(i){i.preventDefault();var s,a;if(i.touches&&i.touches.length>=1?(s=i.touches[0].clientX,a=i.touches[0].clientY):(s=i.clientX,a=i.clientY),this.oldMouseX&&this.oldMouseY){var o=s-this.oldMouseX,l=a-this.oldMouseY,u=this.xpos+o,c=this.ypos+l;this.setPosition(u,c)}this.oldMouseX=s,this.oldMouseY=a}function r(i){window.onmousemove=null,window.ontouchmove=null,window.onmouseup=null,window.ontouchend=null,this.oldMouseX=0,this.oldMouseY=0}window.onmousemove=t.bind(this),window.ontouchmove=t.bind(this),window.onmouseup=r.bind(this),window.ontouchend=r.bind(this)}}const CE={small:14,medium:20,large:28};class ay extends kt{constructor(){super(),this.type="omdLabel",this.text="",this.size="medium",this.textBox=new Bt,this.textBox.setFontFamily("Albert Sans"),this.textBox.setFontColor("black"),this.textBox.setVerticalCentering(),this.textBox.setAlignment("left"),this.addChild(this.textBox),this.backRect.setFillColor("transparent"),this.backRect.setOpacity(0)}loadFromJSON(e){typeof e=="string"?this.text=e:(typeof e.text<"u"&&(this.text=e.text),typeof e.size<"u"&&(this.size=e.size),typeof e.color<"u"&&this.textBox.setFontColor(e.color)),this.updateLayout()}updateLayout(){const e=CE[this.size]??CE.medium;this.textBox.setFontSize(e);const t=8,r=e*.58,i=Math.max(60,Math.ceil(String(this.text).length*r)+t*2),s=e+t*2;this.textBox.setWidthAndHeight(i,s),this.textBox.setText(this.text??""),this.backRect.setWidthAndHeight(i,s),this.setWidthAndHeight(i,s),this.width=i,this.height=s}hideBackgroundByDefault(){this.backRect.setOpacity(0)}}class i9 extends j0{constructor(){super(),this.setViewbox(400,400),this.setBackgroundColor("#F8F8F4")}setCanvasSize(e,t){this.setViewbox(e,t)}setBackgroundColor(e){this.svgObject.style.backgroundColor=e}generateGraphic(e){if(this.removeAllChildren(),!e||!e.omdType){console.error("Invalid jsonData: missing omdType",e);return}var t=null;const r=e.omdType;switch(r){case"number":t=new ui;break;case"variable":t=new li;break;case"operator":t=new Kn;break;case"term":t=new Fr;break;case"expression":t=new zt;break;case"powerExpression":t=new qs;break;case"rationalExpression":t=new ka;break;case"function":t=new Pa;break;case"equation":if(e.equation&&typeof e.equation=="string"&&e.equation.includes("="))try{t=ut.fromString(e.equation),typeof t.computeDimensions=="function"&&t.computeDimensions(),typeof t.updateLayout=="function"&&t.updateLayout(),t.setPosition(0,30),this.addChild(t);return}catch(i){console.warn("⚠️ omdEquationNode failed, falling back to legacy omdEquation:",i)}if(e.leftExpression||e.rightExpression)console.log("📝 Using legacy omdEquation for complex JSON structure"),t=new Ba;else{console.warn("⚠️ Equation data missing both equation string and expression structure");return}break;case"numberLine":t=new Qn;break;case"doubleNumberLine":t=new sy;break;case"balanceHanger":t=new Oa;break;case"tapeDiagram":t=new mn;break;case"doubleTapeDiagram":t=new iy;break;case"numberTile":t=new $i;break;case"ratioChart":t=new Zn;break;case"coordinatePlane":t=new $s;break;case"spinner":t=new za;break;case"table":t=new ty;break;case"tileEquation":t=new ny;break;case"rightTriangle":t=new ks;break;case"isoscelesTriangle":t=new Ps;break;case"rectangle":t=new zs;break;case"ellipse":t=new Rs;break;case"circle":t=new Ls;break;case"regularPolygon":t=new Is;break;case"label":t=new ay;break;default:console.error(`Unsupported OMD type: ${r}. Available types: number, variable, operator, term, expression, powerExpression, rationalExpression, function, equation, numberLine, balanceHanger, tapeDiagram, numberTile, ratioChart, coordinatePlane, spinner, table, tileEquation, rightTriangle, isoscelesTriangle, rectangle, ellipse, circle, regularPolygon`);return}if(!t){console.error(`Failed to create OMD object for type: ${r}`);return}t.setPosition(0,30),r==="balanceHanger"&&t.setPosition(150,30);try{t.loadFromJSON(e)}catch(i){console.error(`Error loading JSON data for ${r}:`,i),console.error("JSON data:",e);return}this.addChild(t)}getSVG(){return this.svgObject}getDiv(){const e=document.createElement("div");return e.style.width=this.width+"px",e.style.height=this.height+"px",e.style.overflow="visible",e.appendChild(this.svgObject),e}}const og={balanceHanger:Oa,table:ty,tapeDiagram:mn,doubleTapeDiagram:iy,coordinatePlane:$s,numberLine:Qn,doubleNumberLine:sy,numberTile:$i,ratioChart:Zn,tileEquation:ny,spinner:za,equation:Ba,expression:zt,term:Fr,number:ui,variable:li,powerExpression:qs,rationalExpression:ka,function:Pa,rightTriangle:ks,isoscelesTriangle:Ps,rectangle:zs,ellipse:Rs,circle:Ls,regularPolygon:Is,label:ay};function n9(n){if(!n||typeof n!="object")throw new Error("createFromJSON requires a valid JSON object");const e=n.omdType;if(!e)throw new Error('JSON data must include an "omdType" field');const t=og[e];if(!t)throw new Error(`Unsupported omdType: "${e}". Supported types: ${Object.keys(og).join(", ")}`);const r=new t;return r.loadFromJSON(n),r}function s9(){return Object.keys(og)}function a9(n){return n in og}class Ra{constructor(e={}){var t,r,i,s,a,o,l,u,c,h,f,d,p,m,y,v,S,g,b,w;this.width=e.width||800,this.height=e.height||500,this.backgroundColor=e.backgroundColor||"white",this.showToolbar=e.showToolbar!==!1,this.showGrid=e.showGrid||!1,this.gridSpacing=e.gridSpacing||20,this.enabledTools=e.enabledTools||["pointer","pencil","eraser"],this.defaultTool=e.defaultTool||"pointer",this.enableFocusFrames=e.enableFocusFrames!==!1,this.enableKeyboardShortcuts=e.enableKeyboardShortcuts!==!1,this.enableMultiTouch=e.enableMultiTouch!==!1,this.tools={pencil:{strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,smoothing:.5,pressureSensitivity:!0,...(t=e.tools)==null?void 0:t.pencil},eraser:{size:20,hardness:.8,...(r=e.tools)==null?void 0:r.eraser}},this.theme={primary:"#007bff",secondary:"#6c757d",success:"#28a745",warning:"#ffc107",danger:"#dc3545",...e.theme},this.selection={border:{color:((s=(i=e.selection)==null?void 0:i.border)==null?void 0:s.color)??"#007bff",width:((o=(a=e.selection)==null?void 0:a.border)==null?void 0:o.width)??2,dasharray:((u=(l=e.selection)==null?void 0:l.border)==null?void 0:u.dasharray)??"4,2",cornerRadius:((h=(c=e.selection)==null?void 0:c.border)==null?void 0:h.cornerRadius)??void 0},handle:{size:((d=(f=e.selection)==null?void 0:f.handle)==null?void 0:d.size)??8,color:((m=(p=e.selection)==null?void 0:p.handle)==null?void 0:m.color)??"#007bff",strokeColor:((v=(y=e.selection)==null?void 0:y.handle)==null?void 0:v.strokeColor)??"#ffffff",strokeWidth:((g=(S=e.selection)==null?void 0:S.handle)==null?void 0:g.strokeWidth)??1,cornerRadius:((w=(b=e.selection)==null?void 0:b.handle)==null?void 0:w.cornerRadius)??1}},this._validate()}_validate(){if(this.width<=0||this.height<=0)throw new Error("Canvas dimensions must be positive numbers");const e=["pointer","pencil","eraser"],t=this.enabledTools.filter(r=>!e.includes(r));t.length>0&&(console.warn(`Invalid tools specified: ${t.join(", ")}`),this.enabledTools=this.enabledTools.filter(r=>e.includes(r))),this.enabledTools.length===0&&(this.enabledTools=["pencil"]),this.enabledTools.includes(this.defaultTool)||(this.defaultTool=this.enabledTools[0]),this._validateToolConfigs()}_validateToolConfigs(){this.tools.pencil.strokeWidth<=0&&(this.tools.pencil.strokeWidth=5),(this.tools.pencil.strokeOpacity<0||this.tools.pencil.strokeOpacity>1)&&(this.tools.pencil.strokeOpacity=1),this.tools.eraser.size<=0&&(this.tools.eraser.size=20),(this.tools.eraser.hardness<0||this.tools.eraser.hardness>1)&&(this.tools.eraser.hardness=.8)}update(e){Object.assign(this,e),this._validate()}getToolConfig(e){return this.tools[e]||{}}updateToolConfig(e,t){this.tools[e]||(this.tools[e]={}),Object.assign(this.tools[e],t),this._validateToolConfigs()}clone(){return new Ra({width:this.width,height:this.height,backgroundColor:this.backgroundColor,showToolbar:this.showToolbar,showGrid:this.showGrid,gridSpacing:this.gridSpacing,enabledTools:[...this.enabledTools],defaultTool:this.defaultTool,enableFocusFrames:this.enableFocusFrames,enableKeyboardShortcuts:this.enableKeyboardShortcuts,enableMultiTouch:this.enableMultiTouch,tools:JSON.parse(JSON.stringify(this.tools)),theme:{...this.theme},selection:JSON.parse(JSON.stringify(this.selection))})}toJSON(){return{width:this.width,height:this.height,backgroundColor:this.backgroundColor,showToolbar:this.showToolbar,showGrid:this.showGrid,gridSpacing:this.gridSpacing,enabledTools:this.enabledTools,defaultTool:this.defaultTool,enableFocusFrames:this.enableFocusFrames,enableKeyboardShortcuts:this.enableKeyboardShortcuts,enableMultiTouch:this.enableMultiTouch,tools:this.tools,theme:this.theme,selection:this.selection}}static fromJSON(e){return new Ra(e)}}class oy{constructor(e){this.canvas=e,this.lastPointerPosition={x:0,y:0},this.lastPointerTime=0,this.velocity={x:0,y:0},this.multiTouchState={isActive:!1,initialDistance:0,initialAngle:0,lastScale:1,lastRotation:0},this.gestureThresholds={minPinchDistance:20,minRotationAngle:.1}}handlePointerDown(e,t){this.lastPointerPosition={x:t.x,y:t.y},this.lastPointerTime=t.timestamp,this.velocity={x:0,y:0},t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure)}handlePointerMove(e,t){if(this._calculateVelocity(t),e.getCoalescedEvents){const r=e.getCoalescedEvents();t.coalescedEvents=r.map(i=>{const s=this.canvas.clientToSVG(i.clientX,i.clientY);return{x:s.x,y:s.y,pressure:this._normalizePressure(i.pressure),timestamp:i.timeStamp||Date.now()}})}t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure),this.lastPointerPosition={x:t.x,y:t.y},this.lastPointerTime=t.timestamp}handlePointerUp(e,t){this._calculateVelocity(t),t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure),this.velocity={x:0,y:0}}handleMultiTouchStart(e){if(e.size===2){const t=Array.from(e.values()),r=t[0],i=t[1];this.multiTouchState.isActive=!0,this.multiTouchState.initialDistance=this._calculateDistance(r,i),this.multiTouchState.initialAngle=this._calculateAngle(r,i),this.multiTouchState.lastScale=1,this.multiTouchState.lastRotation=0,this.canvas.emit("multiTouchStart",{pointers:t,distance:this.multiTouchState.initialDistance,angle:this.multiTouchState.initialAngle})}}handleMultiTouchMove(e){if(e.size===2&&this.multiTouchState.isActive){const t=Array.from(e.values()),r=t[0],i=t[1],s=this._calculateDistance(r,i),a=this._calculateAngle(r,i),o=s/this.multiTouchState.initialDistance,l=a-this.multiTouchState.initialAngle;Math.abs(o-1)>.1&&(this.canvas.emit("pinch",{scale:o,deltaScale:o-this.multiTouchState.lastScale,center:this._calculateCenter(r,i)}),this.multiTouchState.lastScale=o),Math.abs(l)>this.gestureThresholds.minRotationAngle&&(this.canvas.emit("rotate",{rotation:l,deltaRotation:l-this.multiTouchState.lastRotation,center:this._calculateCenter(r,i)}),this.multiTouchState.lastRotation=l)}}handleMultiTouchEnd(e){e.size<2&&(this.multiTouchState.isActive=!1,this.canvas.emit("multiTouchEnd"))}_calculateVelocity(e){const t=e.timestamp-this.lastPointerTime;if(t>0){const r=e.x-this.lastPointerPosition.x,i=e.y-this.lastPointerPosition.y;this.velocity.x=r/t*1e3,this.velocity.y=i/t*1e3}}_normalizePressure(e=.5){if(e==null)return .5;let t=e;return t<.1&&(t=.1),t=Math.pow(t,.8),Math.max(0,Math.min(1,t))}_calculateDistance(e,t){const r=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(r*r+i*i)}_calculateAngle(e,t){return Math.atan2(t.clientY-e.clientY,t.clientX-e.clientX)}_calculateCenter(e,t){const r=(e.clientX+t.clientX)/2,i=(e.clientY+t.clientY)/2;return this.canvas.clientToSVG(r,i)}getVelocity(){return{x:this.velocity.x,y:this.velocity.y,magnitude:Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),angle:Math.atan2(this.velocity.y,this.velocity.x)}}getMultiTouchState(){return{isActive:this.multiTouchState.isActive,scale:this.multiTouchState.lastScale,rotation:this.multiTouchState.lastRotation}}}class uy{constructor(e){this.canvas=e,this.isInitialized=!1,this.pointerEventHandler=new oy(e),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerCancel=this._onPointerCancel.bind(this),this._onPointerEnter=this._onPointerEnter.bind(this),this._onPointerLeave=this._onPointerLeave.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this._onWheel=this._onWheel.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this.activePointers=new Map,this.isDrawing=!1,this.lastEventTime=0}initialize(){if(this.isInitialized)return;const e=this.canvas.svg;e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUp),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("pointerenter",this._onPointerEnter),e.addEventListener("pointerleave",this._onPointerLeave),this.canvas.config.enableKeyboardShortcuts&&(document.addEventListener("keydown",this._onKeyDown),document.addEventListener("keyup",this._onKeyUp)),e.addEventListener("wheel",this._onWheel),e.addEventListener("contextmenu",this._onContextMenu),e.style.touchAction="none",this.isInitialized=!0}_onPointerDown(e){e.preventDefault(),this.activePointers.set(e.pointerId,e),e.target.setPointerCapture(e.pointerId);const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>1){this.pointerEventHandler.handleMultiTouchStart(this.activePointers);return}this.pointerEventHandler.handlePointerDown(e,r);const i=this.canvas.toolManager.getActiveTool();i&&(i.onPointerDown(r),this.isDrawing===!1&&i.constructor.name!=="PointerTool"&&(this.isDrawing=!0)),this.canvas.emit("pointerDown",r)}_onPointerMove(e){const t=Date.now();if(t-this.lastEventTime<16)return;this.lastEventTime=t,this.activePointers.has(e.pointerId)&&this.activePointers.set(e.pointerId,e);const r=this.canvas.clientToSVG(e.clientX,e.clientY),i=this._normalizePointerEvent(e,r);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>1){this.pointerEventHandler.handleMultiTouchMove(this.activePointers);return}if(this.canvas.cursor&&(this.canvas.cursor.setPosition(r.x,r.y),e.pressure!==void 0&&this.canvas.cursor.setPressureFeedback(e.pressure)),this.pointerEventHandler.handlePointerMove(e,i),this.isDrawing){const s=this.canvas.toolManager.getActiveTool();s&&s.onPointerMove(i)}this.canvas.emit("pointerMove",i)}_onPointerUp(e){this.activePointers.delete(e.pointerId),e.target.releasePointerCapture(e.pointerId);const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>=1){this.pointerEventHandler.handleMultiTouchEnd(this.activePointers);return}this.isDrawing=!1,this.pointerEventHandler.handlePointerUp(e,r);const i=this.canvas.toolManager.getActiveTool();i&&i.onPointerUp(r),this.canvas.emit("pointerUp",r)}_onPointerCancel(e){this.activePointers.delete(e.pointerId),e.target.releasePointerCapture(e.pointerId),this.isDrawing=!1;const t=this.canvas.toolManager.getActiveTool();t&&t.onCancel(),this.canvas.emit("pointerCancel",{pointerId:e.pointerId})}_onPointerEnter(e){if(this.canvas.cursor){this.canvas.cursor.show();const t=this.canvas.toolManager.getActiveTool();t&&(t.getCursor&&this.canvas.cursor.setShape(t.getCursor()),t.config&&this.canvas.cursor.updateFromToolConfig(t.config))}if(e.buttons!==0){const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);this.isDrawing=!0;const i=this.canvas.toolManager.getActiveTool();i&&i.onPointerDown(r)}this.canvas.emit("pointerEnter",{event:e})}_onPointerLeave(e){this.canvas.cursor&&this.canvas.cursor.hide(),e.buttons===0&&(this.isDrawing=!1),e.buttons===0&&this.activePointers.clear(),this.canvas.emit("pointerLeave",{event:e})}_onKeyDown(e){if(e.target.tagName==="INPUT"||e.target.tagName==="TEXTAREA")return;const t=e.key.toLowerCase();switch(t){case"p":this.canvas.config.enabledTools.includes("pencil")&&(this.canvas.toolManager.setActiveTool("pencil"),e.preventDefault());break;case"e":this.canvas.config.enabledTools.includes("eraser")&&(this.canvas.toolManager.setActiveTool("eraser"),e.preventDefault());break;case"s":this.canvas.config.enabledTools.includes("select")&&(this.canvas.toolManager.setActiveTool("select"),e.preventDefault());break;case"escape":const i=this.canvas.toolManager.getActiveTool();i&&i.onCancel(),e.preventDefault();break}const r=this.canvas.toolManager.getActiveTool();r&&r.onKeyboardShortcut&&r.onKeyboardShortcut(t,e)&&e.preventDefault(),this.canvas.emit("keyDown",{key:t,event:e})}_onKeyUp(e){if(e.target.tagName==="INPUT"||e.target.tagName==="TEXTAREA")return;const t=e.key.toLowerCase();this.canvas.emit("keyUp",{key:t,event:e})}_onWheel(e){e.preventDefault();const t=this.canvas.clientToSVG(e.clientX,e.clientY);this.canvas.emit("wheel",{deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,x:t.x,y:t.y,ctrlKey:e.ctrlKey,metaKey:e.metaKey})}_onContextMenu(e){e.preventDefault()}_normalizePointerEvent(e,t){return{pointerId:e.pointerId,pointerType:e.pointerType,isPrimary:e.isPrimary,x:t.x,y:t.y,clientX:e.clientX,clientY:e.clientY,pressure:this._normalizePressure(e.pressure),tiltX:e.tiltX||0,tiltY:e.tiltY||0,twist:e.twist||0,width:e.width||1,height:e.height||1,tangentialPressure:e.tangentialPressure||0,buttons:e.buttons,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,timestamp:e.timeStamp||Date.now()}}_normalizePressure(e){return e==null?.5:Math.max(0,Math.min(1,e))}getPointerInfo(){return{activePointers:this.activePointers.size,isDrawing:this.isDrawing,multiTouch:this.activePointers.size>1}}destroy(){if(!this.isInitialized)return;const e=this.canvas.svg;e.removeEventListener("pointerdown",this._onPointerDown),e.removeEventListener("pointermove",this._onPointerMove),e.removeEventListener("pointerup",this._onPointerUp),e.removeEventListener("pointercancel",this._onPointerCancel),e.removeEventListener("pointerenter",this._onPointerEnter),e.removeEventListener("pointerleave",this._onPointerLeave),document.removeEventListener("keydown",this._onKeyDown),document.removeEventListener("keyup",this._onKeyUp),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("contextmenu",this._onContextMenu),this.activePointers.clear(),this.isDrawing=!1,this.isInitialized=!1}}class ly{constructor(e){this.canvas=e,this.tools=new Map,this.activeTool=null,this.previousTool=null,this.isDestroyed=!1}registerTool(e,t){return this.isDestroyed?(console.warn("Cannot register tool on destroyed ToolManager"),!1):!e||typeof e!="string"?(console.error("Tool name must be a non-empty string"),!1):!t||typeof t.onPointerDown!="function"?(console.error("Tool must implement required methods"),!1):this.canvas.config.enabledTools.includes(e)?(t.name=e,t.canvas=this.canvas,this.tools.set(e,t),!0):(console.warn(`Tool '${e}' is not enabled in canvas configuration`),!1)}unregisterTool(e){const t=this.tools.get(e);return t?(this.activeTool===t&&this.setActiveTool(null),this.tools.delete(e),!0):!1}setActiveTool(e){var r,i;if(this.activeTool){try{this.activeTool.onDeactivate()}catch(s){console.error("Error deactivating tool:",s)}this.previousTool=this.activeTool}if(!e)return this.activeTool=null,this.canvas.emit("toolChanged",{name:null,tool:null,previous:(r=this.previousTool)==null?void 0:r.name}),!0;const t=this.tools.get(e);if(!t)return console.error(`Tool '${e}' not found`),!1;this.activeTool=t;try{this.activeTool.onActivate()}catch(s){return console.error("Error activating tool:",s),this.activeTool=null,!1}if(this.canvas.cursor&&this.activeTool.getCursor){const s=this.activeTool.getCursor();this.canvas.cursor.setShape(s)}return this.canvas.cursor&&this.activeTool.config&&this.canvas.cursor.updateFromToolConfig(this.activeTool.config),this.canvas.emit("toolChanged",{name:e,tool:t,previous:(i=this.previousTool)==null?void 0:i.name}),!0}getActiveTool(){return this.activeTool}getTool(e){return this.tools.get(e)}getToolNames(){return Array.from(this.tools.keys())}getAllTools(){return new Map(this.tools)}getAllToolMetadata(){return Array.from(this.tools.entries()).map(([e,t])=>({name:e,displayName:t.displayName||e,description:t.description||"",shortcut:t.shortcut||"",category:t.category||"general",icon:t.icon||"tool"}))}switchToPreviousTool(){return this.previousTool?this.setActiveTool(this.previousTool.name):!1}async withTemporaryTool(e,t){var i;const r=(i=this.activeTool)==null?void 0:i.name;if(!this.setActiveTool(e))throw new Error(`Failed to activate temporary tool: ${e}`);try{return await t(this.activeTool)}finally{r&&this.setActiveTool(r)}}updateToolConfig(e,t){const r=this.tools.get(e);return r?r.updateConfig?(r.updateConfig(t),this.activeTool===r&&this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(r.config),!0):(console.warn(`Tool '${e}' does not support configuration updates`),!1):(console.error(`Tool '${e}' not found`),!1)}getToolConfig(e){const t=this.tools.get(e);return t?t.config||{}:null}hasTool(e){return this.tools.has(e)}isToolEnabled(e){return this.canvas.config.enabledTools.includes(e)}getToolCapabilities(e){const t=this.tools.get(e);return t?{name:t.name,displayName:t.displayName,description:t.description,shortcut:t.shortcut,category:t.category,supportsKeyboardShortcuts:typeof t.onKeyboardShortcut=="function",supportsPressure:t.supportsPressure||!1,supportsMultiTouch:t.supportsMultiTouch||!1,configurable:typeof t.updateConfig=="function",hasHelp:typeof t.getHelpText=="function"}:null}handleKeyboardShortcut(e,t){for(const[r,i]of this.tools)if(i.shortcut&&i.shortcut.toLowerCase()===e.toLowerCase())return this.setActiveTool(r),!0;return this.activeTool&&this.activeTool.onKeyboardShortcut?this.activeTool.onKeyboardShortcut(e,t):!1}getHelpText(e=null){if(e){const r=this.tools.get(e);return r&&r.getHelpText?r.getHelpText():`No help available for tool: ${e}`}const t={};for(const[r,i]of this.tools)i.getHelpText&&(t[r]=i.getHelpText());return t}getState(){var e,t;return{activeToolName:((e=this.activeTool)==null?void 0:e.name)||null,previousToolName:((t=this.previousTool)==null?void 0:t.name)||null,registeredTools:this.getToolNames(),enabledTools:this.canvas.config.enabledTools,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed){if(this.activeTool)try{this.activeTool.onDeactivate()}catch(e){console.error("Error deactivating tool during destroy:",e)}for(const[e,t]of this.tools)if(t.destroy)try{t.destroy()}catch(r){console.error(`Error destroying tool '${e}':`,r)}this.tools.clear(),this.activeTool=null,this.previousTool=null,this.canvas=null,this.isDestroyed=!0}}}class Di{constructor(e=0,t=0,r=0,i=0){this.x=e,this.y=t,this.width=r,this.height=i}set(e,t,r,i){this.x=e,this.y=t,this.width=r,this.height=i}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}get centerX(){return this.x+this.width/2}get centerY(){return this.y+this.height/2}get center(){return{x:this.centerX,y:this.centerY}}containsPoint(e,t,r=0){return e>=this.left-r&&e<=this.right+r&&t>=this.top-r&&t<=this.bottom+r}intersects(e){return!(this.right<e.left||e.right<this.left||this.bottom<e.top||e.bottom<this.top)}contains(e){return this.left<=e.left&&this.right>=e.right&&this.top<=e.top&&this.bottom>=e.bottom}expandToIncludePoint(e,t){if(this.width===0&&this.height===0)this.x=e,this.y=t,this.width=0,this.height=0;else{const r=Math.min(this.left,e),i=Math.min(this.top,t),s=Math.max(this.right,e),a=Math.max(this.bottom,t);this.x=r,this.y=i,this.width=s-r,this.height=a-i}}expandToIncludeBox(e){if(!(e.width===0&&e.height===0))if(this.width===0&&this.height===0)this.set(e.x,e.y,e.width,e.height);else{const t=Math.min(this.left,e.left),r=Math.min(this.top,e.top),i=Math.max(this.right,e.right),s=Math.max(this.bottom,e.bottom);this.x=t,this.y=r,this.width=i-t,this.height=s-r}}getIntersection(e){if(!this.intersects(e))return null;const t=Math.max(this.left,e.left),r=Math.max(this.top,e.top),i=Math.min(this.right,e.right),s=Math.min(this.bottom,e.bottom);return new Di(t,r,i-t,s-r)}getUnion(e){if(this.width===0&&this.height===0)return e.clone();if(e.width===0&&e.height===0)return this.clone();const t=Math.min(this.left,e.left),r=Math.min(this.top,e.top),i=Math.max(this.right,e.right),s=Math.max(this.bottom,e.bottom);return new Di(t,r,i-t,s-r)}inflate(e){this.x-=e,this.y-=e,this.width+=e*2,this.height+=e*2,this.width=Math.max(0,this.width),this.height=Math.max(0,this.height)}move(e,t){this.x+=e,this.y+=t}scale(e,t=this.centerX,r=this.centerY){const i=this.width*e,s=this.height*e;this.x=t-(t-this.x)*e,this.y=r-(r-this.y)*e,this.width=i,this.height=s}getArea(){return this.width*this.height}getPerimeter(){return 2*(this.width+this.height)}isEmpty(){return this.width<=0||this.height<=0}isValid(){return!isNaN(this.x)&&!isNaN(this.y)&&!isNaN(this.width)&&!isNaN(this.height)&&this.width>=0&&this.height>=0}distanceToPoint(e,t){if(this.containsPoint(e,t))return 0;const r=Math.max(0,Math.max(this.left-e,e-this.right)),i=Math.max(0,Math.max(this.top-t,t-this.bottom));return Math.sqrt(r*r+i*i)}getCorners(){return[{x:this.left,y:this.top},{x:this.right,y:this.top},{x:this.right,y:this.bottom},{x:this.left,y:this.bottom}]}clone(){return new Di(this.x,this.y,this.width,this.height)}toString(){return`BoundingBox(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toJSON(){return{x:this.x,y:this.y,width:this.width,height:this.height}}static fromJSON(e){return new Di(e.x,e.y,e.width,e.height)}static fromPoints(e){if(e.length===0)return new Di;let t=1/0,r=1/0,i=-1/0,s=-1/0;return e.forEach(a=>{t=Math.min(t,a.x),r=Math.min(r,a.y),i=Math.max(i,a.x),s=Math.max(s,a.y)}),new Di(t,r,i-t,s-r)}}class gn{constructor(e={}){this.id=e.id||this._generateId(),this.tool=e.tool||"pencil",this.strokeWidth=e.strokeWidth||5,this.strokeColor=e.strokeColor||"#000000",this.strokeOpacity=e.strokeOpacity||1,this.points=[],this.isFinished=!1,this.isSelected=!1,this.boundingBox=new Di,this._createElement(),e.x!==void 0&&e.y!==void 0&&this.addPoint({x:e.x,y:e.y,pressure:.5,width:this.strokeWidth,timestamp:Date.now()})}_createElement(){this.jsvgPath=new Ni,this.element=this.jsvgPath.svgObject,this.jsvgPath.setFillColor("none"),this.jsvgPath.setStrokeColor(this.strokeColor),this.jsvgPath.setStrokeWidth(this.strokeWidth),this.element.setAttribute("stroke-opacity",this.strokeOpacity),this.element.setAttribute("stroke-linecap","round"),this.element.setAttribute("stroke-linejoin","round"),this.element.setAttribute("data-stroke-id",this.id),this.element.setAttribute("data-tool",this.tool)}addPoint(e){const t={x:e.x,y:e.y,pressure:e.pressure||.5,width:e.width||this.strokeWidth,timestamp:e.timestamp||Date.now()};this.points.push(t),this._updatePath(),this._updateBoundingBox()}_updatePath(){if(this.points.length===0){this.jsvgPath.clearPoints();return}if(this.jsvgPath.clearPoints(),this.points.length===1){const e=this.points[0];this.jsvgPath.addPoint(e.x,e.y),this.jsvgPath.addPoint(e.x+.1,e.y)}else this._generateSmoothPath();this.jsvgPath.updatePath()}_generateSmoothPath(){if(this.points.length<2)return"";if(this.jsvgPath.addPoint(this.points[0].x,this.points[0].y),this.points.length===2){this.jsvgPath.addPoint(this.points[1].x,this.points[1].y);return}for(let e=1;e<this.points.length-1;e++){const t=this.points[e-1],r=this.points[e],i=this.points[e+1];r.x+(i.x-t.x)*.25,r.y+(i.y-t.y)*.25,i.x-(i.x-r.x)*.25,i.y-(i.y-r.y)*.25,this.jsvgPath.addPoint(i.x,i.y)}}_updateBoundingBox(){if(this.points.length===0)return;let e=1/0,t=1/0,r=-1/0,i=-1/0;this.points.forEach(s=>{const a=s.width/2;e=Math.min(e,s.x-a),t=Math.min(t,s.y-a),r=Math.max(r,s.x+a),i=Math.max(i,s.y+a)}),this.boundingBox.set(e,t,r-e,i-t)}finish(){this.isFinished=!0,this.element.setAttribute("data-finished","true")}setSelected(e){this.isSelected=e,e?(this.element.setAttribute("stroke-dasharray","5,5"),this.element.setAttribute("data-selected","true")):(this.element.removeAttribute("stroke-dasharray"),this.element.removeAttribute("data-selected"))}updateConfig(e){e.strokeColor!==void 0&&(this.strokeColor=e.strokeColor,this.jsvgPath.setStrokeColor(this.strokeColor)),e.strokeWidth!==void 0&&(this.strokeWidth=e.strokeWidth,this.jsvgPath.setStrokeWidth(this.strokeWidth)),e.strokeOpacity!==void 0&&(this.strokeOpacity=e.strokeOpacity,this.element.setAttribute("stroke-opacity",this.strokeOpacity))}isNearPoint(e,t,r=10){if(!this.boundingBox.containsPoint(e,t,r))return!1;for(let i=1;i<this.points.length;i++){const s=this.points[i-1],a=this.points[i];if(this._distanceToLineSegment(e,t,s.x,s.y,a.x,a.y)<=r)return!0}return!1}_distanceToLineSegment(e,t,r,i,s,a){const o=s-r,l=a-i,u=Math.sqrt(o*o+l*l);if(u===0)return Math.sqrt((e-r)*(e-r)+(t-i)*(t-i));const c=Math.max(0,Math.min(1,((e-r)*o+(t-i)*l)/(u*u))),h=r+c*o,f=i+c*l;return Math.sqrt((e-h)*(e-h)+(t-f)*(t-f))}getLength(){let e=0;for(let t=1;t<this.points.length;t++){const r=this.points[t-1],i=this.points[t],s=i.x-r.x,a=i.y-r.y;e+=Math.sqrt(s*s+a*a)}return e}toJSON(){return{id:this.id,tool:this.tool,strokeWidth:this.strokeWidth,strokeColor:this.strokeColor,strokeOpacity:this.strokeOpacity,points:this.points,isFinished:this.isFinished,boundingBox:this.boundingBox.toJSON()}}static fromJSON(e){const t=new gn({id:e.id,tool:e.tool,strokeWidth:e.strokeWidth,strokeColor:e.strokeColor,strokeOpacity:e.strokeOpacity});return e.points.forEach(r=>t.addPoint(r)),e.isFinished&&t.finish(),t}_generateId(){return`stroke_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}clone(){return gn.fromJSON(this.toJSON())}getPointCount(){return this.points.length}getBoundingBox(){return this.boundingBox}move(e,t){this.points.forEach(r=>{r.x+=e,r.y+=t}),this._updatePath(),this._updateBoundingBox()}scale(e,t=0,r=0){this.points.forEach(i=>{i.x=t+(i.x-t)*e,i.y=r+(i.y-r)*e,i.width*=e}),this.strokeWidth*=e,this.jsvgPath.setStrokeWidth(this.strokeWidth),this._updatePath(),this._updateBoundingBox()}}class Yo{constructor(e,t={}){this.canvas=e,this.name="",this.displayName="",this.description="",this.icon="",this.shortcut="",this.category="general",this.isActive=!1,this.isDrawing=!1,this.currentStroke=null,this.config={strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,...t},this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this)}onActivate(){this.isActive=!0,this.canvas.emit("toolActivated",{tool:this,name:this.name})}onDeactivate(){this.isActive=!1,this.isDrawing&&this.onCancel(),this.canvas.emit("toolDeactivated",{tool:this,name:this.name})}onPointerDown(e){throw new Error("Tool.onPointerDown() must be implemented by subclass")}onPointerMove(e){throw new Error("Tool.onPointerMove() must be implemented by subclass")}onPointerUp(e){throw new Error("Tool.onPointerUp() must be implemented by subclass")}onCancel(){this.isDrawing&&(this.isDrawing=!1,this.currentStroke&&this.currentStroke.id&&this.canvas.removeStroke(this.currentStroke.id),this.currentStroke=null)}updateConfig(e){this.config={...this.config,...e},this.onConfigUpdate()}onConfigUpdate(){}getConfig(){return{...this.config}}isDrawingActive(){return this.isDrawing}getCursor(){return this.name}getProperties(){return{name:this.name,displayName:this.displayName,description:this.description,icon:this.icon,shortcut:this.shortcut,category:this.category,config:this.getConfig()}}createStroke(e,t){const r={x:e,y:t,strokeWidth:this.config.strokeWidth,strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity,tool:this.name};return new gn(r)}calculateStrokeWidth(e=.5){const t=this.config.strokeWidth,r=Math.max(1,t*.3),i=t*1.5;return r+(i-r)*e}onKeyboardShortcut(e,t){return!1}getHelpText(){return`${this.displayName}: ${this.description}`}canUse(){return!this.canvas.isDestroyed&&this.isActive}}class cy extends Yo{constructor(e,t={}){super(e,{strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,smoothing:.5,pressureSensitive:!0,...t}),this.displayName="Pencil",this.description="Draw freehand strokes",this.icon="pencil",this.shortcut="P",this.category="drawing",this.points=[],this.lastPoint=null,this.minDistance=2}onPointerDown(e){this.canUse()&&(this.isDrawing=!0,this.points=[],this.lastPoint={x:e.x,y:e.y},this.currentStroke=new gn({x:e.x,y:e.y,strokeWidth:this.calculateStrokeWidth(e.pressure),strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity,tool:this.name}),this.addPoint(e.x,e.y,e.pressure),this.canvas.addStroke(this.currentStroke),this.canvas.emit("strokeStarted",{stroke:this.currentStroke,tool:this.name,point:{x:e.x,y:e.y,pressure:e.pressure}}))}onPointerMove(e){if(!(!this.isDrawing||!this.currentStroke)){if(e.coalescedEvents&&e.coalescedEvents.length>0){const r=e.coalescedEvents.slice(0,5);for(const i of r)this._addPointIfNeeded(i.x,i.y,i.pressure)}else this._addPointIfNeeded(e.x,e.y,e.pressure);this.canvas.emit("strokeContinued",{stroke:this.currentStroke,tool:this.name,point:{x:e.x,y:e.y,pressure:e.pressure}})}}onPointerUp(e){!this.isDrawing||!this.currentStroke||(this.addPoint(e.x,e.y,e.pressure),this.currentStroke.finish(),this.canvas.emit("strokeCompleted",{stroke:this.currentStroke,tool:this.name,totalPoints:this.points.length}),this.isDrawing=!1,this.currentStroke=null,this.points=[],this.lastPoint=null)}onCancel(){this.isDrawing&&this.currentStroke&&(this.canvas.removeStroke(this.currentStroke.id),this.canvas.emit("strokeCancelled",{stroke:this.currentStroke,tool:this.name})),super.onCancel(),this.points=[],this.lastPoint=null}addPoint(e,t,r=.5){const i={x:e,y:t,pressure:r,width:this.calculateStrokeWidth(r),timestamp:Date.now()};this.points.push(i),this.currentStroke&&this.currentStroke.addPoint(i)}_addPointIfNeeded(e,t,r=.5){if(!this.lastPoint){this.addPoint(e,t,r),this.lastPoint={x:e,y:t};return}const i=this.getDistance(this.lastPoint,{x:e,y:t});i>=this.minDistance&&(i>8?this._interpolatePoints(this.lastPoint,{x:e,y:t,pressure:r}):this.addPoint(e,t,r),this.lastPoint={x:e,y:t})}_interpolatePoints(e,t){const r=this.getDistance(e,t),i=Math.ceil(r/3),a=Math.min(i,10);for(let o=1;o<=a;o++){const l=o/a,u=e.x+(t.x-e.x)*l,c=e.y+(t.y-e.y)*l,h=e.pressure?e.pressure+(t.pressure-e.pressure)*l:t.pressure;this.addPoint(u,c,h)}}getDistance(e,t){const r=t.x-e.x,i=t.y-e.y;return Math.sqrt(r*r+i*i)}onConfigUpdate(){this.minDistance=Math.max(1,this.config.strokeWidth*.2),this.isDrawing&&this.currentStroke&&this.currentStroke.updateConfig({strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity}),this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(this.config)}calculateStrokeWidth(e=.5){return this.config.pressureSensitive?super.calculateStrokeWidth(e):this.config.strokeWidth}getSmoothPath(e){if(e.length<2)return e;const t=[],r=this.config.smoothing;t.push(e[0]);for(let i=1;i<e.length-1;i++){const s=e[i-1],a=e[i],o=e[i+1],l={x:a.x+r*((s.x+o.x)/2-a.x),y:a.y+r*((s.y+o.y)/2-a.y),pressure:a.pressure,width:a.width,timestamp:a.timestamp};t.push(l)}return e.length>1&&t.push(e[e.length-1]),t}onKeyboardShortcut(e,t){switch(e){case"[":return this.updateConfig({strokeWidth:Math.max(1,this.config.strokeWidth-1)}),this.canvas.toolManager.updateToolConfig(this.name,this.config),!0;case"]":return this.updateConfig({strokeWidth:Math.min(50,this.config.strokeWidth+1)}),this.canvas.toolManager.updateToolConfig(this.name,this.config),!0;default:return super.onKeyboardShortcut(e,t)}}getHelpText(){return`${super.getHelpText()}
93
+ </svg>`);this.penButton.addImage(h,12,12),this.popup.addChild(this.penButton)}_createTextInput(e,t,r){const i=this.buttonSize*2+r*2+this.margin,s=e-i-r*2,a=t-r*2,o=this.buttonSize+r*2,l=r;this.popupTextInput=new hE,this.popupTextInput.setWidthAndHeight(s,a),this.popupTextInput.setPosition(o,l),this.popupTextInput.setFillColor("transparent"),this.popupTextInput.setStrokeColor("transparent"),this.popupTextInput.setStrokeWidth(0),this.popupTextInput.setPlaceholderText(""),this.popupTextInput.div&&(this.popupTextInput.div.style.border="none",this.popupTextInput.div.style.outline="none",this.popupTextInput.div.style.background="transparent",this.popupTextInput.div.style.textAlign="center",this.popupTextInput.div.style.fontSize="48px",this.popupTextInput.div.style.fontFamily="Albert Sans, Arial, sans-serif",this.popupTextInput.div.style.resize="none",this.popupTextInput.div.style.width="100%",this.popupTextInput.div.style.height="100%",this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.alignItems="center",this.popupTextInput.div.style.justifyContent="center",this.popupTextInput.div.style.boxSizing="border-box"),this.popup.addChild(this.popupTextInput)}_createPenCanvas(){var f;const e=this.popupWidth,t=(((f=this.targetNode)==null?void 0:f.height)||this.targetNodeDefaultHeight)*this.popupHeightMultiplier,r=this.buttonSize,i=2*this.buttonSize+this.buttonSpacing,s=Math.max(e-r-i,this.canvasMinWidth),a=this.buttonSize*2+this.buttonSpacing+this.margin*2,o=t-a,l=Math.max(o,this.canvasMinHeight),u=r;let c,h=null;this.parentElement&&this.parentElement.element&&this.parentElement.element.namespaceURI==="http://www.w3.org/2000/svg"?(h=document.createElementNS("http://www.w3.org/2000/svg","foreignObject"),h.setAttribute("width",s),h.setAttribute("height",l),h.setAttribute("x",u),h.setAttribute("y",this.canvasTopOffset),c=document.createElement("div"),c.style.width=`${s}px`,c.style.height=`${l}px`,c.style.border="1px solid #ddd",c.style.borderRadius="4px",c.style.backgroundColor="#f8f9fa",c.style.margin="0",c.style.padding="0",h.appendChild(c)):(c=document.createElement("div"),c.style.width=`${s}px`,c.style.height=`${l}px`,c.style.position="absolute",c.style.left=`${u}px`,c.style.top=`${this.canvasTopOffset}px`,c.style.border="none",c.style.borderRadius="0px",c.style.backgroundColor="#ffffff",c.style.zIndex="1000",c.style.pointerEvents="auto",c.style.cursor="crosshair"),Promise.resolve().then(()=>p9).then(({createCanvas:d})=>{const p=s,m=l;this.penCanvas=d(c,{width:p-this.buttonSize,height:m,showToolbar:!1,showGrid:!1,backgroundColor:"#ffffff",strokeWidth:3,strokeColor:"#000000"}),this.penCanvas.container=c,this.penCanvas.foreignObject=h,this.penCanvas.toolManager.setActiveTool("pencil"),this.penCanvas.on("strokeStarted",y=>{}),this.penCanvas.on("strokeCompleted",y=>{}),c.addEventListener("pointerdown",y=>{}),c.addEventListener("click",y=>{}),this.penCanvasCleanup=()=>{this.penCanvas&&this.penCanvas.destroy(),h&&h.parentNode?h.parentNode.removeChild(h):c&&c.parentNode&&c.parentNode.removeChild(c),this._removeStepVisualizerListeners()},this._setupStepVisualizerListeners(),this.currentMode==="pen"&&this.popup&&this._addCanvasToParent(h||c)}).catch(console.error)}_showPenMode(){if(this.popupTextInput&&this.popupTextInput.div&&(this.popupTextInput.div.style.display="none",this.popupTextInput.div.style.visibility="hidden"),!this.penCanvas)this._createPenCanvas();else{const e=this.penCanvas.foreignObject||this.penCanvas.container;e&&(e.style.display="block",e.style.opacity="1"),this._addCanvasToParent()}}_showTextMode(){if(this.penCanvas){const e=this.penCanvas.foreignObject||this.penCanvas.container;e&&e.parentNode&&e.parentNode.removeChild(e)}this.popupTextInput&&this.popup&&(this.popupTextInput.div&&(this.popupTextInput.div.style.display="flex",this.popupTextInput.div.style.visibility="visible",this.popupTextInput.div.style.opacity="1"),this.popup.addChild(this.popupTextInput),setTimeout(()=>{this.popupTextInput.div&&this.popupTextInput.div.focus()},100))}_addCanvasToParent(e=null){if(!e&&this.penCanvas&&this.penCanvas.container){this.penCanvas.container.parentNode&&this.penCanvas.container.parentNode.removeChild(this.penCanvas.container),document.body.appendChild(this.penCanvas.container),this._updateCanvasPosition();return}if(this.penCanvas&&this.popup&&this.parentElement){const t=this.popup.xpos||0,r=this.popup.ypos||0;if(e)if(e.namespaceURI==="http://www.w3.org/2000/svg")e.setAttribute("x",t+this.canvasLeftOffset),e.setAttribute("y",r+this.canvasTopOffset),this.parentElement.element?this.parentElement.element.appendChild(e):this.parentElement.appendChild&&this.parentElement.appendChild(e);else{const i=this.popup.svgObject?this.popup.svgObject.getBoundingClientRect():null;if(i){const s=this.buttonSize+this.margin*2,a=this.buttonSize*2+this.margin*2+this.margin,o=i.left+s,l=i.top+this.margin;e.style.left=`${o}px`,e.style.top=`${l}px`,e.style.position="fixed",e.style.zIndex="9999",e.style.pointerEvents="auto";const u=i.width-s-a;e.style.width=`${u}px`,this.penCanvas.popupRect=i,this._setupResizeObserver()}else{const s=(window.innerWidth-280)/2,a=(window.innerHeight-60)/2;e.style.left=`${s}px`,e.style.top=`${a}px`,e.style.position="fixed",e.style.zIndex="9999",e.style.pointerEvents="auto"}document.body.appendChild(e)}}}_updateButtonStates(){!this.penButton||!this.textButton||(this.currentMode==="pen"?(this.penButton.setFillColor("#2980B9"),this.textButton.setFillColor("#9B59B6")):(this.penButton.setFillColor("#3498DB"),this.textButton.setFillColor("#8E44AD")))}_positionPopup(e,t){this.popup&&this.popup.setPosition(e,t)}_animateOpacity(e,t,r){return new Promise(i=>{if(!this.popup){i();return}this.popupAnimationId&&cancelAnimationFrame(this.popupAnimationId);const s=performance.now(),a=t-e,o=l=>{const u=l-s,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e+a*h;this.popup.setOpacity(f),this.penCanvas&&this.penCanvas.container&&this.currentMode==="pen"&&(this.penCanvas.container.style.opacity=f),c<1?this.popupAnimationId=requestAnimationFrame(o):(this.popupAnimationId=null,this.penCanvas&&this.penCanvas.container&&this.currentMode==="pen"&&(this.penCanvas.container.style.opacity="1"),i())};this.popupAnimationId=requestAnimationFrame(o)})}flashValidation(e){if(!this.popupBackground)return;const t=e?"#E8F5E8":"#FFE6E6";this._flashAllElements(t)}_flashAllElements(e){this.popupBackground.setFillColor(e),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.backgroundColor=e),this.penCanvas&&this.penCanvas.svg&&(this.penCanvas.svg.style.backgroundColor=e),setTimeout(()=>{this.popupBackground.setFillColor("white"),this.penCanvas&&this.penCanvas.container&&(this.penCanvas.container.style.backgroundColor="white"),this.penCanvas&&this.penCanvas.svg&&(this.penCanvas.svg.style.backgroundColor="white")},300)}areExpressionsEquivalent(e,t){if(!window.math||!window.math.simplify||!window.math.parse)return!1;try{const r=e.trim(),i=t.trim(),s=window.math.simplify(r),a=window.math.simplify(i);if(s.equals(a))return!0;const o=u=>{const c=window.math.parse(u),h=new Set;return c.traverse(f=>{f.isSymbolNode&&h.add(f.name)}),Array.from(h)},l=Array.from(new Set([...o(r),...o(i)]));if(l.length===0)return s.evaluate()===a.evaluate();for(let u=0;u<100;u++){const c={};for(const d of l)c[d]=Math.floor(Math.random()*1e3+1);const h=s.evaluate(c),f=a.evaluate(c);if(Math.abs(h-f)>1e-9)return!1}return!0}catch{return!1}}_cleanup(){this.popup&&this.parentElement&&this.parentElement.removeChild(this.popup),this.penCanvas&&(this.penCanvas.foreignObject&&this.penCanvas.foreignObject.parentNode&&this.penCanvas.foreignObject.parentNode.removeChild(this.penCanvas.foreignObject),this.penCanvas.container&&this.penCanvas.container.parentNode&&this.penCanvas.container.parentNode.removeChild(this.penCanvas.container)),this.penCanvasCleanup&&(this.penCanvasCleanup(),this.penCanvasCleanup=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this._removeStepVisualizerListeners(),this.popupAnimationId&&(cancelAnimationFrame(this.popupAnimationId),this.popupAnimationId=null),this.popup=null,this.popupBackground=null,this.popupTextInput=null,this.penCanvas=null,this.penButton=null,this.textButton=null,this.clearButton=null,this.submitButton=null}destroy(){return this.hide()}debugCanvasPosition(){if(this.penCanvas&&this.penCanvas.container){const e=this.penCanvas.container;e.style.border="3px solid #00ff00",setTimeout(()=>{e.style.border="2px solid #ff0000"},1e3)}}centerCanvas(){if(this.penCanvas&&this.penCanvas.container){const e=this.penCanvas.container,t=(window.innerWidth-280)/2,r=(window.innerHeight-60)/2;e.style.left=`${t}px`,e.style.top=`${r}px`}}_setupResizeObserver(){!this.penCanvas||!this.popup||!this.popup.svgObject||(this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this._updateCanvasPosition()}),this.resizeObserver.observe(this.popup.svgObject),this.parentElement&&this.parentElement.svgObject&&this.resizeObserver.observe(this.parentElement.svgObject),this.resizeObserver.observe(document.body))}_setupStepVisualizerListeners(){this.penCanvas&&(this._stepVisualizerUpdateHandler=()=>{console.log("[Step Visualizer Debug] Layout change detected, updating canvas position"),setTimeout(()=>this._updateCanvasPosition(),50)},document.addEventListener("click",this._stepVisualizerUpdateHandler),window.addEventListener("resize",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&this.parentElement.element.addEventListener("stepVisualizerChanged",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&(this._mutationObserver=new MutationObserver(e=>{let t=!1;for(const r of e){if(r.type==="attributes"&&(r.attributeName==="style"||r.attributeName==="class"||r.attributeName==="transform")){console.log("[Step Visualizer Debug] Mutation detected:",r.attributeName,r.target),t=!0;break}if(r.type==="childList"&&(r.addedNodes.length>0||r.removedNodes.length>0)){console.log("[Step Visualizer Debug] Child list mutation detected"),t=!0;break}}t&&setTimeout(()=>this._updateCanvasPosition(),10)}),this._mutationObserver.observe(this.parentElement.element,{childList:!0,attributes:!0,subtree:!0,attributeFilter:["style","class","transform","viewBox"]})))}_removeStepVisualizerListeners(){this._stepVisualizerUpdateHandler&&(document.removeEventListener("click",this._stepVisualizerUpdateHandler),window.removeEventListener("resize",this._stepVisualizerUpdateHandler),this.parentElement&&this.parentElement.element&&this.parentElement.element.removeEventListener("stepVisualizerChanged",this._stepVisualizerUpdateHandler),this._stepVisualizerUpdateHandler=null),this._mutationObserver&&(this._mutationObserver.disconnect(),this._mutationObserver=null)}_updateCanvasPosition(){var r,i;if(!this.penCanvas||!this.penCanvas.container||!this.popup)return;const e=this.penCanvas.container,t=this.popup.svgObject?this.popup.svgObject.getBoundingClientRect():null;if(console.log("[Canvas Position Debug] Update triggered:",{hasCanvas:!!this.penCanvas,hasContainer:!!e,strokeCount:((i=(r=this.penCanvas)==null?void 0:r.strokes)==null?void 0:i.size)||0,popupRect:t?`${t.width}x${t.height}`:"null"}),t&&t.width>0&&t.height>0){const s=this.buttonSize+this.margin*2,a=this.buttonSize*2+this.margin*2+this.margin,o=Math.max(t.width-s-a,this.canvasMinWidth),l=Math.max(t.height-this.margin*2-this.buttonSize*2-this.buttonSpacing,this.canvasMinHeight),u=t.left+s,c=t.top+this.margin,h=t.width-s-a,f=t.height-this.margin*2-this.buttonSize*2-this.buttonSpacing,d=Math.min(Math.max(o,this.canvasMinWidth),h),p=Math.min(Math.max(l,this.canvasMinHeight),f);console.log("[Canvas Position Debug] Moving canvas:",{from:`${e.style.left}, ${e.style.top}`,to:`${u}px, ${c}px`,size:`${d}x${p}`}),e.style.left=`${u}px`,e.style.top=`${c}px`,e.style.width=`${d}px`,e.style.height=`${p}px`,setTimeout(()=>{var m,y;console.log("[Canvas Position Debug] After move stroke count:",((y=(m=this.penCanvas)==null?void 0:m.strokes)==null?void 0:y.size)||0)},50)}}async _downloadCanvasAsBitmap(){if(this.penCanvas)try{const e=this.penCanvas.svg;if(!e)return;const t=document.createElement("canvas"),r=t.getContext("2d"),i=e.getBoundingClientRect();t.width=i.width,t.height=i.height;const s=new XMLSerializer().serializeToString(e),a=new Blob([s],{type:"image/svg+xml;charset=utf-8"}),o=URL.createObjectURL(a),l=new Image;l.onload=async()=>{r.drawImage(l,0,0),t.toBlob(async u=>{URL.revokeObjectURL(o),await this._transcribeCanvas(u)},"image/png")},l.src=o}catch{}}async _transcribeCanvas(e){try{const{omdTranscriptionService:t}=await Promise.resolve().then(()=>Gq),r=new t({defaultProvider:"gemini"});if(!r.isAvailable())return;const i=await r.transcribeWithFallback(e,{prompt:"Transcribe this handwritten mathematical expression. Return ONLY the pure mathematical expression with no formatting, no LaTeX, no dollar signs, no explanations. Use ^ for powers (e.g., 3^2), use / for fractions (e.g., (2x+1)/(x-3)), use * for multiplication, use + and - for addition/subtraction. Return only the expression."});i.text?(this._setSubmitButtonLoading(!1),this.flashValidation(!0),this.transcribedText=i.text,this.onValidateCallback&&this.onValidateCallback()):this._setSubmitButtonLoading(!1)}catch{this.flashValidation(!1),this._setSubmitButtonLoading(!1)}}_setSubmitButtonLoading(e){this.submitButton&&(e?this._startBlinkingAnimation():(this._stopBlinkingAnimation(),this.submitButton.setText("✓"),this.submitButton.setFillColor("#2ECC71"),this.submitButton.setFontColor("white")))}_startBlinkingAnimation(){if(!this.submitButton)return;let e=!0;const t=()=>{e?this.submitButton.setFillColor("#FFA500"):this.submitButton.setFillColor("#2ECC71"),e=!e,this.blinkAnimationId=setTimeout(t,300)};t()}_stopBlinkingAnimation(){this.blinkAnimationId&&(clearTimeout(this.blinkAnimationId),this.blinkAnimationId=null)}repositionCanvasRelativeToPopup(){this._updateCanvasPosition()}}class ey extends Oe{constructor(e={}){super(),this.options={fillColor:"white",strokeColor:"black",strokeWidth:2,opacity:1,padding:0,cornerRadius:4,overlayType:"rectangle",animated:!1,animationDuration:300,text:"",editable:!1,...e},this.targetNode=null,this.overlayElement=null,this.textElement=null,this.isVisible=!1,this.animationId=null,this.clickLayer=null,this.savedHandlers=[],this.omdPopup=null,this._createOverlayElement()}_createOverlayElement(){switch(this.options.overlayType){case"rectangle":this.overlayElement=new yt,this.options.cornerRadius>0&&this.overlayElement.setCornerRadius(this.options.cornerRadius);break;case"ellipse":this.overlayElement=new jsvgEllipse;break;case"text":this._createTextOverlay();return;default:this.overlayElement=new yt}this.overlayElement.setFillColor(this.options.fillColor),this.overlayElement.setStrokeColor(this.options.strokeColor),this.overlayElement.setStrokeWidth(this.options.strokeWidth),this.overlayElement.setOpacity(this.options.opacity),this.addChild(this.overlayElement),this.setOpacity(0)}_createTextOverlay(){this.overlayElement=new yt,this.options.cornerRadius>0&&this.overlayElement.setCornerRadius(this.options.cornerRadius),this.overlayElement.setFillColor(this.options.fillColor),this.overlayElement.setStrokeColor(this.options.strokeColor),this.overlayElement.setStrokeWidth(this.options.strokeWidth),this.overlayElement.setOpacity(this.options.opacity),this.addChild(this.overlayElement),this.options.editable&&(this.clickLayer=new yt,this.clickLayer.setWidthAndHeight(this.overlayElement.width,this.overlayElement.height),this.clickLayer.setPosition(0,0),this.clickLayer.setFillColor("transparent"),this.clickLayer.setStrokeColor("transparent"),this.addChild(this.clickLayer),this.clickLayer.setClickCallback(()=>{this.togglePopup()})),this.options.editable?this.textElement=null:(this.textElement=new jsvgTextLine,this.textElement.setText(this.options.text),this.textElement.setTextAnchor("middle"),this.textElement.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(this.textElement)),this.setOpacity(0)}coverNode(e){if(!e)return console.warn("omdNodeOverlay: Cannot cover null or undefined node"),this;this.targetNode=e,this.savedHandlers=[];let t=this.targetNode;for(;t;)t.svgObject&&typeof t.svgObject.onmouseenter=="function"&&(this.savedHandlers.push({element:t.svgObject,onmouseenter:t.svgObject.onmouseenter,onmouseleave:t.svgObject.onmouseleave}),t.svgObject.onmouseenter=null,t.svgObject.onmouseleave=null),t=t.parent;return this.targetNode.parent&&e.parent.addChild(this),this._updateOverlayPosition(),this}setCoverArea(e,t,r,i,s=!0){s&&(this.targetNode=null);const a=this.options.padding||0,o=e-a,l=t-a,u=r+a*2,c=i+a*2;return this.setPosition(o,l),this.overlayElement.setWidthAndHeight(u,c),this.clickLayer&&this.clickLayer.setWidthAndHeight(u,c),this.options.overlayType==="text"&&this.textElement&&this.textElement.setPosition(u/2,c/2),this}_updateOverlayPosition(){if(!this.targetNode)return;let e;this.parent===this.targetNode.parent?e={x:this.targetNode.xpos||this.targetNode.x||0,y:this.targetNode.ypos||this.targetNode.y||0}:e=this._getGlobalPosition(this.targetNode);let t=this.targetNode.width||0,r=this.targetNode.height||0;this.targetNode.backRect&&(t=this.targetNode.backRect.width||t,r=this.targetNode.backRect.height||r),this.setCoverArea(e.x,e.y,t,r,!1)}_matchNodeProperties(){if(this.targetNode){if(this.options.overlayType==="rectangle"&&this.overlayElement.setCornerRadius){let e=0;if(this.targetNode.backRect&&this.targetNode.backRect.cornerRadius!==void 0)e=this.targetNode.backRect.cornerRadius;else if(this.targetNode.svgObject){const t=this.targetNode.svgObject.getAttribute("rx"),r=this.targetNode.svgObject.getAttribute("ry");e=parseFloat(t||r||0)}else if(this.targetNode.svgObject&&this.targetNode.svgObject.tagName==="rect"){const t=this.targetNode.svgObject.getAttribute("rx"),r=this.targetNode.svgObject.getAttribute("ry");e=parseFloat(t||r||0)}e>0&&(this.overlayElement.setCornerRadius(e),this.options.cornerRadius=e)}if(this.options.overlayType==="text"&&this.textElement&&this._matchFontProperties(),this.targetNode.svgObject&&!this.options.preserveStrokeWidth){const e=this.targetNode.svgObject.getAttribute("stroke-width");if(e){const t=parseFloat(e);t>0&&this.overlayElement.setStrokeWidth(t)}}}}_matchFontProperties(){if(!this.targetNode||!this.textElement)return;let e=32;if(this.targetNode.getFontSize&&typeof this.targetNode.getFontSize=="function"?e=this.targetNode.getFontSize():this.targetNode.fontSize&&(e=this.targetNode.fontSize),this.textElement.setFontSize(e),this.targetNode.textElement){const t=this.targetNode.textElement.svgObject;if(t){const r=t.style.fontFamily||"Arial, Helvetica, sans-serif";this.textElement.setFontFamily(r);const i=t.style.fill||t.getAttribute("fill")||"black";this.textElement.setFontColor?this.textElement.setFontColor(i):this.textElement.div&&(this.textElement.div.style.color=i);const s=t.style.fontWeight;s&&this.textElement.setFontWeight?this.textElement.setFontWeight(s):s&&this.textElement.div&&(this.textElement.div.style.fontWeight=s)}}}_getGlobalPosition(e){if(e.svgObject&&e.svgObject.getCTM)try{const s=e.svgObject.getCTM();if(s)return{x:s.e,y:s.f}}catch{}let t=e.xpos||e.x||0,r=e.ypos||e.y||0,i=e.parent;for(;i&&i.xpos!==void 0;)t+=i.xpos||i.x||0,r+=i.ypos||i.y||0,i=i.parent;return{x:t,y:r}}_createPopup(){!this.options.editable||this.omdPopup||(this.omdPopup=new Wq(this.targetNode,this.parent,{animationDuration:this.options.animationDuration}),this.omdPopup.setValue(this.options.text),this.omdPopup.setValidationCallback(()=>{const e=this.omdPopup.getValue();if(this.targetNode){const t=this.targetNode.text||this.targetNode.toString()||"";this.omdPopup.areExpressionsEquivalent(e.trim(),t.trim())?(this.omdPopup.flashValidation(!0),setTimeout(()=>{this.destroy()},500)):this.omdPopup.flashValidation(!1)}}),this.omdPopup.setClearCallback(()=>{this.omdPopup.setValue("")}))}togglePopup(){if(!this.options.editable)return Promise.resolve();this.omdPopup||this._createPopup();const e=this.xpos||this.x||0,t=this.ypos||this.y||0,r=this.overlayElement.width||this.targetNode.width||100,i=this.overlayElement.height||this.targetNode.height||40,a=e+r/2-400/2,o=t+i+10;return this.omdPopup.toggle(a,o)}_hidePopup(){this.omdPopup&&(this.omdPopup.destroy(),this.omdPopup=null)}show(e=this.options.animated){return new Promise(t=>{if(this.isVisible){t();return}this.isVisible=!0,e?this._animateOpacity(0,this.options.opacity,this.options.animationDuration).then(t):(this.setOpacity(this.options.opacity),t())})}_animateOpacity(e,t,r){return new Promise(i=>{this.animationId&&cancelAnimationFrame(this.animationId);const s=performance.now(),a=t-e,o=l=>{const u=l-s,c=Math.min(u/r,1),h=1-Math.pow(1-c,3),f=e+a*h;this.setOpacity(f),c<1?this.animationId=requestAnimationFrame(o):(this.animationId=null,i())};this.animationId=requestAnimationFrame(o)})}destroy(e=this.options.animated){return new Promise(t=>{e&&this.isVisible?this._animateOpacity(this.options.opacity,0,this.options.animationDuration).then(()=>{this._performDestroy(),t()}):(this._performDestroy(),t())})}_performDestroy(){this.animationId&&cancelAnimationFrame(this.animationId),this.savedHandlers.forEach(({element:e,onmouseenter:t,onmouseleave:r})=>{e&&(e.onmouseenter=t,e.onmouseleave=r)}),this._hidePopup(),this.targetNode=null,this.isVisible=!1,this.parent&&this.parent.removeChild(this)}getIsVisible(){return this.isVisible}getTargetNode(){return this.targetNode}setText(e){return this.textElement&&(this.textElement.setText(e),this.options.text=e),this}getText(){return this.textElement?this.textElement.getText():this.options.text}}class jq{static createHidingOverlay(e=!1,t=null){const r={fillColor:"white",strokeColor:"black",strokeWidth:2,padding:1,animated:!0};return e&&(r.overlayType="text",r.text=t||"",r.editable=!0,r.fillColor="white",r.strokeColor="black",r.strokeWidth=2),new ey(r)}static createHighlightOverlay(e="#ffff00"){return new ey({fillColor:"none",strokeColor:e,strokeWidth:3,padding:2,cornerRadius:4,animated:!0})}}class wE{constructor(e={}){this.options={endpoint:e.endpoint||this._getDefaultEndpoint(),defaultProvider:e.defaultProvider||"openai",defaultModel:e.defaultModel||"gpt-4o",...e}}_getDefaultEndpoint(){return"/.netlify/functions/transcribe"}async _blobToBase64(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>{const s=i.result.split(",")[1];t(s)},i.onerror=r,i.readAsDataURL(e)})}async transcribe(e,t={}){try{const r=await this._blobToBase64(e),i=await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({imageBase64:r,prompt:t.prompt||"Please transcribe the handwritten mathematical expression in this image. Return only the mathematical expression in pure format (no LaTeX, no dollar signs). For powers use ^, for fractions use /, for square roots use sqrt().",model:t.model||this.options.defaultModel,provider:t.provider||this.options.defaultProvider})});if(!i.ok)throw new Error(`Transcription API error: ${i.status} ${i.statusText}`);const s=await i.json();return{text:(s.text||"").trim(),provider:s.provider||this.options.defaultProvider,model:s.model||t.model||this.options.defaultModel,confidence:s.confidence||1}}catch(r){throw console.error("Transcription error:",r),r}}async transcribeWithFallback(e,t={}){return this.transcribe(e,t)}isAvailable(){return!0}getAvailableProviders(){return["openai"]}isProviderAvailable(e){return e==="openai"}}const Gq=Object.freeze(Object.defineProperty({__proto__:null,omdTranscriptionService:wE},Symbol.toStringTag,{value:"Module"}));class ty extends Oe{constructor(){super(),this.type="omdTable",this.equation="",this.data=[],this.headers=["x","y"],this.xMin=-5,this.xMax=5,this.stepSize=1,this.title="",this.fontSize=14,this.headerFontSize=16,this.fontFamily="Albert Sans",this.headerFontFamily="Albert Sans",this.cellHeight=35,this.headerHeight=40,this.minCellWidth=80,this.maxCellWidth=300,this.padding=10,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=15,this.backgroundOpacity=1,this.showBackground=!0,this.alternatingRowColors=[Fe.mediumGray,Fe.lightGray],this.headerBackgroundColor=Fe.lightGray,this.cellBackgroundColor="white",this.evenRowColor="rgba(255,255,255,0.5)",this.oddRowColor="transparent",this.alternatingRowOpacity=1,this.updateLayout()}estimateTitleWidth(){if(!this.title||this.title.length===0)return 0;const e=this.headerFontSize+2,t=40,r=200,i=Math.round(this.title.length*(e*.6))+t;return Math.max(r,i)}loadFromJSON(e){typeof e.equation<"u"&&(this.equation=e.equation),typeof e.data<"u"&&(this.data=e.data),typeof e.headers<"u"&&(this.headers=e.headers),typeof e.xMin<"u"&&(this.xMin=e.xMin),typeof e.xMax<"u"&&(this.xMax=e.xMax),typeof e.stepSize<"u"&&(this.stepSize=e.stepSize),typeof e.title<"u"&&(this.title=e.title),typeof e.fontSize<"u"&&(this.fontSize=e.fontSize),typeof e.headerFontSize<"u"&&(this.headerFontSize=e.headerFontSize),typeof e.fontFamily<"u"&&(this.fontFamily=e.fontFamily),typeof e.headerFontFamily<"u"&&(this.headerFontFamily=e.headerFontFamily),typeof e.cellHeight<"u"&&(this.cellHeight=e.cellHeight),typeof e.headerHeight<"u"&&(this.headerHeight=e.headerHeight),typeof e.minCellWidth<"u"&&(this.minCellWidth=e.minCellWidth),typeof e.maxCellWidth<"u"&&(this.maxCellWidth=e.maxCellWidth),typeof e.padding<"u"&&(this.padding=e.padding),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.backgroundCornerRadius<"u"&&(this.backgroundCornerRadius=e.backgroundCornerRadius),typeof e.backgroundOpacity<"u"&&(this.backgroundOpacity=e.backgroundOpacity),typeof e.showBackground<"u"&&(this.showBackground=e.showBackground),typeof e.alternatingRowColors<"u"&&(this.alternatingRowColors=e.alternatingRowColors,console.log("LoadFromJSON - Setting alternatingRowColors to:",this.alternatingRowColors)),typeof e.evenRowColor<"u"&&(this.evenRowColor=e.evenRowColor),typeof e.oddRowColor<"u"&&(this.oddRowColor=e.oddRowColor),typeof e.alternatingRowOpacity<"u"&&(this.alternatingRowOpacity=e.alternatingRowOpacity),this.updateLayout()}setEquation(e){this.equation=e,this.updateLayout()}setData(e,t){this.data=e,t&&(this.headers=t),this.updateLayout()}calculateOptimalCellWidth(e){let t=(this.headers[e]??"").toString().length;for(let i of this.data){const s=i[e];s!=null&&(t=Math.max(t,s.toString().length))}const r=Math.max(t*8+this.padding*2,this.minCellWidth);return Math.min(r,this.maxCellWidth)}generateDataFromEquation(){if(!this.equation||this.equation.trim().length===0)return;this.data=[],this.headers=["x","y"];let e=this.equation;e=e.replace(/^\s*y\s*=\s*/i,"").replace(/\s*=\s*y\s*$/i,"");try{if(typeof math<"u"&&math.compile){const t=math.compile(e);for(let r=this.xMin;r<=this.xMax;r+=this.stepSize)try{let i=t.evaluate({x:r});i=Math.round(i*100)/100,this.data.push([r,i])}catch{}return}}catch(t){console.warn("math.js evaluation failed, falling back to simple parser:",t)}e=e.replace(/(\d)([a-z])/gi,"$1*$2").replace(/([a-z])(\d)/gi,"$1*$2").replace(/\^/g,"**");try{const t=new Function("x",`return ${e};`);for(let r=this.xMin;r<=this.xMax;r+=this.stepSize){let i=t(r);i=Math.round(i*100)/100,this.data.push([r,i])}}catch(t){console.error("Error generating table data from equation:",t)}}updateLayout(){console.log("updateLayout called - alternatingRowColors:",this.alternatingRowColors),console.log("alternatingRowColors type:",typeof this.alternatingRowColors),console.log("alternatingRowColors isArray:",Array.isArray(this.alternatingRowColors)),this.removeAllChildren(),this.equation&&this.equation.length>0&&this.generateDataFromEquation();const e=this.headers.length,t=this.data.length;let r=[],i=0;for(let S=0;S<e;S++){const g=this.calculateOptimalCellWidth(S);r.push(g),i+=g}this.width=i;const s=this.title&&this.title.length>0?30:0,a=this.headerHeight+t*this.cellHeight,o=s+a;this.height=o;const l=this.estimateTitleWidth(),u=Math.max(this.width,l),c=Math.max(0,(u-this.width)/2);let h;if(this.backgroundCornerRadius>0){const S=new Ho(this.width,a,this.backgroundCornerRadius);if(S.setPosition(c,s),this.addChild(S),h=S,this.showBackground){const g=new yt;g.setWidthAndHeight(this.width,a),g.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&g.setOpacity(this.backgroundOpacity),g.setStrokeWidth(0),g.setPosition(0,0),h.addChild(g)}}else{if(this.showBackground){const S=new yt;S.setWidthAndHeight(this.width,a),S.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&S.setOpacity(this.backgroundOpacity),S.setStrokeWidth(0),S.setPosition(c,s),this.addChild(S)}h=this}this.equation&&this.equation.length>0&&this.generateDataFromEquation();let f=0;if(this.title&&this.title.length>0){var d=new Bt;d.setWidthAndHeight(l,25),d.setText(this.title),d.setFontFamily(this.headerFontFamily),d.setFontColor("black"),d.setFontSize(this.headerFontSize+2),d.setAlignment("center"),d.setVerticalCentering();const S=Math.max(0,(u-l)/2);d.setPosition(S,f),d.setFontWeight(600),this.addChild(d),f+=30}let p=0;const m=0;if(this.alternatingRowColors&&Array.isArray(this.alternatingRowColors)&&this.alternatingRowColors.length>0){console.log("Creating header background with color:",this.alternatingRowColors[0]);const S=new yt;S.setWidthAndHeight(this.width,this.headerHeight),S.setFillColor(this.alternatingRowColors[0]),S.setCornerRadius(0),S.setStrokeWidth(0),S.setPosition(0,m),h.addChild(S)}else console.log("NOT creating header background - alternatingRowColors:",this.alternatingRowColors);for(let S=0;S<e;S++){const g=r[S];if(!this.alternatingRowColors||!Array.isArray(this.alternatingRowColors)||this.alternatingRowColors.length===0){var y=new yt;y.setWidthAndHeight(g,this.headerHeight),y.setFillColor(this.headerBackgroundColor||Fe.lightGray),y.setCornerRadius(0),y.setStrokeWidth(0),y.setPosition(p,m),h.addChild(y)}const b=this.createHeaderTextBox(g,this.headerHeight,this.headers[S]||`Col ${S+1}`);b.setPosition(p,m),h.addChild(b),p+=g}f+=this.headerHeight;for(let S=0;S<t;S++){const g=this.data[S];let b=0;const w=this.headerHeight+S*this.cellHeight;if(this.alternatingRowColors&&Array.isArray(this.alternatingRowColors)&&this.alternatingRowColors.length>0){const x=(S+1)%this.alternatingRowColors.length,N=this.alternatingRowColors[x];console.log(`Creating row ${S} background with color:`,N,"at position:",0,w);var v=new yt;v.setWidthAndHeight(this.width,this.cellHeight),v.setFillColor(N),this.backgroundOpacity<1&&v.setOpacity(this.backgroundOpacity),v.setCornerRadius(0),v.setStrokeWidth(0),v.setPosition(0,w),h.addChild(v)}else console.log(`Row ${S}: No alternating colors - alternatingRowColors:`,this.alternatingRowColors);for(let x=0;x<e;x++){const N=r[x],D=this.createBodyTextBox(N,this.cellHeight,""),C=g[x];D.setText((C??"").toString()),D.setPosition(b,w),h.addChild(D),b+=N}f+=this.cellHeight}if(e>1){let S=0;for(let g=0;g<e-1;g++){S+=r[g];const b=new yt;b.setWidthAndHeight(1,Math.max(0,a-1)),b.setFillColor("black"),b.setCornerRadius(0),b.setOpacity(.5),b.setStrokeWidth(0),b.setPosition(S,0),h.addChild(b)}}this.setWidthAndHeight(u,o),this.svgObject.setAttribute("viewBox",`0 0 ${u} ${o}`)}createHeaderTextBox(e,t,r){const i=new Bt;return i.setWidthAndHeight(e,t),i.setText(r),i.setFontFamily(this.headerFontFamily),i.setFontColor("black"),i.setFontSize(this.headerFontSize),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(600),i}createBodyTextBox(e,t,r){const i=new Bt;return i.setWidthAndHeight(e,t),i.setText(r),i.setFontFamily(this.fontFamily),i.setFontColor("black"),i.setFontSize(this.fontSize),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(400),i}addRow(e){this.data.push(e),this.updateLayout()}setHeaders(e){this.headers=e,this.updateLayout()}setFont(e,t){this.fontFamily=e,t?this.headerFontFamily=t:this.headerFontFamily=e,this.updateLayout()}clearData(){this.data=[],this.updateLayout()}setBackgroundColor(e){this.backgroundColor=e,this.updateLayout()}setBackgroundCornerRadius(e){this.backgroundCornerRadius=e,this.updateLayout()}setBackgroundOpacity(e){this.backgroundOpacity=Math.max(0,Math.min(1,e)),this.updateLayout()}setShowBackground(e){this.showBackground=e,this.updateLayout()}setBackgroundStyle(e={}){e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.cornerRadius!==void 0&&(this.backgroundCornerRadius=e.cornerRadius),e.opacity!==void 0&&(this.backgroundOpacity=Math.max(0,Math.min(1,e.opacity))),e.show!==void 0&&(this.showBackground=e.show),this.updateLayout()}setAlternatingRowColors(e){console.log("setAlternatingRowColors called with:",e),this.alternatingRowColors=e,console.log("alternatingRowColors set to:",this.alternatingRowColors),this.updateLayout()}setHeaderBackgroundColor(e){this.headerBackgroundColor=e,this.updateLayout()}setCellBackgroundColor(e){this.cellBackgroundColor=e,this.updateLayout()}}class Oa extends Oe{constructor(){super(),this.type="omdBalanceHanger",this.leftValues=[],this.rightValues=[],this.tilt="none",this.fontFamily="Albert Sans",this.fontSize=18,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=5,this.backgroundOpacity=1,this.showBackground=!0,this.updateLayout()}loadFromJSON(e){typeof e.leftValues<"u"&&(this.leftValues=e.leftValues),typeof e.rightValues<"u"&&(this.rightValues=e.rightValues),typeof e.tilt<"u"&&(this.tilt=e.tilt),typeof e.fontFamily<"u"&&(this.fontFamily=e.fontFamily),typeof e.fontSize<"u"&&(this.fontSize=e.fontSize),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.backgroundCornerRadius<"u"&&(this.backgroundCornerRadius=e.backgroundCornerRadius),typeof e.backgroundOpacity<"u"&&(this.backgroundOpacity=e.backgroundOpacity),typeof e.showBackground<"u"&&(this.showBackground=e.showBackground),this.updateLayout()}setLeftAndRightValues(e,t){this.leftValues=e,this.rightValues=t}updateLayout(){this.removeAllChildren();var e=Math.max(this.leftValues.length,this.rightValues.length),t=50,r=0;this.tilt=="left"&&(r=-10),this.tilt=="right"&&(r=10);var i=20,s=e>0?(e-1)*40+30:0,a=t*2,o=Math.abs(r)+i+s;this.line=new Ut,this.line.setStrokeColor("black"),this.line.setStrokeWidth(1),this.line.setEndpoints(-t,r,t,-r),this.addChild(this.line);var l=new Ut;l.setStrokeColor("black"),l.setStrokeWidth(1),l.setEndpoints(-t,r,-t,r+i+40*(this.leftValues.length-1)),this.addChild(l);var u=new Ut;u.setStrokeColor("black"),u.setStrokeWidth(1),u.setEndpoints(t,-r,t,-r+i+40*(this.rightValues.length-1)),this.addChild(u);var c=new Tr;c.setWidthAndHeight(10,10),c.setFillColor("black"),c.setPosition(0,0),this.addChild(c),this.makeValueStack(this.leftValues,-t,r+i),this.makeValueStack(this.rightValues,t,-r+i);const h=40,f=Math.max(300,a+h),d=Math.max(200,o+h);this.setWidthAndHeight(f,d),this.svgObject.setAttribute("viewBox",`${-f/2} ${-d/2} ${f} ${d}`)}makeValueStack(e,t,r){for(var i=0;i<e.length;i++){var s=e[i],a=30;typeof s=="string"?a=20+s.length*10:a=30;var o;typeof s=="string"?(o=new Tr,o.setWidthAndHeight(a,30),o.setPosition(t-a/2+a/2,r+i*40+15)):(o=new yt,o.setWidthAndHeight(a,30),o.setCornerRadius(5),o.setPosition(t-a/2,r+i*40)),this.showBackground?(o.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&o.setOpacity(this.backgroundOpacity)):o.setFillColor("transparent"),this.backgroundCornerRadius>0&&o.setCornerRadius&&o.setCornerRadius(this.backgroundCornerRadius),this.addChild(o);var l=new Bt;l.setWidthAndHeight(a,30),l.setText(this.name),l.setFontFamily(this.fontFamily),l.setFontColor("black"),l.setFontSize(this.fontSize),l.setAlignment("center"),l.setVerticalCentering(),l.setText(s),l.setPosition(t-a/2,r+i*40),this.addChild(l)}}setFont(e,t){this.fontFamily=e,t&&(this.fontSize=t),this.updateLayout()}}const Xq=10,Yq=38;function ry(n){return n?Yq:Xq}function Jq(n){const e=Array.isArray(n==null?void 0:n.points)?n.points:[];if(e.length<=1)return e.slice();const t=e[0],r=e[e.length-1];return t.x===r.x&&t.y===r.y?e.slice(0,-1):e.slice()}function Zq(n){if(!n.length)return{x:0,y:0};let e=0,t=0;for(const r of n)e+=r.x,t+=r.y;return{x:e/n.length,y:t/n.length}}class ks extends Oe{constructor(){super(),this.type="omdRightTriangle",this.horizontalLeg=5,this.verticalLeg=10,this.angleA=0,this.angleB=0,this.hypotenuse=0,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){if(typeof e.horizontalLeg<"u"&&(this.horizontalLeg=e.horizontalLeg),typeof e.verticalLeg<"u"&&(this.verticalLeg=e.verticalLeg),typeof e.angleA<"u"&&(this.angleA=e.angleA),typeof e.angleB<"u"&&(this.angleB=e.angleB),typeof e.hypotenuse<"u"&&(this.hypotenuse=e.hypotenuse),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.angleA&&this.hypotenuse){var t=Math.PI*this.angleA/180;this.horizontalLeg=Math.cos(t)*this.hypotenuse,this.verticalLeg=Math.sin(t)*this.hypotenuse}this.updateLayout()}updateLayout(){const e=ry(this.showLabels),t=e,r=this.unitScale*this.verticalLeg+e;if(this.shapePath.clearPoints(),this.shapePath.addPoint(t,r),this.shapePath.addPoint(t+this.unitScale*this.horizontalLeg,r),this.shapePath.addPoint(t+this.unitScale*this.horizontalLeg,r-this.unitScale*this.verticalLeg),this.shapePath.addPoint(t,r),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var i=new Xo,s=this.horizontalLeg.toString(),a=this.verticalLeg.toString(),o="";i.initializeWithShapePath(this.shapePath,[s,a,o]),this.labelsHolder.addChild(i)}this.width=this.unitScale*this.horizontalLeg+e*2,this.height=this.unitScale*this.verticalLeg+e*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Ps extends Oe{constructor(){super(),this.type="omdIsoscelesTriangle",this.triangleBase=5,this.triangleHeight=10,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.base<"u"&&(this.triangleBase=e.base),typeof e.height<"u"&&(this.triangleHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){this.shapePath.clearPoints();const e=this.unitScale*this.triangleBase,t=this.unitScale*this.triangleHeight,r=ry(this.showLabels),i=r,s=t+r;if(this.shapePath.addPoint(i,s),this.shapePath.addPoint(i+e,s),this.shapePath.addPoint(i+e*.5,s-t),this.shapePath.addPoint(i,s),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var a=new Xo;a.initializeWithShapePath(this.shapePath),this.labelsHolder.addChild(a)}this.width=this.unitScale*this.triangleBase+r*2,this.height=this.unitScale*this.triangleHeight+r*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class zs extends Oe{constructor(){super(),this.type="omdRectangle",this.rectWidth=10,this.rectHeight=10,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.width<"u"&&(this.rectWidth=e.width),typeof e.height<"u"&&(this.rectHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=ry(this.showLabels),t=e,r=this.unitScale*this.rectHeight+e;if(this.shapePath.clearPoints(),this.shapePath.addPoint(t,r),this.shapePath.addPoint(t+this.unitScale*this.rectWidth,r),this.shapePath.addPoint(t+this.unitScale*this.rectWidth,r-this.unitScale*this.rectHeight),this.shapePath.addPoint(t,r-this.unitScale*this.rectHeight),this.shapePath.addPoint(t,r),this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var i=new Xo,s=this.rectWidth.toString(),a=this.rectHeight.toString();i.initializeWithShapePath(this.shapePath,[s,a,"",""]),this.labelsHolder.addChild(i)}this.width=this.unitScale*this.rectWidth+e*2,this.height=this.unitScale*this.rectHeight+e*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Rs extends Oe{constructor(){super(),this.type="omdEllipse",this.rectWidth=10,this.rectHeight=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Tr,this.shapePath.setWidthAndHeight(this.rectWidth*this.unitScale,this.rectHeight*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.width<"u"&&(this.rectWidth=e.width),typeof e.height<"u"&&(this.rectHeight=e.height),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=this.rectWidth*this.unitScale,t=this.rectHeight*this.unitScale;if(this.shapePath.setWidthAndHeight(e,t),this.shapePath.setPosition(e*.5+10,t*.5+10),this.labelsHolder.removeAllChildren(),this.showLabels){const r=new si;r.setAlignment("center"),r.setFontFamily("Albert Sans"),r.setFontColor("black"),r.setFontSize(12),r.setPosition(e*.5+10,t*.5+14),r.setText(`${this.rectWidth} × ${this.rectHeight}`),this.labelsHolder.addChild(r)}this.width=this.rectWidth*this.unitScale+20,this.height=this.rectHeight*this.unitScale+20,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Ls extends Oe{constructor(){super(),this.type="omdCircle",this.radius=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Tr,this.shapePath.setWidthAndHeight(this.radius*this.unitScale,this.radius*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.radius<"u"&&(this.radius=e.radius),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){const e=2*this.radius*this.unitScale,t=this.radius*this.unitScale,r=t+10,i=t+10;if(this.shapePath.setWidthAndHeight(e,e),this.shapePath.setPosition(r,i),this.labelsHolder.removeAllChildren(),this.showLabels){const s=-Math.PI/6,a=r+Math.cos(s)*t*.82,o=i+Math.sin(s)*t*.82,l=new Ut;l.setStrokeColor("black"),l.setStrokeWidth(1.5),l.setEndpoints(r,i,a,o),this.labelsHolder.addChild(l);const u=new si;u.setAlignment("center"),u.setFontFamily("Albert Sans"),u.setFontColor("black"),u.setFontSize(12),u.svgObject.setAttribute("dominant-baseline","middle"),u.setRotation(s*180/Math.PI),u.setPosition((r+a)*.5+3,(i+o)*.5-4),u.setText(`r=${this.radius}`),this.labelsHolder.addChild(u)}this.width=2*this.radius*this.unitScale+20,this.height=2*this.radius*this.unitScale+20,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Is extends Oe{constructor(){super(),this.type="omdRegularPolygon",this.radius=5,this.numberOfSides=5,this.unitScale=10,this.showLabels=!1,this.shapePath=new Ni,this.shapePath.setWidthAndHeight(this.radius*this.unitScale,this.radius*this.unitScale),this.shapePath.setStrokeColor("black"),this.shapePath.setStrokeWidth(2),this.shapePath.setFillColor(Fe.lightGray),this.addChild(this.shapePath),this.labelsHolder=new Oe,this.addChild(this.labelsHolder),this.updateLayout()}loadFromJSON(e){typeof e.radius<"u"&&(this.radius=e.radius),typeof e.numberOfSides<"u"&&(this.numberOfSides=e.numberOfSides),typeof e.unitScale<"u"&&(this.unitScale=e.unitScale),typeof e.showLabels<"u"&&(this.showLabels=e.showLabels),this.updateLayout()}updateLayout(){this.shapePath.clearPoints();const e=this.radius*this.unitScale,t=this.showLabels?48:14,r=e+t,i=e+t;var s=0;this.numberOfSides%2==1&&(s=Math.PI/this.numberOfSides*.5,(this.numberOfSides-1)/2%2==0&&(s*=-1));for(var a=0;a<=this.numberOfSides;a++){var o=-2*Math.PI/this.numberOfSides*a;o+=s;var l=r+Math.cos(o)*e,u=i+Math.sin(o)*e;this.shapePath.addPoint(l,u)}if(this.shapePath.updatePath(),this.showLabels){this.labelsHolder.removeAllChildren();var c=new Xo,h=2*this.radius*Math.sin(Math.PI/this.numberOfSides),o=h.toFixed(2);c.initializeWithShapePath(this.shapePath,[o]),this.labelsHolder.addChild(c)}this.width=2*e+t*2,this.height=2*e+t*2,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Xo extends Oe{constructor(){super()}initializeWithShapePath(e,t=[]){const r=Jq(e),i=Zq(r);for(let s=0;s<r.length;s++){if(s>=t.length)continue;const a=t[s],o=String(a??"");if(o.length===0)continue;const l=r[s],u=l.x,c=l.y,h=r[(s+1)%r.length],f=h.x,d=h.y;let p=f-u,m=d-c;const y=Math.sqrt(p*p+m*m);p/=y,m/=y;const v=(u+f)/2,S=(c+d)/2;let g=-1*m,b=p;const w=v-i.x,x=S-i.y;w*g+x*b<0&&(g*=-1,b*=-1);const N=new Ut,D=u+g*10,C=c+b*10,A=f+g*10,E=d+b*10;N.setEndpoints(D,C,A,E),this.addChild(N);let F=Math.atan2(m,p)*180/Math.PI;(F>90||F<-90)&&(F+=180);const O=v+g*18,k=S+b*18,B=new si;B.setAlignment("center"),B.setFontFamily("Albert Sans"),B.setFontColor("black"),B.setFontSize(12),B.setPosition(O,k),B.setRotation(F),B.svgObject.setAttribute("dominant-baseline","middle"),this.addChild(B),B.setText(o)}}}class $s extends Oe{constructor(){super();const t=document.createElementNS("http://www.w3.org/2000/svg","svg");this.svgObject&&this.svgObject.parentNode&&this.svgObject.parentNode.replaceChild(t,this.svgObject),this.svgObject=t,this.svgObject.setAttribute("overflow","hidden"),this.graphEquations=[],this.lineSegments=[],this.dotValues=[],this.shapeSet=[],this.xMin=-5,this.xMax=5,this.yMin=-5,this.yMax=5,this.xLabel="",this.yLabel="",this.axisLabelOffsetPx=20,this.size="medium",this.tickInterval=1,this.forceAllTickLabels=!0,this.tickLabelOffsetPx=5,this.showTickLabels=!0,this.backgroundColor=Fe.lightGray,this.backgroundCornerRadius=15,this.backgroundOpacity=1,this.showBackground=!0,this.interactive=!1,this.variables=[],this.basePaddingBottom=30,this.interactivePaddingBottom=0,this.customPaddingTop=null,this.customPaddingRight=null,this.customPaddingBottom=null,this.customPaddingLeft=null,this.renderedFunctionEntries=[],this.sliderControlRows=[],this.calculatePadding(),this.updateLayout()}loadFromJSON(e){this.graphEquations=e.graphEquations||[],this.lineSegments=e.lineSegments||[],this.dotValues=e.dotValues||[],this.shapeSet=e.shapeSet||[],this.xMin=e.xMin!==void 0?e.xMin:this.xMin,this.xMax=e.xMax!==void 0?e.xMax:this.xMax,this.yMin=e.yMin!==void 0?e.yMin:this.yMin,this.yMax=e.yMax!==void 0?e.yMax:this.yMax,this.xLabel=e.xLabel!==void 0?e.xLabel:this.xLabel,this.yLabel=e.yLabel!==void 0?e.yLabel:this.yLabel,this.axisLabelOffsetPx=e.axisLabelOffsetPx!==void 0?e.axisLabelOffsetPx:this.axisLabelOffsetPx,this.size=e.size!==void 0?e.size:this.size,this.tickInterval=e.tickInterval!==void 0?e.tickInterval:this.tickInterval,this.tickLabelOffsetPx=e.tickLabelOffsetPx!==void 0?e.tickLabelOffsetPx:this.tickLabelOffsetPx,this.forceAllTickLabels=e.forceAllTickLabels!==void 0?e.forceAllTickLabels:this.forceAllTickLabels,this.showTickLabels=e.showTickLabels!==void 0?e.showTickLabels:this.showTickLabels,typeof e.graphPadding=="number"?(this.customPaddingTop=e.graphPadding,this.customPaddingRight=e.graphPadding,this.customPaddingBottom=e.graphPadding,this.customPaddingLeft=e.graphPadding):e.graphPadding&&typeof e.graphPadding=="object"&&(typeof e.graphPadding.top=="number"&&(this.customPaddingTop=e.graphPadding.top),typeof e.graphPadding.right=="number"&&(this.customPaddingRight=e.graphPadding.right),typeof e.graphPadding.bottom=="number"&&(this.customPaddingBottom=e.graphPadding.bottom),typeof e.graphPadding.left=="number"&&(this.customPaddingLeft=e.graphPadding.left)),typeof e.paddingTop=="number"&&(this.customPaddingTop=e.paddingTop),typeof e.paddingRight=="number"&&(this.customPaddingRight=e.paddingRight),typeof e.paddingBottom=="number"&&(this.customPaddingBottom=e.paddingBottom),typeof e.paddingLeft=="number"&&(this.customPaddingLeft=e.paddingLeft),this.backgroundColor=e.backgroundColor||this.backgroundColor,this.backgroundCornerRadius=e.backgroundCornerRadius!==void 0?e.backgroundCornerRadius:this.backgroundCornerRadius,this.backgroundOpacity=e.backgroundOpacity!==void 0?e.backgroundOpacity:this.backgroundOpacity,this.showBackground=e.showBackground!==void 0?e.showBackground:this.showBackground,this.interactive=e.interactive===!0||e.interactive==="true",this.variables=this.normalizeInteractiveVariables(e.variables||e.interactiveVariables||[]),this.calculatePadding(),this.updateLayout()}updateLayout(){this.removeAllChildren(),this.calculateGraphDimensions();const e=this.width,t=this.height,r=new Ho(e,t,15);this.addChild(r);const i=new yt;i.setWidthAndHeight(e,t),this.showBackground?(i.setFillColor(this.backgroundColor),this.backgroundOpacity<1&&i.setOpacity(this.backgroundOpacity)):i.setFillColor("transparent"),i.setStrokeWidth(0),i.setCornerRadius&&this.backgroundCornerRadius>0&&i.setCornerRadius(this.backgroundCornerRadius),r.addChild(i);const s=new Oe;s.setPosition(0,0),r.addChild(s),this.setWidthAndHeight(e,t),this.svgObject.setAttribute("viewBox",`0 0 ${e} ${t}`);const a=new Oe;s.addChild(a),this.makeGrid(a);const o=new Ho(this.graphWidth,this.graphHeight,0);o.setPosition(this.paddingLeft,this.paddingTop),s.addChild(o);const l=new Oe;o.addChild(l),this.graphMultipleFunctions(l);const u=new Oe;o.addChild(u),this.drawLineSegments(u);const c=new Oe;o.addChild(c),this.plotDots(c);const h=new Oe;o.addChild(h),this.addShapes(h),this.sliderControlRows=[],this.shouldShowInteractiveControls()&&this.createInteractiveControls(this.svgObject)}createAxisGrid(e,t){const r=this.tickInterval||1,i=t?this.xMin:this.yMin,s=t?this.xMax:this.yMax,a=Math.ceil(i),o=Math.floor(s);let l=r;if(!this.forceAllTickLabels){const c=t?this.xMax-this.xMin:this.yMax-this.yMin;let f=Math.floor(c/10)*10/6,d=Math.round(f/5)*5;d===0&&(d=1),l=d}let u=!1;for(let c=a;c<=o;c+=r){const h=this.computeAxisPos(t,c),f=new Ut;this.setAxisLineEndpoints(t,f,h),f.setStrokeColor("black"),f.setOpacity(c===0?1:.15),e.addChild(f),c===0&&(u=!0);let d=!1;this.showTickLabels&&(this.forceAllTickLabels?d=!0:d=((y,v)=>Math.abs(y/v-Math.round(y/v))<1e-9)(c,l)),d&&(this.addTickLabel(e,t,h,c),t?Math.max(20,Math.min(h,this.width-20)):Math.max(15,Math.min(h,this.height-7.5)))}if(0>=i&&0<=s&&!u){const c=this.computeAxisPos(t,0),h=new Ut;this.setAxisLineEndpoints(t,h,c),h.setStrokeColor("black"),h.setOpacity(1),e.addChild(h)}}createAxisLabels(e){if(this.xLabel){const t=Math.max(60,this.xLabel.length*10),r=20,i=new Bt;i.setWidthAndHeight(t,r),i.setText(this.xLabel),i.setFontSize(14),i.setFontColor("black"),i.setAlignment("center"),i.setVerticalCentering(),i.setFontWeight(600);const s=this.paddingLeft+this.graphWidth/2-t/2,a=Math.max(5,Math.min(s,this.width-t-5));i.setPosition(a,this.height-this.paddingBottom+this.axisLabelOffsetPx),e.addChild(i)}if(this.yLabel){const r=Math.max(15,this.paddingLeft-(this.axisLabelOffsetPx+10)),i=this.paddingTop+this.graphHeight/2,s=new Oe,a=new si;a.setText(this.yLabel),a.setFontSize(14),a.setFontColor("black"),a.setPosition(0,0),a.svgObject.setAttribute("text-anchor","middle"),a.svgObject.setAttribute("dominant-baseline","middle"),a.setFontWeight(600),s.addChild(a),s.svgObject.setAttribute("transform",`translate(${r}, ${i}) rotate(-90)`),e.addChild(s)}}makeGrid(e){this.createAxisGrid(e,!0),this.createAxisGrid(e,!1),this.createAxisLabels(e)}calculatePadding(){const e=this.yLabel?50:30,t=this.xLabel?50:30,r=25,i=25;this.paddingLeft=typeof this.customPaddingLeft=="number"?this.customPaddingLeft:e,this.basePaddingBottom=typeof this.customPaddingBottom=="number"?this.customPaddingBottom:t,this.interactivePaddingBottom=this.shouldShowInteractiveControls()?this.getInteractiveControlHeight():0,this.paddingBottom=this.basePaddingBottom+this.interactivePaddingBottom,this.paddingTop=typeof this.customPaddingTop=="number"?this.customPaddingTop:r,this.paddingRight=typeof this.customPaddingRight=="number"?this.customPaddingRight:i}computeAxisPos(e,t){return e?this.paddingLeft+(t-this.xMin)*this.xSpacer:this.height-this.paddingBottom-(t-this.yMin)*this.ySpacer}setAxisLineEndpoints(e,t,r){e?t.setEndpoints(r,this.paddingTop,r,this.height-this.paddingBottom):t.setEndpoints(this.paddingLeft,r,this.width-this.paddingRight,r)}addTickLabel(e,t,r,i){const s=this.createNumericLabel(i);if(t){const a=Math.max(10,Math.min(r-10,this.width-30));s.setPosition(a,this.height-this.paddingBottom+this.tickLabelOffsetPx)}else{const a=Math.max(5,this.paddingLeft-(this.tickLabelOffsetPx+20)),o=Math.max(7.5,Math.min(r-7.5,this.height-15));s.setPosition(a,o)}e.addChild(s)}toGraphPixelX(e){return(e-this.xMin)*this.xSpacer}toGraphPixelY(e){return this.graphHeight-(e-this.yMin)*this.ySpacer}createNumericLabel(e){const t=new Bt;return t.setWidthAndHeight(20,15),t.setText(String(e)),t.setFontSize(9),t.setFontColor(this.getAllowedColor("black")),t.setAlignment("center"),t.setVerticalCentering(),t}getAllowedColor(e){if(!e)return"black";const t=String(e).trim();return Fe[t.toLowerCase()]||t||"black"}assignFromData(e,t){for(const[r,i]of Object.entries(t))typeof e[r]===i&&(this[r]=e[r])}calculateGraphDimensions(){let e=200,t=8;this.size==="large"?(e=300,t=12):this.size==="small"&&(e=100,t=6),this.dotSize=t,this.xSpan=this.xMax-this.xMin,this.ySpan=this.yMax-this.yMin;const r=Math.min(e/this.xSpan,e/this.ySpan);this.graphWidth=r*this.xSpan,this.graphHeight=r*this.ySpan,this.width=this.graphWidth+this.paddingLeft+this.paddingRight,this.height=this.graphHeight+this.paddingTop+this.paddingBottom,this.xSpacer=r,this.ySpacer=r,this.originX=this.paddingLeft-this.xMin*this.xSpacer,this.originY=this.height-this.paddingBottom+this.yMin*this.ySpacer}graphMultipleFunctions(e){this.renderedFunctionEntries=[];for(const t of this.graphEquations)try{const r=this.compileFunctionExpression(t.equation),i=new Ni;i.setStrokeColor(this.getAllowedColor(t.color)),i.setStrokeWidth(t.strokeWidth),this.graphFunctionWithDomain(i,t.domain,r),e.addChild(i);const s={functionConfig:t,compiledExpression:r,path:i,label:null};t.label&&(s.label=this.addFunctionLabel(e,t,r)),this.renderedFunctionEntries.push(s)}catch(r){console.warn(`Failed to graph equation: ${t.equation}`,r)}}_extractExpression(e){let t=String(e).trim();return t=t.replace(/^\s*y\s*=\s*/i,"").replace(/\s*=\s*y\s*$/i,""),t}compileFunctionExpression(e){return math.compile(this._extractExpression(e))}graphFunctionWithDomain(e,t,r){e.clearPoints();const i=t&&typeof t.min=="number"?t.min:this.xMin,s=t&&typeof t.max=="number"?t.max:this.xMax,a=this.shouldShowInteractiveControls()?400:1e3,o=s-i;for(let l=0;l<=a;l++){const u=i+o*l/a,c=r.evaluate(this.getEvaluationScope({x:u}));Number.isFinite(c)&&e.addPoint(this.toGraphPixelX(u),this.toGraphPixelY(c))}e.updatePath()}addFunctionLabel(e,t,r){const i=String(t.label),s=12,a=6,o=Math.max(40,i.length*(s*.6)),l=s+a,u=new Bt;return u.setWidthAndHeight(o,l),u.setText(i),u.setFontSize(s),u.setFontColor(this.getAllowedColor(t.color||"black")),u.setAlignment("center"),u.setVerticalCentering(),u.setFontWeight(500),this.updateFunctionLabelPosition(u,t,r),e.addChild(u),u}updateFunctionLabelPosition(e,t,r){const i=typeof t.labelAtX=="number"?t.labelAtX:this.xMin+(this.xMax-this.xMin)*.1;let s=this.yMin+(this.yMax-this.yMin)*.1;s=r.evaluate(this.getEvaluationScope({x:i}));const o=this.toGraphPixelX(i),l=this.toGraphPixelY(s),u=(t.labelPosition||"below").toLowerCase(),c=10;let h=o,f=l;switch(u){case"above":f=l-c;break;case"below":f=l+c;break;case"left":h=o-c;break;case"right":h=o+c;break;default:f=l+c}e.setPosition(h,f)}drawLineSegments(e){for(const t of this.lineSegments){const r=this.toGraphPixelX(t.point1[0]),i=this.toGraphPixelY(t.point1[1]),s=this.toGraphPixelX(t.point2[0]),a=this.toGraphPixelY(t.point2[1]),o=new Ut;o.setEndpoints(r,i,s,a),o.setStrokeColor(this.getAllowedColor(t.color||"blue")),o.setStrokeWidth(t.strokeWidth||2),e.addChild(o)}}plotDots(e){for(const t of this.dotValues){const r=this.toGraphPixelX(t[0]),i=this.toGraphPixelY(t[1]),s=new Tr;s.setWidthAndHeight(this.dotSize,this.dotSize),s.setPosition(r,i),s.setFillColor(this.getAllowedColor(t.length>=3?t[2]:"black")),e.addChild(s)}}addShapes(e){e.setPosition(-this.xMin*this.xSpacer,this.graphHeight+this.yMin*this.ySpacer);const t={rightTriangle:ks,isoscelesTriangle:Ps,rectangle:zs,ellipse:Rs,circle:Ls,regularPolygon:Is};for(const r of this.shapeSet){const i=t[r.omdType];if(!i)continue;r.unitScale=this.xSpacer;const s=new i;s.loadFromJSON(r),s.shapePath&&s.shapePath.setFillColor("none"),e.addChild(s)}}shouldShowInteractiveControls(){return this.interactive===!0&&this.variables.length>0}getInteractiveControlHeight(){return 18+this.variables.length*38}normalizeInteractiveVariables(e){return Array.isArray(e)?e.map((t,r)=>this.normalizeInteractiveVariable(t,r)).filter(Boolean):[]}normalizeInteractiveVariable(e,t){const r=typeof e=="string"?{name:e}:e&&typeof e=="object"?e:null;if(!r)return null;const i=String(r.name??r.variable??r.id??"").trim();if(!i)return null;let s=Number.isFinite(r.min)?r.min:-10,a=Number.isFinite(r.max)?r.max:10;if(a<s){const c=s;s=a,a=c}a===s&&(a=s+1);const o=Number.isFinite(r.step)&&r.step>0?r.step:.1,l=s<=0&&a>=0?0:s,u=this.clampInteractiveValue(Number.isFinite(r.value)?r.value:l,s,a);return{name:i,label:String(r.label??i),min:s,max:a,step:o,value:u,color:r.color??null,graphIndex:Number.isInteger(r.graphIndex)?r.graphIndex:Number.isInteger(r.equationIndex)?r.equationIndex:null,order:t}}clampInteractiveValue(e,t,r){return Math.max(t,Math.min(r,e))}snapInteractiveValue(e,t){const r=t.step||.1,i=t.min+Math.round((e-t.min)/r)*r,s=this.getStepPrecision(r),a=Number(i.toFixed(s));return this.clampInteractiveValue(a,t.min,t.max)}getStepPrecision(e){const t=String(e);return t.includes(".")?t.split(".")[1].length:0}getInteractiveVariableValue(e){return e?Number.isFinite(e.currentValue)?e.currentValue:Number.isFinite(e.value)?e.value:0:0}getEvaluationScope(e={}){const t={...e};for(const r of this.variables)t[r.name]=this.getInteractiveVariableValue(r);return t}createInteractiveControls(e){const t=this.createSvgElement("g",{"data-omd-interactive-controls":"true"}),i=this.paddingTop+this.graphHeight+this.basePaddingBottom+8,s=this.paddingLeft,a=this.width-this.paddingRight,o=this.paddingLeft+36,l=this.width-this.paddingRight-56,u=Math.max(40,l-o);this.sliderControlRows=this.variables.map((c,h)=>{const f=this.resolveInteractiveVariableColor(c),d=i+h*38,p=this.createSvgElement("g",{transform:`translate(0, ${d})`,"data-omd-variable":c.name}),m=this.createSvgElement("text",{x:s,y:4,fill:f,"font-size":13,"font-weight":700,"dominant-baseline":"middle"});m.textContent=c.label;const y=this.createSvgElement("line",{x1:o,y1:0,x2:o+u,y2:0,stroke:"#d1d5db","stroke-width":6,"stroke-linecap":"round"}),v=this.createSvgElement("line",{x1:o,y1:0,x2:o,y2:0,stroke:f,"stroke-width":6,"stroke-linecap":"round"}),S=this.createSvgElement("circle",{cx:o,cy:0,r:8,fill:f,stroke:"#ffffff","stroke-width":2}),g=this.createSvgElement("text",{x:a,y:4,fill:f,"font-size":12,"font-weight":600,"dominant-baseline":"middle","text-anchor":"end"}),b=this.createSvgElement("rect",{x:o-10,y:-14,width:u+20,height:28,fill:"transparent","pointer-events":"all",rx:14});b.style.cursor="pointer",p.appendChild(m),p.appendChild(y),p.appendChild(v),p.appendChild(S),p.appendChild(g),p.appendChild(b),t.appendChild(p);const w={variable:c,color:f,label:m,track:y,activeTrack:v,thumb:S,valueText:g,hitArea:b,trackStart:o,trackEnd:o+u};return this.attachSliderInteraction(w),this.updateSliderRow(w),w}),e.appendChild(t)}attachSliderInteraction(e){const t=r=>{const s=(this.clientToLocalSvgX(r.clientX)-e.trackStart)/(e.trackEnd-e.trackStart),a=e.variable.min+s*(e.variable.max-e.variable.min),o=this.snapInteractiveValue(a,e.variable);e.variable.currentValue=o,e.variable.value=o,this.refreshInteractiveElements()};e.hitArea.addEventListener("pointerdown",r=>{var a,o;r.preventDefault(),r.stopPropagation(),t(r),(o=(a=e.hitArea).setPointerCapture)==null||o.call(a,r.pointerId);const i=l=>{l.preventDefault(),l.stopPropagation(),t(l)},s=l=>{var u,c,h,f;(u=l==null?void 0:l.preventDefault)==null||u.call(l),(c=l==null?void 0:l.stopPropagation)==null||c.call(l),e.hitArea.removeEventListener("pointermove",i),e.hitArea.removeEventListener("pointerup",s),e.hitArea.removeEventListener("pointercancel",s);try{(f=(h=e.hitArea).releasePointerCapture)==null||f.call(h,r.pointerId)}catch{}};e.hitArea.addEventListener("pointermove",i),e.hitArea.addEventListener("pointerup",s),e.hitArea.addEventListener("pointercancel",s)})}refreshInteractiveElements(){var e;for(const t of this.renderedFunctionEntries)try{this.graphFunctionWithDomain(t.path,t.functionConfig.domain,t.compiledExpression),t.label&&this.updateFunctionLabelPosition(t.label,t.functionConfig,t.compiledExpression)}catch(r){console.warn(`Failed to refresh equation: ${(e=t.functionConfig)==null?void 0:e.equation}`,r)}for(const t of this.sliderControlRows)this.updateSliderRow(t)}updateSliderRow(e){const t=this.getInteractiveVariableValue(e.variable),r=(t-e.variable.min)/(e.variable.max-e.variable.min),i=Math.max(0,Math.min(1,r)),s=e.trackStart+(e.trackEnd-e.trackStart)*i;e.activeTrack.setAttribute("x2",String(s)),e.thumb.setAttribute("cx",String(s)),e.valueText.textContent=this.formatInteractiveValue(t,e.variable.step)}formatInteractiveValue(e,t){const r=Math.min(4,Math.max(0,this.getStepPrecision(t)));return`${Number(e.toFixed(r))}`}resolveInteractiveVariableColor(e){var i;if(e.color)return this.getAllowedColor(e.color);const t=e.graphIndex;if(Number.isInteger(t)&&((i=this.graphEquations[t])!=null&&i.color))return this.getAllowedColor(this.graphEquations[t].color);const r=this.graphEquations.find(s=>this.equationContainsVariable(s==null?void 0:s.equation,e.name));return r!=null&&r.color?this.getAllowedColor(r.color):this.getAllowedColor("#2563eb")}equationContainsVariable(e,t){if(!e||!t)return!1;const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_])${r}([^A-Za-z0-9_]|$)`).test(String(e))}createSvgElement(e,t={}){const r=document.createElementNS("http://www.w3.org/2000/svg",e);for(const[i,s]of Object.entries(t))s!=null&&r.setAttribute(i,String(s));return r}clientToLocalSvgX(e){const t=this.svgObject.getBoundingClientRect(),r=(this.svgObject.getAttribute("viewBox")||"0 0 0 0").split(/\s+/).map(Number),[i=0,,s=0]=r;return!t.width||!s?0:i+(e-t.left)/t.width*s}setBackgroundColor(e){this.backgroundColor=e,this.updateLayout()}setBackgroundCornerRadius(e){this.backgroundCornerRadius=e,this.updateLayout()}setBackgroundOpacity(e){this.backgroundOpacity=Math.max(0,Math.min(1,e)),this.updateLayout()}setShowBackground(e){this.showBackground=e,this.updateLayout()}setBackgroundStyle(e={}){e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.cornerRadius!==void 0&&(this.backgroundCornerRadius=e.cornerRadius),e.opacity!==void 0&&(this.backgroundOpacity=Math.max(0,Math.min(1,e.opacity))),e.show!==void 0&&(this.showBackground=e.show),this.updateLayout()}}class Qq extends Oe{constructor(){super(),this.startValue=1,this.endValue=3,this.startIndex=0,this.endIndex=1,this.label="label",this.showBelow=!1,this.unitWidth=30,this.indexPositions=[],this.startPos=0,this.endPos=0,this.updateLayout()}setIndexPositions(e){this.indexPositions=e}loadFromJSON(e){if(!e||typeof e!="object")return;const{startIndex:t,endIndex:r,label:i,showBelow:s}=e;t!==void 0&&(this.startIndex=t,t>=0&&t<=this.indexPositions.length&&(this.startPos=this.indexPositions[t])),r!==void 0&&(this.endIndex=r,r>=0&&r<=this.indexPositions.length&&(this.endPos=this.indexPositions[r])),i!==void 0&&(this.label=i),s!==void 0&&(this.showBelow=s),this.updateLayout()}updateLayout(){this.removeAllChildren();var e=this.startPos,t=this.endPos,r=t-e;this.line=new Ut,this.line.setEndpoints(e,0,t,0),this.addChild(this.line);var i=new Ut;i.setEndpoints(e,-3,e,3),this.addChild(i),i=new Ut,i.setEndpoints(t,-3,t,3),this.addChild(i);var s=new Bt;s.setWidthAndHeight(r,30),s.setText(this.name),s.setFontFamily("Albert Sans"),s.setFontColor("black"),s.setFontSize(14),s.setAlignment("center"),s.setText(this.label),this.showBelow?s.setPosition(e,5):s.setPosition(e,-20),this.addChild(s);var a=Math.max(r,t),o=this.showBelow?35:30;this.setWidthAndHeight(a,o),this.svgObject.setAttribute("viewBox",`0 ${this.showBelow?-5:-25} ${a} ${o}`)}}class mn extends Oe{constructor(){super(),this.type="omdTapeDiagram",this.title="",this.values=[],this.labelSet=[],this.totalWidth=300,this.updateLayout()}loadFromJSON(e){typeof e.title<"u"&&(this.title=e.title),typeof e.values<"u"&&(this.values=e.values),typeof e.labelSet<"u"&&(this.labelSet=e.labelSet),typeof e.totalWidth<"u"&&(this.totalWidth=e.totalWidth),this.updateLayout()}setValues(e){this.values=e,this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.title?80:20,t=20,r=70;if(this.title){const g=new Bt;g.setWidthAndHeight(r,30),g.setFontFamily("Albert Sans"),g.setFontColor("black"),g.setFontSize(12),g.setAlignment("left"),g.setText(this.title),g.setPosition(5,5),this.addChild(g)}const i=[];let s=0;for(const g of this.values){let b="",w=!0,x=Fe.lightGray,N=1;typeof g=="object"&&g!==null?(b=g.value||"",w=g.showLabel!==void 0?g.showLabel:!0,x=g.color||Fe.lightGray):b=g.toString();const D=b.match(/^([0-9.]+)?([a-zA-Z]*)$/);if(D){const C=D[1]?parseFloat(D[1]):(D[2],1);D[2],N=C}i.push({value:b,showLabel:w,color:x,numericValue:N}),s+=N}var a=e,o=[];for(const g of i){o.push(a);const b=s>0?g.numericValue/s:1/i.length,w=this.totalWidth*b;var l=new yt;if(l.setWidthAndHeight(w,30),l.setCornerRadius(5),l.setStrokeColor("white"),l.setStrokeWidth(1),l.setFillColor(g.color),l.setPosition(a,0),this.addChild(l),g.showLabel){var u=new Bt;u.setWidthAndHeight(w,30),u.setFontFamily("Albert Sans"),u.setFontColor("black"),u.setFontSize(18),u.setAlignment("center"),u.setVerticalCentering(),u.setText(g.value),u.setPosition(a,0),this.addChild(u)}a+=w}o.push(a);var c=a-e,h=30,f=0,d=0;const p=this.labelSet.slice().map((g,b)=>({data:g,span:(g.endIndex||0)-(g.startIndex||0)})).sort((g,b)=>g.span-b.span),m=[],y=[];for(const g of p){const b=g.data,w=new Qq;if(w.setIndexPositions(o),w.loadFromJSON(b),w.showBelow){let x=0;const N=b.startIndex||0,D=b.endIndex||0;for(;x<y.length&&y[x].some(E=>!(D<=E.start||N>=E.end));)x++;x===y.length&&y.push([]),y[x].push({start:N,end:D});const C=40+x*35;w.setPosition(0,C),d=Math.max(d,C+30)}else{let x=0;const N=b.startIndex||0,D=b.endIndex||0;for(;x<m.length&&m[x].some(E=>!(D<=E.start||N>=E.end));)x++;x===m.length&&m.push([]),m[x].push({start:N,end:D});const C=-10-x*35;w.setPosition(0,C),f=Math.max(f,(x+1)*35)}this.addChild(w)}this.width=e+c+t,this.height=f+h+d;const v=-f,S=this.height;this.svgObject.setAttribute("viewBox",`0 ${v} ${this.width} ${S}`),this.svgObject.setAttribute("viewBox",`0 ${-f} ${this.width} ${this.height}`)}}class iy extends Oe{constructor(){super(),this.type="omdDoubleTapeDiagram",this.topTapeDiagram=new mn,this.bottomTapeDiagram=new mn,this.spacing=30,this.updateLayout()}loadFromJSON(e){typeof e.spacing<"u"&&(this.spacing=e.spacing),typeof e.topTapeDiagram<"u"&&this.topTapeDiagram.loadFromJSON(e.topTapeDiagram),typeof e.bottomTapeDiagram<"u"&&this.bottomTapeDiagram.loadFromJSON(e.bottomTapeDiagram),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.calculateTotalValue(this.topTapeDiagram),t=this.calculateTotalValue(this.bottomTapeDiagram),r=Math.max(e,t),i=300,s=r>0?i/r:i;this.topTapeDiagram.totalWidth=e*s,this.bottomTapeDiagram.totalWidth=t*s,this.topTapeDiagram.updateLayout(),this.bottomTapeDiagram.updateLayout();const a=this.topTapeDiagram.title?80:20,o=this.bottomTapeDiagram.title?80:20,l=Math.max(a,o),u=l-a;this.topTapeDiagram.setPosition(u,0),this.addChild(this.topTapeDiagram);const c=l-o,h=this.topTapeDiagram.height+this.spacing;this.bottomTapeDiagram.setPosition(c,h),this.addChild(this.bottomTapeDiagram);const f=Math.max(this.topTapeDiagram.width+u,this.bottomTapeDiagram.width+c);this.width=f,this.height=this.topTapeDiagram.height+this.spacing+this.bottomTapeDiagram.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}calculateTotalValue(e){let t=0;for(const r of e.values){let i="";typeof r=="object"&&r!==null?i=r.value||"":i=r.toString();const s=i.match(/^([0-9.]+)?([a-zA-Z]*)$/);if(s){const a=s[1]?parseFloat(s[1]):(s[2],1);t+=a}else t+=1}return t}}class $i extends Oe{constructor(){super(),this.type="omdNumberLine",this.value=1,this.size="large",this.dotsPerColumn=10,this.backgroundColor=Fe.lightGray,this.dotColor="black",this.updateLayout()}loadFromJSON(e){typeof e.value<"u"&&(this.value=e.value),typeof e.size<"u"&&(this.size=e.size),typeof e.dotsPerColumn<"u"&&(this.dotsPerColumn=Math.max(1,Number(e.dotsPerColumn))),typeof e.backgroundColor<"u"&&(this.backgroundColor=e.backgroundColor),typeof e.dotColor<"u"&&(this.dotColor=e.dotColor),this.updateLayout()}setValue(e){this.value=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}updateLayout(){this.removeAllChildren();const e=Math.max(0,Number(this.value)||0),t=Math.max(1,Number(this.dotsPerColumn)||1);let r;this.size==="large"?r=15:this.size==="medium"?r=12:r=5;const i=Math.max(2,Math.round(r*.6)),s=Math.max(3,Math.round(r*.8)),a=Math.ceil(e/t),o=Math.min(t,e);this._dotSize=r,this._pad=s;const l=a>0?a*r+(a-1)*i:0,u=o>0?o*r+(o-1)*i:0,c=l+2*s,h=u+2*s,f=new yt;f.setWidthAndHeight(c,h);const d=a>1?Math.round(r):Math.min(c,h)/2;f.setCornerRadius(d),f.setFillColor(this.backgroundColor||Fe.lightGray),this.addChild(f),this.width=f.width,this.height=f.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);for(let p=0;p<e;p++){const m=Math.floor(p/t),y=p%t,v=s+m*(r+i)+r/2,S=s+y*(r+i)+r/2,g=new Tr;g.setFillColor(this.dotColor||"black"),g.setWidthAndHeight(r,r),g.setPosition(v,S),this.addChild(g)}}getTopDotCenterY(){const e=this._pad??0,t=this._dotSize??0;return e+t/2}}class ny extends Oe{constructor(){super(),this.type="omdTileEquation",this.left=[],this.right=[],this.equation=null,this.tileSize=28,this.tileGap=6,this.rowGap=10,this.equalGap=24,this.tileRadius=6,this.showLabels=!0,this.fontFamily="Albert Sans",this.fontSize=16,this.plusColor="#79BBFD",this.equalsColor="#FF6B6B",this.xPillColor=Fe.lightGray,this.numberTileDefaults={backgroundColor:Fe.lightGray,dotColor:"black"},this.updateLayout()}loadFromJSON(e){!e||typeof e!="object"||(Array.isArray(e.left)&&(this.left=e.left),Array.isArray(e.right)&&(this.right=e.right),typeof e.equation=="string"?this.equation=this._parseEquationString(e.equation):e.equation&&typeof e.equation=="object"?this.equation=e.equation:typeof e.equationString=="string"&&(this.equation=this._parseEquationString(e.equationString)),typeof e.tileSize=="number"&&(this.tileSize=e.tileSize),typeof e.tileGap=="number"&&(this.tileGap=e.tileGap),typeof e.equalGap=="number"&&(this.equalGap=e.equalGap),typeof e.tileRadius=="number"&&(this.tileRadius=e.tileRadius),typeof e.showLabels=="boolean"&&(this.showLabels=e.showLabels),typeof e.fontFamily=="string"&&(this.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(this.fontSize=e.fontSize),typeof e.plusColor=="string"&&(this.plusColor=e.plusColor),typeof e.equalsColor=="string"&&(this.equalsColor=e.equalsColor),e.xPill&&typeof e.xPill.color=="string"&&(this.xPillColor=e.xPill.color),typeof e.xPillColor=="string"&&(this.xPillColor=e.xPillColor),e.numberTileDefaults&&typeof e.numberTileDefaults=="object"&&(this.numberTileDefaults={backgroundColor:e.numberTileDefaults.backgroundColor??this.numberTileDefaults.backgroundColor,dotColor:e.numberTileDefaults.dotColor??this.numberTileDefaults.dotColor}),this.updateLayout())}_parseEquationString(e){try{const r=String(e||"").replace(/\s+/g,"").split("=");if(r.length!==2)return null;const i=r[0],s=r[1],a=c=>{const h=String(c||"").replace(/[\s−–]/g,y=>y===" "?"":"-"),f=/([+-]?\d*[a-zA-Z])|([+-]?\d+)/g;let d=null;const p=[];return(h.match(f)||[]).forEach(y=>{if(/[a-zA-Z]/.test(y)){const v=y.match(/^([+-]?)(\d*)([a-zA-Z])$/),S=(v[1]||"+")==="-"?"-":"+",g=v[2]?parseInt(v[2],10):1;d=d||v[3],p.push({kind:"x",count:Math.max(1,g),sign:S})}else{const v=y[0]==="-"?"-":"+",S=Math.abs(parseInt(y,10));p.push({kind:"const",value:Math.max(0,S),sign:v})}}),{varLabel:d,tokens:p}},o=a(i),l=a(s),u=o.varLabel||l.varLabel||"X";return{leftTokens:o.tokens,rightTokens:l.tokens,xLabel:u}}catch{return null}}updateLayout(){if(this.removeAllChildren(),this.equation){const o=this._renderEquation(this.equation);this.setWidthAndHeight(o.width,o.height),this.svgObject.setAttribute("viewBox",`0 0 ${o.width} ${o.height}`);return}const e=new Oe,t=new Oe;this.addChild(e),this.addChild(t);const r=this._renderSide(e,this.left),i=this._renderSide(t,this.right);t.setPosition(r.width+this.equalGap,0);const s=r.width+this.equalGap+i.width,a=Math.max(r.height,i.height);this.setWidthAndHeight(s,a),this.svgObject.setAttribute("viewBox",`0 0 ${s} ${a}`)}_renderSide(e,t){let r=0,i=0,s=0;return t.forEach(a=>{const o=(a==null?void 0:a.kind)||"var",l=(a==null?void 0:a.color)||(o==="var"?"#79BBFD":"#FFA26D"),u=Math.max(1,Number((a==null?void 0:a.count)||1));if(o==="text"){const p=new Bt;p.setWidthAndHeight(this.fontSize*(String(a.value).length*.7)+8*2,this.fontSize+6*2),p.setFontFamily(this.fontFamily),p.setFontSize(this.fontSize),p.setFontColor("black"),p.setAlignment("center"),p.setVerticalCentering(),p.setText(String(a.value));const v=new yt;v.setWidthAndHeight(p.width,p.height),v.setCornerRadius(Math.min(this.tileRadius,p.height/2)),v.setFillColor(Fe.lightGray);const S=new Oe;S.setPosition(r,i),S.addChild(v),S.addChild(p),e.addChild(S),r+=p.width+this.tileGap,s=Math.max(s,p.height);return}const c=new Oe;c.setPosition(r,i),e.addChild(c);const h=!!a.stack;let f=0,d=0;for(let p=0;p<u;p++){const m=new yt;m.setWidthAndHeight(this.tileSize,this.tileSize),m.setCornerRadius(Math.min(this.tileRadius,this.tileSize/2)),m.setFillColor(l);const y=h?0:p*(this.tileSize+this.tileGap),v=h?p*(this.tileSize+this.rowGap):0;m.setPosition(y,v),c.addChild(m),f=Math.max(f,y+this.tileSize),d=Math.max(d,v+this.tileSize)}r+=f+this.tileGap,s=Math.max(s,d)}),{width:r>0?r-this.tileGap:0,height:s}}_renderEquation(e){const t=Array.isArray(e.leftTokens)&&Array.isArray(e.rightTokens),r=t?e.leftTokens:[],i=t?e.rightTokens:[],s=Math.max(0,Number(e.leftX??e.x??0)),a=Array.isArray(e.leftUnitList)?e.leftUnitList:Number.isFinite(e.leftUnits??e.units)?[Math.max(0,Number(e.leftUnits??e.units))]:[],o=Math.max(0,Number(e.rightX??0)),l=Array.isArray(e.rightUnitList)?e.rightUnitList:Number.isFinite(e.rightUnits??e.total)?[Math.max(0,Number(e.rightUnits??e.total))]:[],u=String(e.xLabel||"X"),c=this.xPillColor||Fe.lightGray,f=.62*this.tileSize,d=Math.max(this.tileSize*1.6,Math.round(5*f)),p=this.tileSize,m=t?r.filter(L=>L.kind==="x").reduce((L,Y)=>L+Y.count,0):s,y=t?i.filter(L=>L.kind==="x").reduce((L,Y)=>L+Y.count,0):o,v=m>0?m*(p+this.rowGap)-this.rowGap:0,S=t?r.filter(L=>L.kind==="const").map(L=>{const Y=new $i;return Y.loadFromJSON({value:L.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}):a.map(L=>{const Y=new $i;return Y.loadFromJSON({value:L,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}),g=t?i.filter(L=>L.kind==="const").map(L=>{const Y=new $i;return Y.loadFromJSON({value:L.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}):l.map(L=>{const Y=new $i;return Y.loadFromJSON({value:L,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),Y}),b=m>0?p/2:0,w=S.length?Math.min(...S.map(L=>L.getTopDotCenterY())):0,x=g.length?Math.min(...g.map(L=>L.getTopDotCenterY())):0,N=Math.max(b,w,x,this.tileSize*.6),D=m>0?N-b:0,C=S.length?N-w:0,A=g.length?N-x:0,E=[];m>0&&E.push(D+v),S.forEach(L=>E.push(C+L.height)),g.forEach(L=>E.push(A+L.height));const F=E.length?Math.max(...E):this.tileSize*2;let O=0;const k=(L,Y)=>{const ee=new si;ee.setText(L),ee.setFontSize(this.tileSize),ee.setFontColor(this.plusColor),ee.setAlignment("center"),ee.svgObject.setAttribute("dominant-baseline","middle"),ee.setPosition(Y+this.equalGap/2,N),this.addChild(ee)},B=()=>{const L=new Oe;for(let Y=0;Y<m;Y++){const ee=Y*(p+this.rowGap),_=new yt;_.setWidthAndHeight(d,p),_.setCornerRadius(p/2),_.setFillColor(c),_.setPosition(0,ee),L.addChild(_);const V=new si;V.setText(u),V.setFontWeight("bold"),V.setFontSize(this.tileSize*.7),V.setFontFamily(this.fontFamily),V.setFontColor("black"),V.setAlignment("center"),V.svgObject.setAttribute("dominant-baseline","middle");const z=p*.06;V.setPosition(d/2,ee+p/2+z),L.addChild(V)}return L},T=(L,Y,ee,_,V)=>{let z=Y,de=!1;return(t?L.slice():[..._>0?[{kind:"x",count:_,sign:"+"}]:[],...(V?a:l).map(oe=>({kind:"const",value:oe,sign:"+"}))]).forEach(oe=>{const $=oe.sign==="-"?"-":"+";if((de||$==="-")&&(k($==="-"?"−":"+",z),z+=this.equalGap),oe.kind==="x"){const H=B();H.setPosition(z,N-b),this.addChild(H),z+=d,de=!0}else{const H=new $i;H.loadFromJSON({value:oe.value,size:"medium",backgroundColor:this.numberTileDefaults.backgroundColor,dotColor:this.numberTileDefaults.dotColor}),H.setPosition(z,ee),this.addChild(H),z+=H.width,de=!0}}),z};(t?r.length>0:m>0||S.length)&&(new Oe().setPosition(0,0),O=T(r,O,C,m,!0)),O+=this.equalGap,this.tileSize*1.2;const I=new si;I.setText("="),I.setFontSize(this.tileSize*1.1),I.setFontColor(this.equalsColor),I.setAlignment("center"),I.svgObject.setAttribute("dominant-baseline","middle");const U=O-this.equalGap/2;return I.setPosition(U,N),this.addChild(I),O=T(i,O,A,y,!1),{width:O,height:F}}}class Zn extends Oe{constructor(){super(),this.type="omdNumberLine",this.valueA=1,this.valueB=2,this.size="large",this.renderType="pie",this.updateLayout()}loadFromJSON(e){typeof e.valueA<"u"&&(this.valueA=e.valueA),typeof e.numerator<"u"&&(this.valueA=e.numerator),typeof e.valueB<"u"&&(this.valueB=e.valueB),typeof e.denominator<"u"&&(this.valueA=e.numerator,this.valueB=e.denominator-e.numerator),typeof e.renderType<"u"&&(this.renderType=e.renderType),typeof e.size<"u"&&(this.size=e.size),this.updateLayout()}setValues(e,t){this.valueA=e,this.valueB=t,this.updateLayout()}setRenderType(e){this.renderType=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}updateLayout(){this.removeAllChildren(),this.renderType=="pie"&&this.renderAsPie(),(this.renderType=="dots"||this.renderType=="dot"||this.renderType=="tile")&&this.renderAsDots(),this.renderType=="bar"&&this.renderAsBar()}renderAsPie(){var e=120;this.size=="large"&&(e=120),this.size=="medium"&&(e=80),this.size=="small"&&(e=40),this.width=e,this.height=e,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);var t=new Oe;t.setPosition(e/2,e/2),this.addChild(t);var r=new Tr;r.setFillColor(Fe.mediumGray),r.setWidthAndHeight(e,e),t.addChild(r);var i=this.valueA/(this.valueA+this.valueB),s=0,a=360*i,o=new lE;o.createPieSlice(e/2,s,a),o.setFillColor("black"),t.addChild(o);for(var l=this.valueA+this.valueB,u=Math.PI*2/l,c=0;c<l;c++){var h=c*u-Math.PI/2,f=Math.cos(h)*e/2,d=Math.sin(h)*e/2,p=new Ut;p.setStrokeColor("white"),p.setEndpoints(0,0,f,d),t.addChild(p)}}renderAsDots(){if(this.size=="large")var e=120,t=150,r=15,i=e/4;if(this.size=="medium")var e=80,t=100,r=12,i=e/4;if(this.size=="small")var e=40,t=50,r=5,i=e/4;var s=new yt;s.setWidthAndHeight(e*2,t),s.setCornerRadius(r),s.setFillColor(Fe.lightGray),this.addChild(s),this.width=s.width,this.height=s.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);for(var l=i,u=i,a=0;a<this.valueA;a++){var o=new Tr;o.setFillColor("black"),o.setWidthAndHeight(r,r),o.setPosition(l,u),this.addChild(o),l+=i,a!=0&&a%3==2&&(l=i,u+=i)}for(var l=i*5,u=i,a=0;a<this.valueB;a++){var o=new Tr;o.setFillColor("black"),o.setWidthAndHeight(r,r),o.setPosition(l,u),this.addChild(o),l+=i,a!=0&&a%3==2&&(l=i*5,u+=i)}var c=new Ut;c.setEndpoints(i*4,i/2,i*4,t-i/2),this.addChild(c)}renderAsBar(){if(this.size=="large")var e=240;if(this.size=="medium")var e=120;if(this.size=="small")var e=80;var t=this.valueA/(this.valueA+this.valueB);this.width=e,this.height=30,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);var r=new yt;r.setWidthAndHeight(e,30),r.setFillColor(Fe.mediumGray),this.addChild(r);var i=new yt;i.setWidthAndHeight(t*e,30),i.setFillColor("black"),this.addChild(i);for(var s=this.valueA+this.valueB,a=e/s,o=1;o<s;o++){var l=o*a,u=new Ut;u.setStrokeColor("white"),u.setEndpoints(l,0,l,30),this.addChild(u)}}}class Qn extends Oe{constructor(){super(),this.type="omdNumberLine",this.title="",this.min=0,this.max=10,this.increment=1,this.showLeftArrow=!1,this.showRightArrow=!1,this.units="",this.hideDefaultNumbers=!1,this.specialNumbers=[],this.totalWidth=320,this.dotValues=[],this.label="",this.updateLayout()}loadFromJSON(e){typeof e.title<"u"&&(this.title=e.title),typeof e.min<"u"&&(this.min=e.min),typeof e.max<"u"&&(this.max=e.max),typeof e.increment<"u"&&(this.increment=e.increment),typeof e.showLeftArrow<"u"&&(this.showLeftArrow=e.showLeftArrow),typeof e.showRightArrow<"u"&&(this.showRightArrow=e.showRightArrow),typeof e.units<"u"&&(this.units=e.units),typeof e.hideDefaultNumbers<"u"&&(this.hideDefaultNumbers=e.hideDefaultNumbers),typeof e.specialNumbers<"u"&&(this.specialNumbers=e.specialNumbers),typeof e.totalWidth<"u"&&(this.totalWidth=e.totalWidth),typeof e.dotValues<"u"&&(this.dotValues=e.dotValues),typeof e.label<"u"&&(this.label=e.label),this.updateLayout()}setMinAndMax(e,t){this.min=e,this.max=t,this.updateLayout()}addNumberDot(e){this.dotValues.push(e),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.title?80:20,t=20,r=10,i=8,s=this.totalWidth,a=s-(this.showLeftArrow?r:0)-(this.showRightArrow?r:0);if(this.width=e+s+t,this.height=70,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.title){const d=new Bt;d.setWidthAndHeight(70,30),d.setFontFamily("Albert Sans"),d.setFontColor("black"),d.setFontSize(12),d.setAlignment("left"),d.setText(this.title),d.setPosition(5,20),this.addChild(d)}const o=e+(this.showLeftArrow?r:0),l=a;if(this.line=new yt,this.line.setWidthAndHeight(l,5),this.line.setPosition(o,22.5),this.line.setFillColor(Fe.mediumGray),this.line.setCornerRadius(2.5),this.addChild(this.line),this.showLeftArrow){const d=new yt;d.setWidthAndHeight(3,5),d.setPosition(o,22.5),d.setFillColor(Fe.mediumGray),this.addChild(d);const p=new Ni,m=25,y=e;p.addPoint(y+r,m-5),p.addPoint(y,m),p.addPoint(y+r,m+5),p.addPoint(y+r,m-5),p.updatePath(),p.setFillColor(Fe.mediumGray),p.setStrokeWidth(0),p.path.setAttribute("fill",Fe.mediumGray),this.addChild(p)}if(this.showRightArrow){const d=new yt;d.setWidthAndHeight(3,5),d.setPosition(o+l-3,22.5),d.setFillColor(Fe.mediumGray),this.addChild(d);const p=new Ni,m=25,y=e+s-r;p.addPoint(y,m-5),p.addPoint(y+r,m),p.addPoint(y,m+5),p.addPoint(y,m-5),p.updatePath(),p.setFillColor(Fe.mediumGray),p.setStrokeWidth(0),p.path.setAttribute("fill",Fe.mediumGray),this.addChild(p)}const u=new Set;if(!this.hideDefaultNumbers)for(let d=this.min;d<=this.max;d+=this.increment)u.add(d);for(const d of this.specialNumbers)d>=this.min&&d<=this.max&&u.add(d);const c=Array.from(u).sort((d,p)=>d-p),h=o+i,f=a-2*i;for(const d of c){const p=(d-this.min)/(this.max-this.min),m=h+p*f,y=new Ut;y.setStrokeColor("black"),y.setStrokeWidth(1),y.setEndpoints(m,20,m,30),this.addChild(y);const v=new Bt;v.setWidthAndHeight(40,30),v.setFontFamily("Albert Sans"),v.setFontColor("black"),v.setFontSize(10),v.setAlignment("center");const S=this.units?`${d}${this.units}`:d.toString();v.setText(S),v.setPosition(m-20,32),this.addChild(v)}for(const d of this.dotValues){if(d<this.min||d>this.max)continue;const p=(d-this.min)/(this.max-this.min),m=h+p*f,y=new Tr;y.setFillColor("black"),y.setStrokeWidth(0),y.setWidthAndHeight(8,8),y.setPosition(m,25),this.addChild(y)}}}class sy extends Oe{constructor(){super(),this.type="omdDoubleNumberLine",this.topNumberLine=new Qn,this.bottomNumberLine=new Qn,this.spacing=30,this.updateLayout()}loadFromJSON(e){typeof e.spacing<"u"&&(this.spacing=e.spacing),typeof e.topNumberLine<"u"&&this.topNumberLine.loadFromJSON(e.topNumberLine),typeof e.bottomNumberLine<"u"&&this.bottomNumberLine.loadFromJSON(e.bottomNumberLine),this.updateLayout()}updateLayout(){this.removeAllChildren();const e=this.topNumberLine.title?80:20,t=this.bottomNumberLine.title?80:20,r=Math.max(e,t),i=r-e;this.topNumberLine.setPosition(i,0),this.addChild(this.topNumberLine);const s=r-t;this.bottomNumberLine.setPosition(s,this.spacing),this.addChild(this.bottomNumberLine);const a=Math.max(this.topNumberLine.width+i,this.bottomNumberLine.width+s);this.width=a,this.height=70+this.spacing,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class Kn extends kt{constructor(e="+"){super(),this.type="omdOperator",this.operator=e,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.operator),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setOperator(e)}loadFromJSON(e){typeof e.operator<"u"&&this.setOperator(e.operator)}setOperator(e){e=="+"&&(this.operator="+"),e=="-"&&(this.operator="−"),e=="/"&&(this.operator="÷"),e=="÷"&&(this.operator="÷"),e=="x"&&(this.operator="×"),e=="*"&&(this.operator="×"),e=="•"&&(this.operator="×"),e=="×"&&(this.operator="×"),e=="="&&(this.operator="="),this.updateLayout()}updateLayout(){var e=this.operator,t=12+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(e),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class Fr extends kt{constructor(e=1,t="",r=1){super(),this.type="omdTerm",this.coefficient=e,this.variable=t,this.exponent=r,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setValue(e,t,r),this.updateLayout()}loadFromJSON(e){typeof e.coefficient<"u"&&(this.coefficient=e.coefficient),typeof e.variable<"u"&&(this.variable=e.variable),typeof e.exponent<"u"&&(this.exponent=e.exponent),this.updateLayout()}setValue(e,t="",r=1){this.coefficient=e,this.variable=t,this.exponent=r,this.updateLayout()}updateLayout(){var e="";this.variable&&this.variable.length!=0?(e=this.coefficient.toString()+this.variable,this.coefficient==1&&(e=this.variable)):e=this.coefficient.toString(),this.exponent&&(this.exponent==1||(this.exponent==2?e+="²":this.exponent==3?e+="³":e+="<sup>"+this.exponent.toString()+"</sup>"));var t=15+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(e),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class ui extends kt{constructor(e=1){super(),this.type="omdNumber",this.value=e,this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.value.toString()),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setValue(e)}loadFromJSON(e){typeof e.value<"u"&&(this.value=e.value),this.updateLayout()}setValue(e){this.value=e,this.updateLayout()}updateLayout(){var e=this.value.toString(),t=10+e.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(this.value.toString()),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class li extends kt{constructor(e="A"){super(),this.type="omdVariable",this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setName(e)}loadFromJSON(e){typeof e.name<"u"&&(this.name=e.name),this.updateLayout()}setName(e){this.name=e,this.updateLayout()}updateLayout(){var e=15+this.name.length*10;this.backRect.setWidthAndHeight(e,30),this.numText.setWidthAndHeight(e,30),this.numText.setText(this.name),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}function ag(n){const e=String(n||"").replace(/\s+/g,"");if(!e)return null;const t=/([+-]?\d*\.?\d+[a-zA-Z]*)|([+-]?[a-zA-Z]+\^?\d*)|([+\-*/=×÷])/g,r=e.match(t)||[];if(r.length===0)return null;const i=[];for(let o of r){if(/^[+\-*/=×÷]$/.test(o)){i.push({omdType:"operator",operator:o.replace("*","×")});continue}const l=o.match(/^([+-]?)(\d*\.?\d*)([a-zA-Z]?)(?:\^(\d+))?$/);if(l){const u=l[1];let c=u==="-"?-1:1;const h=l[2],f=l[3]||"",d=l[4]?Number(l[4]):1;let p=1;h&&h.length>0&&(p=Number(h));let m=!1;if(u){const y=i.length===0,v=!y&&i[i.length-1].omdType==="operator";!y&&!v&&(m=!0)}m&&(i.push({omdType:"operator",operator:u}),c=1),!f&&h?i.push({omdType:"number",value:c*p}):i.push({omdType:"term",coefficient:c*p,variable:f,exponent:d})}else i.push({omdType:"string",name:o})}const s=[];for(let o=0;o<i.length;o++){const l=i[o];if(l.omdType==="operator"&&(l.operator==="+"||l.operator==="-")){const u=s.length===0,c=!u&&s[s.length-1].omdType==="operator";if(u||c){const h=i[o+1];if(h&&(h.omdType==="term"||h.omdType==="number")){h.omdType==="number"?h.value=l.operator==="-"?-h.value:h.value:h.omdType==="term"&&(h.coefficient=l.operator==="-"?-h.coefficient:h.coefficient),o++,s.push(h);continue}}}s.push(l)}const a=[];for(let o=0;o<s.length;o++)a.push(s[o]);return{termsAndOpers:a}}function Kq(n){const t=String(n||"").split("=");if(t.length!==2)return null;const r=t[0].trim(),i=t[1].trim(),s=ag(r),a=ag(i);return!s||!a?null:{leftExpression:s,rightExpression:a}}class zt extends kt{constructor(){super(),this.type="omdExpression",this.termSet=[],this.operatorSet=[],this.inset=5,this.expressionNode=null,this.expressionStack=new qr,this.expressionStack.setPosition(this.inset,0),this.expressionStack.setSpacer(-6),this.addChild(this.expressionStack)}_renderWithExpressionNode(e,t){if(typeof math>"u"||typeof math.parse!="function")throw new Error("math.js is required to parse expression strings");const r=math.parse(e),i=_t(r),s=new i(r);typeof t=="number"&&s.setFontSize&&s.setFontSize(t),s.hideBackgroundByDefault&&s.hideBackgroundByDefault(),s.computeDimensions&&s.computeDimensions(),s.updateLayout&&s.updateLayout(),typeof this.expressionStack.removeAllChildren=="function"?this.expressionStack.removeAllChildren():this.expressionStack.childList=[],this.expressionStack.addChild(s),this.expressionStack.setSpacer(0),this.expressionNode=s,this.updateLayout()}loadFromJSON(e){if(typeof e=="string"){try{this._renderWithExpressionNode(e,e.fontSize);return}catch(o){console.warn("⚠️ omdExpression math.js render failed, falling back to legacy parsing:",(o==null?void 0:o.message)||o)}const a=ag(e);a&&(e=a)}else if(typeof e=="object"&&e.expression&&typeof e.expression=="string"){try{this._renderWithExpressionNode(e.expression,e.fontSize);return}catch(o){console.warn("⚠️ omdExpression math.js render failed, falling back to legacy parsing:",(o==null?void 0:o.message)||o)}const a=ag(e.expression);a&&(e={...e,...a})}if(typeof e.termsAndOpers<"u")for(var t=0;t<e.termsAndOpers.length;t++){var r=e.termsAndOpers[t];if(r.omdType=="term"){var i=new Fr;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="variable"){var i=new li;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="number"){var i=new ui;i.loadFromJSON(r),i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}else if(r.omdType=="operator"){var s=new Kn;s.loadFromJSON(r),s.hideBackgroundByDefault(),this.operatorSet.push(s),this.expressionStack.addChild(s)}else if(r.omdType=="string"){var i=new Fr(1,r.name,1);i.hideBackgroundByDefault(),this.termSet.push(i),this.expressionStack.addChild(i)}}this.updateLayout()}addTerm(e,t="",r="1"){var i=new Fr(e,t,r);this.termSet.push(i),this.expressionStack.addChild(i),this.updateLayout(),i.hideBackgroundByDefault()}addOperator(e){var t=new Kn(e);this.operatorSet.push(t),this.expressionStack.addChild(t),this.updateLayout(),t.hideBackgroundByDefault()}updateLayout(){if(this.expressionNode){const t=this.expressionNode;t.computeDimensions&&t.computeDimensions(),t.updateLayout&&t.updateLayout(),this.expressionStack.doHorizontalLayout(),this.expressionStack.setPosition(this.inset,this.inset);const r=t.width||this.expressionStack.width,i=t.height||this.expressionStack.height;this.backRect.setWidthAndHeight(r+this.inset*2,i+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height;return}this.expressionStack.doHorizontalLayout();var e=this.expressionStack.width;this.backRect.setWidthAndHeight(e+this.inset*2,30),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height}}class SE extends kt{constructor(e="string"){super(),this.type="omdString",this.numText=new Bt,this.numText.setWidthAndHeight(30,30),this.numText.setText(this.name),this.numText.setFontFamily("Albert Sans"),this.numText.setFontColor("black"),this.numText.setFontSize(18),this.numText.setVerticalCentering(),this.numText.setAlignment("center"),this.addChild(this.numText),this.setName(e)}setName(e){this.name=e;var t=15+this.name.length*10;this.backRect.setWidthAndHeight(t,30),this.numText.setWidthAndHeight(t,30),this.numText.setText(this.name),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}loadFromJSON(e){if(typeof e=="string"){this.setName(e);return}if(e&&typeof e.name=="string"){this.setName(e.name);return}}}class Ba extends kt{constructor(){super(),this.type="omdPowerExpression",this.leftExpression=null,this.rightExpression=null,this.centerEquation=!0,this.inset=5,this.equationStack=new qr,this.equationStack.setSpacer(-7),this.addChild(this.equationStack),this.leftHolder=new Oe,this.equationStack.addChild(this.leftHolder),this.equalSign=new Kn("="),this.equationStack.addChild(this.equalSign),this.rightHolder=new Oe,this.equationStack.addChild(this.rightHolder),this.equationNode=null}loadFromJSON(e){if(typeof e.equation=="string"&&e.equation.trim())try{this._renderWithEquationNode(e.equation,e.fontSize);return}catch(r){console.warn("⚠️ omdEquation math.js render failed, falling back to legacy parsing:",(r==null?void 0:r.message)||r)}function t(r){return r&&r.termsAndOpers&&Array.isArray(r.termsAndOpers)&&r.termsAndOpers.forEach(i=>{i&&i.omdType==="operator"&&i.symbol&&(i.symbol==="−"&&(i.symbol="-"),i.symbol==="+"&&(i.symbol="+"))}),r}if(typeof e.leftExpression<"u"&&e.leftExpression){let r=e.leftExpression;r=t(r),r.omdType=="expression"?this.leftExpression=new zt:r.omdType=="number"?this.leftExpression=new ui:r.omdType=="variable"?this.leftExpression=new li:r.omdType=="term"?this.leftExpression=new Fr:(r.omdType=="string"||typeof r=="string")&&(this.leftExpression=new zt),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&r&&typeof r=="object"&&this.leftExpression.loadFromJSON(r),this.leftExpression&&(this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression))}if(typeof e.rightExpression<"u"&&e.rightExpression){let r=e.rightExpression;r=t(r),r.omdType=="expression"?this.rightExpression=new zt:r.omdType=="number"?this.rightExpression=new ui:r.omdType=="variable"?this.rightExpression=new li:r.omdType=="term"?this.rightExpression=new Fr:(r.omdType=="string"||typeof r=="string")&&(this.rightExpression=new zt),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&r&&typeof r=="object"&&this.rightExpression.loadFromJSON(r),this.rightExpression&&(this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression))}if((!this.leftExpression||!this.rightExpression)&&typeof e.equation=="string"){const r=Kq(e.equation);if(r)this.leftExpression||(this.leftExpression=new zt),this.rightExpression||(this.rightExpression=new zt),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&this.leftExpression.loadFromJSON(r.leftExpression),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&this.rightExpression.loadFromJSON(r.rightExpression),this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression);else{const i=String(e.equation||"").split("="),s=(i[0]||"").trim(),a=(i[1]||"").trim();this.leftExpression||(this.leftExpression=new SE(s||"")),this.rightExpression||(this.rightExpression=new SE(a||"")),this.leftExpression&&typeof this.leftExpression.loadFromJSON=="function"&&typeof s=="string"&&this.leftExpression.loadFromJSON(s),this.rightExpression&&typeof this.rightExpression.loadFromJSON=="function"&&typeof a=="string"&&this.rightExpression.loadFromJSON(a),this.leftHolder.removeAllChildren(),this.leftHolder.addChild(this.leftExpression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpression)}}this.equalSign&&typeof this.equalSign.hideBackgroundByDefault=="function"&&this.equalSign.hideBackgroundByDefault(),this.leftExpression&&typeof this.leftExpression.hideBackgroundByDefault=="function"&&this.leftExpression.hideBackgroundByDefault(),this.rightExpression&&typeof this.rightExpression.hideBackgroundByDefault=="function"&&this.rightExpression.hideBackgroundByDefault(),this.centerEquation=!1,this.updateLayout()}_renderWithEquationNode(e,t){if(typeof math>"u"||typeof math.parse!="function")throw new Error("math.js is required to parse equation strings");const r=ut.fromString(e);typeof t=="number"&&r.setFontSize&&r.setFontSize(t),r.hideBackgroundByDefault&&r.hideBackgroundByDefault(),r.computeDimensions&&r.computeDimensions(),r.updateLayout&&r.updateLayout(),typeof this.equationStack.removeAllChildren=="function"?this.equationStack.removeAllChildren():this.equationStack.childList=[],this.equationStack.addChild(r),this.equationStack.setSpacer(0),this.equationNode=r,this.leftExpression=null,this.rightExpression=null,this.centerEquation=!1,this.updateLayout()}setLeftAndRightExpressions(e,t){this.leftExpression=e,this.leftHolder.removeAllChildren(),this.leftHolder.addChild(e),this.rightExpression=t,this.rightHolder.removeAllChildren(),this.rightHolder.addChild(t),this.equalSign.hideBackgroundByDefault(),this.leftExpression.hideBackgroundByDefault(),this.rightExpression.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){if(this.equationNode){const i=this.equationNode;i.computeDimensions&&i.computeDimensions(),i.updateLayout&&i.updateLayout(),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,this.inset);const s=i.width||this.equationStack.width,a=i.height||this.equationStack.height;this.backRect.setWidthAndHeight(s+this.inset*2,a+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`);return}this.leftHolder.setWidthAndHeight(this.leftExpression.width,this.leftExpression.height),this.rightHolder.setWidthAndHeight(this.rightExpression.width,this.rightExpression.height),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,this.inset);var e=this.equationStack.width,t=this.equationStack.height;if(this.backRect.setWidthAndHeight(e+this.inset*2,t+this.inset*2),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.width=this.backRect.width,this.height=this.backRect.height,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.centerEquation){var r=this.leftExpression.width+this.equalSign.width*.5;this.backRect.setPosition(-1*r+this.inset/2,0),this.equationStack.setPosition(-1*r+this.inset+this.inset/2,this.inset)}}}class qs extends kt{constructor(){super(),this.type="omdPowerExpression",this.expression=null,this.exponent=null,this.expressionHolder=new Oe,this.addChild(this.expressionHolder),this.exponentHolder=new Oe,this.addChild(this.exponentHolder)}loadFromJSON(e){typeof e.baseExpression<"u"&&(e.baseExpression.omdType=="expression"&&(this.expression=new zt),e.baseExpression.omdType=="number"&&(this.expression=new ui),e.baseExpression.omdType=="variable"&&(this.expression=new li),e.baseExpression.omdType=="term"&&(this.expression=new Fr),this.expression.loadFromJSON(e.baseExpression),this.expressionHolder.removeAllChildren(),this.expressionHolder.addChild(this.expression)),typeof e.exponentExpression<"u"&&(e.exponentExpression.omdType=="expression"&&(this.exponent=new zt),e.exponentExpression.omdType=="number"&&(this.exponent=new ui),e.exponentExpression.omdType=="variable"&&(this.exponent=new li),e.exponentExpression.omdType=="term"&&(this.exponent=new Fr),this.exponent.loadFromJSON(e.exponentExpression),this.exponentHolder.removeAllChildren(),this.exponentHolder.addChild(this.exponent)),this.updateLayout()}setExpressionAndPower(e,t){this.expression=e,this.expressionHolder.removeAllChildren(),this.expressionHolder.addChild(e),this.exponent=t,this.exponentHolder.removeAllChildren(),this.exponentHolder.addChild(t),this.updateLayout()}updateLayout(){this.expressionHolder.setPosition(0,0),this.exponentHolder.setPosition(this.expression.width-10,-15),this.exponentHolder.setScale(.7)}}class ka extends kt{constructor(){super(),this.type="omdPowerExpression",this.numeratorExpression=null,this.denominatorExpression=null,this.numeratorHolder=new jsvgGroup,this.addChild(this.numeratorHolder),this.denominatorHolder=new jsvgGroup,this.addChild(this.denominatorHolder),this.dividerLine=new jsvgLine,this.setStrokeWidth(2),this.setStrokeColor("black"),this.addChild(this.dividerLine)}loadFromJSON(e){typeof e.numeratorExpression<"u"&&(e.numeratorExpression.omdType=="expression"&&(this.numeratorExpression=new zt),e.numeratorExpression.omdType=="number"&&(this.numeratorExpression=new ui),e.numeratorExpression.omdType=="variable"&&(this.numeratorExpression=new li),e.numeratorExpression.omdType=="term"&&(this.numeratorExpression=new Fr),this.numeratorExpression.loadFromJSON(e.numeratorExpression),this.numeratorHolder.removeAllChildren(),this.numeratorHolder.addChild(this.numeratorExpression)),typeof e.denominatorExpression<"u"&&(e.denominatorExpression.omdType=="expression"&&(this.denominatorExpression=new zt),e.denominatorExpression.omdType=="number"&&(this.denominatorExpression=new ui),e.denominatorExpression.omdType=="variable"&&(this.denominatorExpression=new li),e.denominatorExpression.omdType=="term"&&(this.denominatorExpression=new Fr),this.denominatorExpression.loadFromJSON(e.denominatorExpression),this.denominatorHolder.removeAllChildren(),this.denominatorHolder.addChild(this.denominatorExpression)),this.updateLayout()}setNumeratorAndDenominator(e,t){this.numeratorExpression=e,this.numeratorHolder.removeAllChildren(),this.numeratorHolder.addChild(e),this.denominatorExpression=t,this.denominatorHolder.removeAllChildren(),this.denominatorHolder.addChild(t),this.numeratorExpression.hideBackgroundByDefault(),this.denominatorExpression.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){this.numeratorHolder.setPosition(5,0),this.denominatorHolder.setPosition(5,30);var e=this.numeratorExpression.width;this.denominatorExpression.width>e&&(e=this.denominatorExpression.width);var t=e/2-this.numeratorExpression.width/2+5;this.numeratorHolder.setPosition(t,0),t=e/2-this.denominatorExpression.width/2+5,this.denominatorHolder.setPosition(t,30),this.dividerLine.setEndpoints(5,30,e+5,30),this.backRect.setWidthAndHeight(e+10,60),this.setWidthAndHeight(this.backRect.width,this.backRect.height)}}class Pa extends kt{constructor(){super(),this.type="omdPowerExpression",this.leftExpression=null,this.rightExpresion=null,this.functionName="f",this.inputVariableArray=[],this.centerEquation=!1,this.inset=5,this.equationStack=new qr,this.equationStack.setSpacer(-7),this.addChild(this.equationStack),this.leftHolder=new Oe,this.equationStack.addChild(this.leftHolder),this.equalSign=new Kn("="),this.equationStack.addChild(this.equalSign),this.rightHolder=new Oe,this.equationStack.addChild(this.rightHolder)}loadFromJSON(e){typeof e.name<"u"&&(this.functionName=e.name),typeof e.inputVariables<"u"&&(this.inputVariableArray=e.inputVariables),typeof e.expression<"u"&&(e.expression.omdType=="expression"&&(this.rightExpresion=new zt),this.rightExpresion.loadFromJSON(e.expression),this.rightHolder.removeAllChildren(),this.rightHolder.addChild(this.rightExpresion)),this.leftHolder.removeAllChildren();var t=this.functionName+"("+this.inputVariableArray[0]+")";this.leftExpression=new zt,this.leftExpression.loadFromJSON(t),this.leftHolder.addChild(this.leftExpression),this.updateLayout()}setNameVariableAndExpression(e,t,r){this.leftHolder.removeAllChildren();var i=e+"("+t+")";this.leftExpression=new zt,this.leftExpression.loadFromJSON(i),this.leftHolder.addChild(this.leftExpression),this.rightExpresion=r,this.rightHolder.removeAllChildren(),this.rightHolder.addChild(r),this.equalSign.hideBackgroundByDefault(),this.leftExpression.hideBackgroundByDefault(),this.rightExpresion.hideBackgroundByDefault(),this.updateLayout()}updateLayout(){this.leftHolder.setWidthAndHeight(this.leftExpression.width,this.leftExpression.height),this.rightHolder.setWidthAndHeight(this.rightExpresion.width,this.rightExpresion.height),this.equationStack.doHorizontalLayout(),this.equationStack.setPosition(this.inset,0);var e=this.equationStack.width;if(this.backRect.setWidthAndHeight(e+this.inset*2,30),this.setWidthAndHeight(this.backRect.width,this.backRect.height),this.centerEquation){var t=this.leftExpression.width+this.equalSign.width*.5;this.backRect.setPosition(-1*t+this.inset/2,0),this.equationStack.setPosition(-1*t+this.inset+this.inset/2,0)}}}class za extends Oe{constructor(){super(),this.type="omdNumberLine",this.size="medium",this.divisions=5,this.arrowPosition=1,this.updateLayout()}loadFromJSON(e){typeof e.divisions<"u"&&(this.divisions=e.divisions),typeof e.arrowPosition<"u"&&(this.arrowPosition=e.arrowPosition),typeof e.size<"u"&&(this.size=e.size),this.updateLayout()}setDivisions(e){this.divisions=e,this.updateLayout()}setRenderType(e){this.renderType=e,this.updateLayout()}setSize(e){this.size=e,this.updateLayout()}setArrowPosition(e){this.arrowPosition=e,this.updateLayout()}updateLayout(){this.removeAllChildren();var e=new Oe;this.addChild(e);var t=120,r=14;this.size=="large"&&(t=120,r=14),this.size=="medium"&&(t=80,r=12),this.size=="small"&&(t=40,r=10);var i=new Tr;i.setFillColor(Fe.mediumGray),i.setWidthAndHeight(t,t),e.addChild(i),e.setPosition(t/2,t/2);for(var s=this.divisions,a=Math.PI*2/s,o=0;o<s;o++){var d=o*a-Math.PI/2,u=Math.cos(d)*t/2,c=Math.sin(d)*t/2,l=new Ut;l.setStrokeColor("white"),l.setEndpoints(0,0,u,c),e.addChild(l);var d=(o+.5)*a-Math.PI/2,u=Math.cos(d)*t*.4,c=Math.sin(d)*t*.4,h=new Bt;h.setWidthAndHeight(30,30),h.setText((o+1).toString()),h.setFontFamily("Albert Sans"),h.setFontColor("black"),h.setFontSize(r),h.setAlignment("center"),h.setPosition(u-15,c-7),e.addChild(h)}var f=t*.4;this.arrow=new Ni,this.arrow.addPoint(0,0),this.arrow.addPoint(f*.8,f*.1),this.arrow.addPoint(f,0),this.arrow.addPoint(f*.8,f*-.1),this.arrow.addPoint(0,0),this.arrow.updatePath(),this.arrow.setFillColor("black"),this.arrow.setOpacity(.8),e.addChild(this.arrow);var d=-90+360/this.divisions*(this.arrowPosition-.5);this.arrow.setRotation(d),this.width=t,this.height=t,this.svgObject.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`)}}class e9 extends Oe{constructor(){super(),window.addEventListener("resize",this.onResize.bind(this)),window.addEventListener("keydown",this.onKeydown.bind(this)),this.setPosition(0,-50);var e=new ui(100);e.setPosition(100,100),this.addChild(e);var t=new li("x");t.setPosition(100,150),this.addChild(t);var v=new Fr(3,"x",2);v.setPosition(100,200),this.addChild(v);var S=new Kn("*");S.setPosition(100,250),this.addChild(S);var r=new zt;r.loadFromJSON(expressionSample),r.setPosition(100,300),this.addChild(r);var i=new qs,s=new zt;s.addTerm(7),s.addOperator("-"),s.addTerm(5,"x"),i.setExpressionAndPower(s,new Fr(3,"x",2)),i.setPosition(100,370),this.addChild(i);var a=new ka,o=new zt;o.addTerm(7),o.addOperator("-"),o.addTerm(5,"x");var l=new zt;l.addTerm(3,"x"),l.addOperator("+"),l.addTerm(2),l.addOperator("-"),l.addTerm(3);var u=new qs,c=new zt;c.addTerm("4","x","3"),c.addOperator("x"),c.addTerm("5","y","2"),u.setExpressionAndPower(l,c),a.setNumeratorAndDenominator(l,o),a.setPosition(100,440),this.addChild(a);var h=new Pa,p=new zt;p.addTerm(3,"x"),p.addOperator("+"),p.addTerm(2),h.setNameVariableAndExpression("f","x",p),h.setPosition(100,540),this.addChild(h);var f=new Ba,d=new zt;d.addTerm(7),d.addOperator("-"),d.addTerm(5,"x");var p=new zt;p.addTerm(3,"x"),p.addOperator("+"),p.addTerm(2),f.setLeftAndRightExpressions(d,p),f.setPosition(100,610),this.addChild(f);var m=new Qn;m.loadFromJSON(numberLineSample),m.setPosition(400,100),m.updateLayout(),this.addChild(m);var v=new mn;v.loadFromJSON(tapeDiagramSample),v.setPosition(400,200),this.addChild(v),v=new mn,v.loadFromJSON(tapeDiagramSample2),v.setPosition(400,300),this.addChild(v);var y=new Oa;y.loadFromJSON(balanceHangerSample2),y.setPosition(300,100),this.addChild(y);var v=new $i;v.setValue(8),v.setSize("medium"),v.setPosition(380,620),this.addChild(v);var S=new Zn;S.setValues(3,5),S.setSize("large"),S.setPosition(490,610),S.setRenderType("pie"),this.addChild(S);var S=new Zn;S.setValues(3,5),S.setSize("medium"),S.setPosition(620,620),S.setRenderType("dots"),this.addChild(S);var S=new Zn;S.setValues(3,5),S.setSize("large"),S.setPosition(520,740),S.setRenderType("bar"),this.addChild(S);var g=new $s;g.setPosition(350,380),g.setGraphFunction("1/2/(x)"),g.setDotValues([[1,1],[3,2],[-3,2]]),g.setSize("medium"),this.addChild(g),g=new $s,g.setPosition(570,380),g.loadFromJSON(planeWithShapes),this.addChild(g);var b=new za;b.setPosition(810,610),b.setDivisions(8),b.setArrowPosition(3),b.setSize("large"),this.addChild(b),b=new ks,b.setPosition(340,860),b.loadFromJSON(rightTriangleSample),this.addChild(b),b=new Ps,b.setPosition(420,860),b.loadFromJSON(isoscelesTriangleSample),this.addChild(b),b=new zs,b.setPosition(470,860),b.loadFromJSON(rectangleSample),this.addChild(b),b=new Rs,b.setPosition(650,830),b.loadFromJSON(ellipseSample),this.addChild(b),b=new Ls,b.setPosition(750,830),b.loadFromJSON(circleSample),this.addChild(b),b=new Is,b.setPosition(830,830),b.loadFromJSON(regularPolygonSample),this.addChild(b),this.inputField=new jsvgTextArea,this.inputField.setPlaceholderText("please enter your request here"),this.inputField.setWidthAndHeight(400,100),this.inputField.setPosition(800,100),this.inputField.setFontFamily("Albert Sans"),this.inputField.setFontColor("black"),this.inputField.setFontSize(14),this.inputField.div.style.backgroundColor=Fe.lightGray,this.inputField.div.style.border="0px",this.inputField.div.style.padding="10px",this.addChild(this.inputField),this.inputButton=new jsvgButton,this.inputButton.setText("submit"),this.inputButton.setFillColor(Fe.lightGray),this.inputButton.setPosition(800,220),this.inputButton.setClickCallback(this.handleSubmitClick.bind(this)),this.addChild(this.inputButton),this.responseText=new jsvgTextBox,this.responseText.setText(""),this.responseText.setWidthAndHeight(400,30),this.responseText.setPosition(920,225),this.responseText.setFontFamily("Albert Sans"),this.responseText.setFontColor(Fe.darkGray),this.responseText.setFontSize(14),this.addChild(this.responseText),this.AIholder=new Oe,this.AIholder.setPosition(800,350),this.addChild(this.AIholder),this.onResize()}onKeydown(e){}update(){super.update(),window.equatorScale=1.5}onResize(){}handleSubmitClick(e){this.responseText.setText("working...");var t=this.inputField.getText();console.log(t),this.fetchAI(t)}handleAIResponse(e){this.AIholder.removeAllChildren();var t=null;if(e.omdType=="number")var t=new ui;if(e.omdType=="variable")var t=new li;if(e.omdType=="operator")var t=new Kn;if(e.omdType=="term")var t=new Fr;if(e.omdType=="expression")var t=new zt;if(e.omdType=="powerExpression")var t=new qs;if(e.omdType=="rationalExpression")var t=new ka;if(e.omdType=="function")var t=new Pa;if(e.omdType=="equation")var t=new Ba;if(e.omdType=="numberLine")var t=new Qn;if(e.omdType=="balanceHanger"){var t=new Oa;t.setPosition(150,0)}if(e.omdType=="tapeDiagram")var t=new mn;if(e.omdType=="numberTile")var t=new $i;if(e.omdType=="ratioChart")var t=new Zn;if(e.omdType=="coordinatePlane")var t=new $s;if(e.omdType=="spinner")var t=new za;if(e.omdType=="rightTriangle")var t=new ks;if(e.omdType=="isoscelesTriangle")var t=new Ps;if(e.omdType=="rectangle")var t=new zs;if(e.omdType=="ellipse")var t=new Rs;if(e.omdType=="circle")var t=new Ls;if(e.omdType=="regularPolygon")var t=new Is;t.loadFromJSON(e),this.AIholder.addChild(t)}fetchAI(e){var t="";window.location.hostname.includes("localhost")?t="http://localhost:8888/.netlify/functions/ai-omd-lookup/":t="https://teaching-lab-omd.netlify.app/.netlify/functions/ai-omd-lookup/",t+="?topic='"+e+"'",fetch(t).then(r=>r.text()).then(r=>{var i=r;i=i.replaceAll("`",""),i=i.replaceAll("json","");try{var s=JSON.parse(i);this.responseText.setText(""),this.handleAIResponse(s)}catch{console.log(i),console.log(">>> data not parse-able"),this.responseText.setText("An error occured. Please try again.")}})}}class NE extends Oe{constructor(){super(),this.type="omdProblem",this.theText="",this.problemText=new Bt,this.problemText.setWidthAndHeight(250,30),this.problemText.setText("this it the problem text"),this.problemText.setFontFamily("Albert Sans"),this.problemText.setFontColor("black"),this.problemText.setFontSize(18),this.addChild(this.problemText)}loadFromJSON(e,t=null){if(console.log(e),typeof e.problemText<"u"&&(this.theText=e.problemText),typeof e.visualization<"u"&&(console.log(e),this.visualJSON=e.visualiation,console.log(this.visualJSON),console.log("testing 1 "),e.svgElement))try{let s=function(){let C=document.getElementById("_omd_measuring_svg");return C||(C=document.createElementNS(i,"svg"),C.setAttribute("id","_omd_measuring_svg"),C.style.position="absolute",C.style.left="-9999px",C.style.top="-9999px",C.style.width="1px",C.style.height="1px",C.style.visibility="hidden",document.body.appendChild(C)),C};this.problemText.setText(this.theText);const r=10,i="http://www.w3.org/2000/svg",o=e.svgElement.cloneNode(!0);let l=null;try{const C=o.querySelector&&o.querySelector("clipPath rect");if(C){const A=parseFloat(C.getAttribute("x")||"0"),E=parseFloat(C.getAttribute("y")||"0"),F=parseFloat(C.getAttribute("width")||"0"),O=parseFloat(C.getAttribute("height")||"0");F>0&&O>0&&(l={x:A,y:E,width:F,height:O})}}catch{}if(!l)try{let C=null;if(o.getAttribute&&(C=o.getAttribute("viewBox")),!C){const A=o.querySelector&&o.querySelector("svg");A&&A.getAttribute&&(C=A.getAttribute("viewBox"))}if(C){const A=C.trim().split(/\s+/).map(Number);A.length===4&&(l={x:A[0],y:A[1],width:A[2],height:A[3]})}}catch{}if(!l){const C=s(),A=document.createElementNS(i,"g");A.appendChild(o),C.appendChild(A);try{const E=A.getBBox();console.debug("omdProblem: measured bbox from wrapper",E),E&&E.width>0&&E.height>0&&(l={x:E.x,y:E.y,width:E.width,height:E.height})}catch{}try{C.removeChild(A)}catch{}}l||(l={x:0,y:0,width:250,height:250});const u=e&&typeof e.cropMargin=="number"?e.cropMargin:6;l={x:Math.max(0,l.x-u),y:Math.max(0,l.y-u),width:l.width+u*2,height:l.height+u*2},console.debug("omdProblem: final crop chosen (expanded)",l);const h=document.createElementNS(i,"svg");h.setAttribute("width",String(l.width)),h.setAttribute("height",String(l.height)),h.setAttribute("viewBox",`0 0 ${l.width} ${l.height}`);const f=document.createElementNS(i,"g");f.setAttribute("transform","translate(-55, -80)"),f.appendChild(o),h.appendChild(f);let d=0;try{this.problemText.height?d=this.problemText.height:this.problemText.svgObject&&this.problemText.svgObject.getBBox?d=this.problemText.svgObject.getBBox().height:d=30}catch{d=30}let p=300,m=null,y=8;try{e&&e.containerInfo?(typeof e.containerInfo.width=="number"&&(p=e.containerInfo.width),typeof e.containerInfo.offsetY=="number"&&(m=e.containerInfo.offsetY),typeof e.containerInfo.innerPadding=="number"&&(y=e.containerInfo.innerPadding)):this.width?p=this.width:this.problemText&&this.problemText.width&&(p=Math.max(300,this.problemText.width))}catch{p=300}const v=Math.round(m!==null?m+r:d+r),S=y,g=Math.max(20,p-S*2);let b=1;l.width>g&&(b=g/l.width);const w=Math.round(l.width*b),x=Math.round(l.height*b);h.setAttribute("width",String(w)),h.setAttribute("height",String(x));let N=Math.max(S,Math.round((p-w)/2));console.debug("omdProblem: containerWidth, desiredX, desiredY",{containerWidth:p,desiredX:N,desiredY:v,cropWidth:l.width,cropHeight:l.height,scaledWidth:w,scaledHeight:x,scale:b});const D=document.createElementNS(i,"g");if(D.appendChild(h),D.setAttribute("transform",`translate(${N}, ${v})`),this.svgObject.appendChild(D),e&&e.debugPlacement)try{const C=document.createElementNS(i,"rect");C.setAttribute("x","0"),C.setAttribute("y","0"),C.setAttribute("width",String(w)),C.setAttribute("height",String(x)),C.setAttribute("fill","none"),C.setAttribute("stroke","rgba(255,0,0,0.9)"),C.setAttribute("stroke-width","2"),C.setAttribute("pointer-events","none"),D.appendChild(C)}catch(C){console.warn("omdProblem: failed to add debugPlacement rect",C)}this.updateLayout();return}catch(r){console.warn("omdProblem: svgElement fast-path failed, falling back to regenerate:",r)}this.updateLayout()}setName(e){this.name=e,this.updateLayout()}updateLayout(){this.problemText.setText(this.theText);let e=400,t=130;try{if(this.problemText.width&&(e=this.problemText.width),this.problemText.height)t=this.problemText.height;else if(this.problemText.svgObject&&this.problemText.svgObject.getBBox){const a=this.problemText.svgObject.getBBox();a.width&&(e=a.width),a.height&&(t=a.height)}}catch{}let r=0;try{for(let a=0;a<this.children.length;a++){const o=this.children[a];if(o!==this.problemText&&o&&o.svgObject&&o.svgObject.getBBox){const l=o.svgObject.getBBox();r=Math.max(r,l.height+20)}}}catch{r=0}const i=Math.max(300,e),s=Math.max(200,t+r+20);this.setWidthAndHeight(i,s)}}class t9 extends Oe{constructor(){super(),console.log("canvas!!!"),window.theApp=this,window.addEventListener("resize",this.onResize.bind(this)),window.addEventListener("keydown",this.onKeydown.bind(this)),this.setPosition(0,-50),this.inputField=new fE,this.inputField.setPlaceholderText("please enter your request here"),this.inputField.setWidthAndHeight(600,100),this.inputField.setPosition(100,100),this.inputField.setFontFamily("Albert Sans"),this.inputField.setFontColor("black"),this.inputField.setFontSize(18),this.inputField.div.style.backgroundColor="#FFDD00",this.inputField.div.style.border="0px",this.inputField.div.style.padding="10px",this.addChild(this.inputField),this.inputButton=new Xn,this.inputButton.setText("submit"),this.inputButton.setFillColor(Fe.lightGray),this.inputButton.setPosition(100,220),this.inputButton.setClickCallback(this.handleSubmitClick.bind(this)),this.addChild(this.inputButton),this.responseText=new Bt,this.responseText.setText(""),this.responseText.setWidthAndHeight(400,30),this.responseText.setPosition(100,260),this.responseText.setFontFamily("Albert Sans"),this.responseText.setFontColor(Fe.darkGray),this.responseText.setFontSize(14),this.addChild(this.responseText),this.AIholder=new Oe,this.AIholder.setPosition(100,350),this.addChild(this.AIholder),this.onResize()}onKeydown(e){}update(){super.update(),window.equatorScale=1.5}onResize(){}handleSubmitClick(e){this.responseText.setText("working...");var t=this.inputField.getText();console.log(t),this.fetchAI(t)}handleAIResponse(e){var t=null;if(e.omdType=="number")var t=new ui;if(e.omdType=="variable")var t=new li;if(e.omdType=="operator")var t=new Kn;if(e.omdType=="term")var t=new Fr;if(e.omdType=="expression")var t=new zt;if(e.omdType=="powerExpression")var t=new qs;if(e.omdType=="rationalExpression")var t=new ka;if(e.omdType=="function")var t=new Pa;if(e.omdType=="equation")var t=new Ba;if(e.omdType=="numberLine")var t=new Qn;if(e.omdType=="balanceHanger"){var t=new Oa;t.setPosition(150,0)}if(e.omdType=="tapeDiagram")var t=new mn;if(e.omdType=="numberTile")var t=new $i;if(e.omdType=="ratioChart")var t=new Zn;if(e.omdType=="coordinatePlane")var t=new $s;if(e.omdType=="spinner")var t=new za;if(e.omdType=="rightTriangle")var t=new ks;if(e.omdType=="isoscelesTriangle")var t=new Ps;if(e.omdType=="rectangle")var t=new zs;if(e.omdType=="ellipse")var t=new Rs;if(e.omdType=="circle")var t=new Ls;if(e.omdType=="regularPolygon")var t=new Is;if(e.omdType=="problem")var t=new NE;t.loadFromJSON(e);var r=new r9;return r.addObject(t),this.AIholder.addChild(r),r}fetchAI(e){var t="";window.location.hostname.includes("localhost")?t="http://localhost:8888/.netlify/functions/ai-omd-lookup/":t="https://teaching-lab-omd.netlify.app/.netlify/functions/ai-omd-lookup/",t+="?topic='"+e+"'",fetch(t).then(r=>r.text()).then(r=>{var i=r;i=i.replaceAll("`",""),i=i.replaceAll("json",""),console.log("=== pre-parse ==="),console.log(i);try{var s=JSON.parse(i);console.log("=== parsedData ==="),console.log(s),this.responseText.setText(""),this.handleAIResponse(s)}catch{console.log(i),console.log(">>> data not parse-able"),this.responseText.setText("An error occured. Please try again.")}})}}class r9 extends Oe{constructor(){super(),this.clickRect=new Tr,this.clickRect.setWidthAndHeight(40,40),this.clickRect.setPosition(10,10),this.clickRect.setFillColor("transparent"),this.addChild(this.clickRect),this.clickRect.svgObject.onmousedown=this.handleMouseDown.bind(this),this.clickRect.svgObject.ontouchstart=this.handleMouseDown.bind(this),this.clickRect.svgObject.style.cursor="pointer",this.backRect=new Tr,this.backRect.setWidthAndHeight(20,20),this.backRect.setPosition(10,10),this.backRect.setFillColor("#DDDDDD"),this.addChild(this.backRect),this.backRect.svgObject.onmousedown=this.handleMouseDown.bind(this),this.backRect.svgObject.ontouchstart=this.handleMouseDown.bind(this),this.backRect.svgObject.style.cursor="pointer"}addObject(e){this.theObject=e,e.setPosition(10,10),this.addChild(e)}handleMouseDown(e){if(!this.visible)return;function t(i){i.preventDefault();var s,a;if(i.touches&&i.touches.length>=1?(s=i.touches[0].clientX,a=i.touches[0].clientY):(s=i.clientX,a=i.clientY),this.oldMouseX&&this.oldMouseY){var o=s-this.oldMouseX,l=a-this.oldMouseY,u=this.xpos+o,c=this.ypos+l;this.setPosition(u,c)}this.oldMouseX=s,this.oldMouseY=a}function r(i){window.onmousemove=null,window.ontouchmove=null,window.onmouseup=null,window.ontouchend=null,this.oldMouseX=0,this.oldMouseY=0}window.onmousemove=t.bind(this),window.ontouchmove=t.bind(this),window.onmouseup=r.bind(this),window.ontouchend=r.bind(this)}}const CE={small:14,medium:20,large:28};class ay extends kt{constructor(){super(),this.type="omdLabel",this.text="",this.size="medium",this.textBox=new Bt,this.textBox.setFontFamily("Albert Sans"),this.textBox.setFontColor("black"),this.textBox.setVerticalCentering(),this.textBox.setAlignment("left"),this.addChild(this.textBox),this.backRect.setFillColor("transparent"),this.backRect.setOpacity(0)}loadFromJSON(e){typeof e=="string"?this.text=e:(typeof e.text<"u"&&(this.text=e.text),typeof e.size<"u"&&(this.size=e.size),typeof e.color<"u"&&this.textBox.setFontColor(e.color)),this.updateLayout()}updateLayout(){const e=CE[this.size]??CE.medium;this.textBox.setFontSize(e);const t=8,r=e*.58,i=Math.max(60,Math.ceil(String(this.text).length*r)+t*2),s=e+t*2;this.textBox.setWidthAndHeight(i,s),this.textBox.setText(this.text??""),this.backRect.setWidthAndHeight(i,s),this.setWidthAndHeight(i,s),this.width=i,this.height=s}hideBackgroundByDefault(){this.backRect.setOpacity(0)}}class i9 extends j0{constructor(){super(),this.setViewbox(400,400),this.setBackgroundColor("#F8F8F4")}setCanvasSize(e,t){this.setViewbox(e,t)}setBackgroundColor(e){this.svgObject.style.backgroundColor=e}generateGraphic(e){if(this.removeAllChildren(),!e||!e.omdType){console.error("Invalid jsonData: missing omdType",e);return}var t=null;const r=e.omdType;switch(r){case"number":t=new ui;break;case"variable":t=new li;break;case"operator":t=new Kn;break;case"term":t=new Fr;break;case"expression":t=new zt;break;case"powerExpression":t=new qs;break;case"rationalExpression":t=new ka;break;case"function":t=new Pa;break;case"equation":if(e.equation&&typeof e.equation=="string"&&e.equation.includes("="))try{t=ut.fromString(e.equation),typeof t.computeDimensions=="function"&&t.computeDimensions(),typeof t.updateLayout=="function"&&t.updateLayout(),t.setPosition(0,30),this.addChild(t);return}catch(i){console.warn("⚠️ omdEquationNode failed, falling back to legacy omdEquation:",i)}if(e.leftExpression||e.rightExpression)console.log("📝 Using legacy omdEquation for complex JSON structure"),t=new Ba;else{console.warn("⚠️ Equation data missing both equation string and expression structure");return}break;case"numberLine":t=new Qn;break;case"doubleNumberLine":t=new sy;break;case"balanceHanger":t=new Oa;break;case"tapeDiagram":t=new mn;break;case"doubleTapeDiagram":t=new iy;break;case"numberTile":t=new $i;break;case"ratioChart":t=new Zn;break;case"coordinatePlane":t=new $s;break;case"spinner":t=new za;break;case"table":t=new ty;break;case"tileEquation":t=new ny;break;case"rightTriangle":t=new ks;break;case"isoscelesTriangle":t=new Ps;break;case"rectangle":t=new zs;break;case"ellipse":t=new Rs;break;case"circle":t=new Ls;break;case"regularPolygon":t=new Is;break;case"label":t=new ay;break;default:console.error(`Unsupported OMD type: ${r}. Available types: number, variable, operator, term, expression, powerExpression, rationalExpression, function, equation, numberLine, balanceHanger, tapeDiagram, numberTile, ratioChart, coordinatePlane, spinner, table, tileEquation, rightTriangle, isoscelesTriangle, rectangle, ellipse, circle, regularPolygon`);return}if(!t){console.error(`Failed to create OMD object for type: ${r}`);return}t.setPosition(0,30),r==="balanceHanger"&&t.setPosition(150,30);try{t.loadFromJSON(e)}catch(i){console.error(`Error loading JSON data for ${r}:`,i),console.error("JSON data:",e);return}this.addChild(t)}getSVG(){return this.svgObject}getDiv(){const e=document.createElement("div");return e.style.width=this.width+"px",e.style.height=this.height+"px",e.style.overflow="visible",e.appendChild(this.svgObject),e}}const og={balanceHanger:Oa,table:ty,tapeDiagram:mn,doubleTapeDiagram:iy,coordinatePlane:$s,numberLine:Qn,doubleNumberLine:sy,numberTile:$i,ratioChart:Zn,tileEquation:ny,spinner:za,equation:Ba,expression:zt,term:Fr,number:ui,variable:li,powerExpression:qs,rationalExpression:ka,function:Pa,rightTriangle:ks,isoscelesTriangle:Ps,rectangle:zs,ellipse:Rs,circle:Ls,regularPolygon:Is,label:ay};function n9(n){if(!n||typeof n!="object")throw new Error("createFromJSON requires a valid JSON object");const e=n.omdType;if(!e)throw new Error('JSON data must include an "omdType" field');const t=og[e];if(!t)throw new Error(`Unsupported omdType: "${e}". Supported types: ${Object.keys(og).join(", ")}`);const r=new t;return r.loadFromJSON(n),r}function s9(){return Object.keys(og)}function a9(n){return n in og}class Ra{constructor(e={}){var t,r,i,s,a,o,l,u,c,h,f,d,p,m,y,v,S,g,b,w;this.width=e.width||800,this.height=e.height||500,this.backgroundColor=e.backgroundColor||"white",this.showToolbar=e.showToolbar!==!1,this.showGrid=e.showGrid||!1,this.gridSpacing=e.gridSpacing||20,this.enabledTools=e.enabledTools||["pointer","pencil","eraser"],this.defaultTool=e.defaultTool||"pointer",this.enableFocusFrames=e.enableFocusFrames!==!1,this.enableKeyboardShortcuts=e.enableKeyboardShortcuts!==!1,this.enableMultiTouch=e.enableMultiTouch!==!1,this.tools={pencil:{strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,smoothing:.5,pressureSensitivity:!0,...(t=e.tools)==null?void 0:t.pencil},eraser:{size:20,hardness:.8,...(r=e.tools)==null?void 0:r.eraser}},this.theme={primary:"#007bff",secondary:"#6c757d",success:"#28a745",warning:"#ffc107",danger:"#dc3545",...e.theme},this.selection={border:{color:((s=(i=e.selection)==null?void 0:i.border)==null?void 0:s.color)??"#007bff",width:((o=(a=e.selection)==null?void 0:a.border)==null?void 0:o.width)??2,dasharray:((u=(l=e.selection)==null?void 0:l.border)==null?void 0:u.dasharray)??"4,2",cornerRadius:((h=(c=e.selection)==null?void 0:c.border)==null?void 0:h.cornerRadius)??void 0},handle:{size:((d=(f=e.selection)==null?void 0:f.handle)==null?void 0:d.size)??8,color:((m=(p=e.selection)==null?void 0:p.handle)==null?void 0:m.color)??"#007bff",strokeColor:((v=(y=e.selection)==null?void 0:y.handle)==null?void 0:v.strokeColor)??"#ffffff",strokeWidth:((g=(S=e.selection)==null?void 0:S.handle)==null?void 0:g.strokeWidth)??1,cornerRadius:((w=(b=e.selection)==null?void 0:b.handle)==null?void 0:w.cornerRadius)??1}},this._validate()}_validate(){if(this.width<=0||this.height<=0)throw new Error("Canvas dimensions must be positive numbers");const e=["pointer","pencil","eraser"],t=this.enabledTools.filter(r=>!e.includes(r));t.length>0&&(console.warn(`Invalid tools specified: ${t.join(", ")}`),this.enabledTools=this.enabledTools.filter(r=>e.includes(r))),this.enabledTools.length===0&&(this.enabledTools=["pencil"]),this.enabledTools.includes(this.defaultTool)||(this.defaultTool=this.enabledTools[0]),this._validateToolConfigs()}_validateToolConfigs(){this.tools.pencil.strokeWidth<=0&&(this.tools.pencil.strokeWidth=5),(this.tools.pencil.strokeOpacity<0||this.tools.pencil.strokeOpacity>1)&&(this.tools.pencil.strokeOpacity=1),this.tools.eraser.size<=0&&(this.tools.eraser.size=20),(this.tools.eraser.hardness<0||this.tools.eraser.hardness>1)&&(this.tools.eraser.hardness=.8)}update(e){Object.assign(this,e),this._validate()}getToolConfig(e){return this.tools[e]||{}}updateToolConfig(e,t){this.tools[e]||(this.tools[e]={}),Object.assign(this.tools[e],t),this._validateToolConfigs()}clone(){return new Ra({width:this.width,height:this.height,backgroundColor:this.backgroundColor,showToolbar:this.showToolbar,showGrid:this.showGrid,gridSpacing:this.gridSpacing,enabledTools:[...this.enabledTools],defaultTool:this.defaultTool,enableFocusFrames:this.enableFocusFrames,enableKeyboardShortcuts:this.enableKeyboardShortcuts,enableMultiTouch:this.enableMultiTouch,tools:JSON.parse(JSON.stringify(this.tools)),theme:{...this.theme},selection:JSON.parse(JSON.stringify(this.selection))})}toJSON(){return{width:this.width,height:this.height,backgroundColor:this.backgroundColor,showToolbar:this.showToolbar,showGrid:this.showGrid,gridSpacing:this.gridSpacing,enabledTools:this.enabledTools,defaultTool:this.defaultTool,enableFocusFrames:this.enableFocusFrames,enableKeyboardShortcuts:this.enableKeyboardShortcuts,enableMultiTouch:this.enableMultiTouch,tools:this.tools,theme:this.theme,selection:this.selection}}static fromJSON(e){return new Ra(e)}}class oy{constructor(e){this.canvas=e,this.lastPointerPosition={x:0,y:0},this.lastPointerTime=0,this.velocity={x:0,y:0},this.multiTouchState={isActive:!1,initialDistance:0,initialAngle:0,lastScale:1,lastRotation:0},this.gestureThresholds={minPinchDistance:20,minRotationAngle:.1}}handlePointerDown(e,t){this.lastPointerPosition={x:t.x,y:t.y},this.lastPointerTime=t.timestamp,this.velocity={x:0,y:0},t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure)}handlePointerMove(e,t){if(this._calculateVelocity(t),e.getCoalescedEvents){const r=e.getCoalescedEvents();t.coalescedEvents=r.map(i=>{const s=this.canvas.clientToSVG(i.clientX,i.clientY);return{x:s.x,y:s.y,pressure:this._normalizePressure(i.pressure),timestamp:i.timeStamp||Date.now()}})}t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure),this.lastPointerPosition={x:t.x,y:t.y},this.lastPointerTime=t.timestamp}handlePointerUp(e,t){this._calculateVelocity(t),t.velocity=this.velocity,t.normalizedPressure=this._normalizePressure(t.pressure),this.velocity={x:0,y:0}}handleMultiTouchStart(e){if(e.size===2){const t=Array.from(e.values()),r=t[0],i=t[1];this.multiTouchState.isActive=!0,this.multiTouchState.initialDistance=this._calculateDistance(r,i),this.multiTouchState.initialAngle=this._calculateAngle(r,i),this.multiTouchState.lastScale=1,this.multiTouchState.lastRotation=0,this.canvas.emit("multiTouchStart",{pointers:t,distance:this.multiTouchState.initialDistance,angle:this.multiTouchState.initialAngle})}}handleMultiTouchMove(e){if(e.size===2&&this.multiTouchState.isActive){const t=Array.from(e.values()),r=t[0],i=t[1],s=this._calculateDistance(r,i),a=this._calculateAngle(r,i),o=s/this.multiTouchState.initialDistance,l=a-this.multiTouchState.initialAngle;Math.abs(o-1)>.1&&(this.canvas.emit("pinch",{scale:o,deltaScale:o-this.multiTouchState.lastScale,center:this._calculateCenter(r,i)}),this.multiTouchState.lastScale=o),Math.abs(l)>this.gestureThresholds.minRotationAngle&&(this.canvas.emit("rotate",{rotation:l,deltaRotation:l-this.multiTouchState.lastRotation,center:this._calculateCenter(r,i)}),this.multiTouchState.lastRotation=l)}}handleMultiTouchEnd(e){e.size<2&&(this.multiTouchState.isActive=!1,this.canvas.emit("multiTouchEnd"))}_calculateVelocity(e){const t=e.timestamp-this.lastPointerTime;if(t>0){const r=e.x-this.lastPointerPosition.x,i=e.y-this.lastPointerPosition.y;this.velocity.x=r/t*1e3,this.velocity.y=i/t*1e3}}_normalizePressure(e=.5){if(e==null)return .5;let t=e;return t<.1&&(t=.1),t=Math.pow(t,.8),Math.max(0,Math.min(1,t))}_calculateDistance(e,t){const r=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(r*r+i*i)}_calculateAngle(e,t){return Math.atan2(t.clientY-e.clientY,t.clientX-e.clientX)}_calculateCenter(e,t){const r=(e.clientX+t.clientX)/2,i=(e.clientY+t.clientY)/2;return this.canvas.clientToSVG(r,i)}getVelocity(){return{x:this.velocity.x,y:this.velocity.y,magnitude:Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),angle:Math.atan2(this.velocity.y,this.velocity.x)}}getMultiTouchState(){return{isActive:this.multiTouchState.isActive,scale:this.multiTouchState.lastScale,rotation:this.multiTouchState.lastRotation}}}class uy{constructor(e){this.canvas=e,this.isInitialized=!1,this.pointerEventHandler=new oy(e),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerCancel=this._onPointerCancel.bind(this),this._onPointerEnter=this._onPointerEnter.bind(this),this._onPointerLeave=this._onPointerLeave.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this._onWheel=this._onWheel.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this.activePointers=new Map,this.isDrawing=!1,this.lastEventTime=0}initialize(){if(this.isInitialized)return;const e=this.canvas.svg;e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUp),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("pointerenter",this._onPointerEnter),e.addEventListener("pointerleave",this._onPointerLeave),this.canvas.config.enableKeyboardShortcuts&&(document.addEventListener("keydown",this._onKeyDown),document.addEventListener("keyup",this._onKeyUp)),e.addEventListener("wheel",this._onWheel),e.addEventListener("contextmenu",this._onContextMenu),e.style.touchAction="none",this.isInitialized=!0}_onPointerDown(e){e.preventDefault(),this.activePointers.set(e.pointerId,e),e.target.setPointerCapture(e.pointerId);const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>1){this.pointerEventHandler.handleMultiTouchStart(this.activePointers);return}this.pointerEventHandler.handlePointerDown(e,r);const i=this.canvas.toolManager.getActiveTool();i&&(i.onPointerDown(r),this.isDrawing===!1&&(i==null?void 0:i.name)!=="pointer"&&(this.isDrawing=!0)),this.canvas.emit("pointerDown",r)}_onPointerMove(e){const t=Date.now();if(t-this.lastEventTime<16)return;this.lastEventTime=t,this.activePointers.has(e.pointerId)&&this.activePointers.set(e.pointerId,e);const r=this.canvas.clientToSVG(e.clientX,e.clientY),i=this._normalizePointerEvent(e,r);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>1){this.pointerEventHandler.handleMultiTouchMove(this.activePointers);return}if(this.canvas.cursor&&(this.canvas.cursor.setPosition(r.x,r.y),e.pressure!==void 0&&this.canvas.cursor.setPressureFeedback(e.pressure)),this.pointerEventHandler.handlePointerMove(e,i),this.isDrawing){const s=this.canvas.toolManager.getActiveTool();s&&s.onPointerMove(i)}this.canvas.emit("pointerMove",i)}_onPointerUp(e){this.activePointers.delete(e.pointerId),e.target.releasePointerCapture(e.pointerId);const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);if(this.canvas.config.enableMultiTouch&&this.activePointers.size>=1){this.pointerEventHandler.handleMultiTouchEnd(this.activePointers);return}this.isDrawing=!1,this.pointerEventHandler.handlePointerUp(e,r);const i=this.canvas.toolManager.getActiveTool();i&&i.onPointerUp(r),this.canvas.emit("pointerUp",r)}_onPointerCancel(e){this.activePointers.delete(e.pointerId),e.target.releasePointerCapture(e.pointerId),this.isDrawing=!1;const t=this.canvas.toolManager.getActiveTool();t&&t.onCancel(),this.canvas.emit("pointerCancel",{pointerId:e.pointerId})}_onPointerEnter(e){if(this.canvas.cursor){this.canvas.cursor.show();const t=this.canvas.toolManager.getActiveTool();t&&(t.getCursor&&this.canvas.cursor.setShape(t.getCursor()),t.config&&this.canvas.cursor.updateFromToolConfig(t.config))}if(e.buttons!==0){const t=this.canvas.clientToSVG(e.clientX,e.clientY),r=this._normalizePointerEvent(e,t);this.isDrawing=!0;const i=this.canvas.toolManager.getActiveTool();i&&i.onPointerDown(r)}this.canvas.emit("pointerEnter",{event:e})}_onPointerLeave(e){this.canvas.cursor&&this.canvas.cursor.hide(),e.buttons===0&&(this.isDrawing=!1),e.buttons===0&&this.activePointers.clear(),this.canvas.emit("pointerLeave",{event:e})}_onKeyDown(e){if(e.target.tagName==="INPUT"||e.target.tagName==="TEXTAREA")return;const t=e.key.toLowerCase();switch(t){case"p":this.canvas.config.enabledTools.includes("pencil")&&(this.canvas.toolManager.setActiveTool("pencil"),e.preventDefault());break;case"e":this.canvas.config.enabledTools.includes("eraser")&&(this.canvas.toolManager.setActiveTool("eraser"),e.preventDefault());break;case"s":this.canvas.config.enabledTools.includes("select")&&(this.canvas.toolManager.setActiveTool("select"),e.preventDefault());break;case"escape":const i=this.canvas.toolManager.getActiveTool();i&&i.onCancel(),e.preventDefault();break}const r=this.canvas.toolManager.getActiveTool();r&&r.onKeyboardShortcut&&r.onKeyboardShortcut(t,e)&&e.preventDefault(),this.canvas.emit("keyDown",{key:t,event:e})}_onKeyUp(e){if(e.target.tagName==="INPUT"||e.target.tagName==="TEXTAREA")return;const t=e.key.toLowerCase();this.canvas.emit("keyUp",{key:t,event:e})}_onWheel(e){e.preventDefault();const t=this.canvas.clientToSVG(e.clientX,e.clientY);this.canvas.emit("wheel",{deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,x:t.x,y:t.y,ctrlKey:e.ctrlKey,metaKey:e.metaKey})}_onContextMenu(e){e.preventDefault()}_normalizePointerEvent(e,t){return{pointerId:e.pointerId,pointerType:e.pointerType,isPrimary:e.isPrimary,x:t.x,y:t.y,clientX:e.clientX,clientY:e.clientY,pressure:this._normalizePressure(e.pressure),tiltX:e.tiltX||0,tiltY:e.tiltY||0,twist:e.twist||0,width:e.width||1,height:e.height||1,tangentialPressure:e.tangentialPressure||0,buttons:e.buttons,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,timestamp:e.timeStamp||Date.now()}}_normalizePressure(e){return e==null?.5:Math.max(0,Math.min(1,e))}getPointerInfo(){return{activePointers:this.activePointers.size,isDrawing:this.isDrawing,multiTouch:this.activePointers.size>1}}destroy(){if(!this.isInitialized)return;const e=this.canvas.svg;e.removeEventListener("pointerdown",this._onPointerDown),e.removeEventListener("pointermove",this._onPointerMove),e.removeEventListener("pointerup",this._onPointerUp),e.removeEventListener("pointercancel",this._onPointerCancel),e.removeEventListener("pointerenter",this._onPointerEnter),e.removeEventListener("pointerleave",this._onPointerLeave),document.removeEventListener("keydown",this._onKeyDown),document.removeEventListener("keyup",this._onKeyUp),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("contextmenu",this._onContextMenu),this.activePointers.clear(),this.isDrawing=!1,this.isInitialized=!1}}class ly{constructor(e){this.canvas=e,this.tools=new Map,this.activeTool=null,this.previousTool=null,this.isDestroyed=!1}registerTool(e,t){return this.isDestroyed?(console.warn("Cannot register tool on destroyed ToolManager"),!1):!e||typeof e!="string"?(console.error("Tool name must be a non-empty string"),!1):!t||typeof t.onPointerDown!="function"?(console.error("Tool must implement required methods"),!1):this.canvas.config.enabledTools.includes(e)?(t.name=e,t.canvas=this.canvas,this.tools.set(e,t),!0):(console.warn(`Tool '${e}' is not enabled in canvas configuration`),!1)}unregisterTool(e){const t=this.tools.get(e);return t?(this.activeTool===t&&this.setActiveTool(null),this.tools.delete(e),!0):!1}setActiveTool(e){var r,i;if(this.activeTool){try{this.activeTool.onDeactivate()}catch(s){console.error("Error deactivating tool:",s)}this.previousTool=this.activeTool}if(!e)return this.activeTool=null,this.canvas.emit("toolChanged",{name:null,tool:null,previous:(r=this.previousTool)==null?void 0:r.name}),!0;const t=this.tools.get(e);if(!t)return console.error(`Tool '${e}' not found`),!1;this.activeTool=t;try{this.activeTool.onActivate()}catch(s){return console.error("Error activating tool:",s),this.activeTool=null,!1}if(this.canvas.cursor&&this.activeTool.getCursor){const s=this.activeTool.getCursor();this.canvas.cursor.setShape(s)}return this.canvas.cursor&&this.activeTool.config&&this.canvas.cursor.updateFromToolConfig(this.activeTool.config),this.canvas.emit("toolChanged",{name:e,tool:t,previous:(i=this.previousTool)==null?void 0:i.name}),!0}getActiveTool(){return this.activeTool}getTool(e){return this.tools.get(e)}getToolNames(){return Array.from(this.tools.keys())}getAllTools(){return new Map(this.tools)}getAllToolMetadata(){return Array.from(this.tools.entries()).map(([e,t])=>({name:e,displayName:t.displayName||e,description:t.description||"",shortcut:t.shortcut||"",category:t.category||"general",icon:t.icon||"tool"}))}switchToPreviousTool(){return this.previousTool?this.setActiveTool(this.previousTool.name):!1}async withTemporaryTool(e,t){var i;const r=(i=this.activeTool)==null?void 0:i.name;if(!this.setActiveTool(e))throw new Error(`Failed to activate temporary tool: ${e}`);try{return await t(this.activeTool)}finally{r&&this.setActiveTool(r)}}updateToolConfig(e,t){const r=this.tools.get(e);return r?r.updateConfig?(r.updateConfig(t),this.activeTool===r&&this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(r.config),!0):(console.warn(`Tool '${e}' does not support configuration updates`),!1):(console.error(`Tool '${e}' not found`),!1)}getToolConfig(e){const t=this.tools.get(e);return t?t.config||{}:null}hasTool(e){return this.tools.has(e)}isToolEnabled(e){return this.canvas.config.enabledTools.includes(e)}getToolCapabilities(e){const t=this.tools.get(e);return t?{name:t.name,displayName:t.displayName,description:t.description,shortcut:t.shortcut,category:t.category,supportsKeyboardShortcuts:typeof t.onKeyboardShortcut=="function",supportsPressure:t.supportsPressure||!1,supportsMultiTouch:t.supportsMultiTouch||!1,configurable:typeof t.updateConfig=="function",hasHelp:typeof t.getHelpText=="function"}:null}handleKeyboardShortcut(e,t){for(const[r,i]of this.tools)if(i.shortcut&&i.shortcut.toLowerCase()===e.toLowerCase())return this.setActiveTool(r),!0;return this.activeTool&&this.activeTool.onKeyboardShortcut?this.activeTool.onKeyboardShortcut(e,t):!1}getHelpText(e=null){if(e){const r=this.tools.get(e);return r&&r.getHelpText?r.getHelpText():`No help available for tool: ${e}`}const t={};for(const[r,i]of this.tools)i.getHelpText&&(t[r]=i.getHelpText());return t}getState(){var e,t;return{activeToolName:((e=this.activeTool)==null?void 0:e.name)||null,previousToolName:((t=this.previousTool)==null?void 0:t.name)||null,registeredTools:this.getToolNames(),enabledTools:this.canvas.config.enabledTools,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed){if(this.activeTool)try{this.activeTool.onDeactivate()}catch(e){console.error("Error deactivating tool during destroy:",e)}for(const[e,t]of this.tools)if(t.destroy)try{t.destroy()}catch(r){console.error(`Error destroying tool '${e}':`,r)}this.tools.clear(),this.activeTool=null,this.previousTool=null,this.canvas=null,this.isDestroyed=!0}}}class Di{constructor(e=0,t=0,r=0,i=0){this.x=e,this.y=t,this.width=r,this.height=i}set(e,t,r,i){this.x=e,this.y=t,this.width=r,this.height=i}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}get centerX(){return this.x+this.width/2}get centerY(){return this.y+this.height/2}get center(){return{x:this.centerX,y:this.centerY}}containsPoint(e,t,r=0){return e>=this.left-r&&e<=this.right+r&&t>=this.top-r&&t<=this.bottom+r}intersects(e){return!(this.right<e.left||e.right<this.left||this.bottom<e.top||e.bottom<this.top)}contains(e){return this.left<=e.left&&this.right>=e.right&&this.top<=e.top&&this.bottom>=e.bottom}expandToIncludePoint(e,t){if(this.width===0&&this.height===0)this.x=e,this.y=t,this.width=0,this.height=0;else{const r=Math.min(this.left,e),i=Math.min(this.top,t),s=Math.max(this.right,e),a=Math.max(this.bottom,t);this.x=r,this.y=i,this.width=s-r,this.height=a-i}}expandToIncludeBox(e){if(!(e.width===0&&e.height===0))if(this.width===0&&this.height===0)this.set(e.x,e.y,e.width,e.height);else{const t=Math.min(this.left,e.left),r=Math.min(this.top,e.top),i=Math.max(this.right,e.right),s=Math.max(this.bottom,e.bottom);this.x=t,this.y=r,this.width=i-t,this.height=s-r}}getIntersection(e){if(!this.intersects(e))return null;const t=Math.max(this.left,e.left),r=Math.max(this.top,e.top),i=Math.min(this.right,e.right),s=Math.min(this.bottom,e.bottom);return new Di(t,r,i-t,s-r)}getUnion(e){if(this.width===0&&this.height===0)return e.clone();if(e.width===0&&e.height===0)return this.clone();const t=Math.min(this.left,e.left),r=Math.min(this.top,e.top),i=Math.max(this.right,e.right),s=Math.max(this.bottom,e.bottom);return new Di(t,r,i-t,s-r)}inflate(e){this.x-=e,this.y-=e,this.width+=e*2,this.height+=e*2,this.width=Math.max(0,this.width),this.height=Math.max(0,this.height)}move(e,t){this.x+=e,this.y+=t}scale(e,t=this.centerX,r=this.centerY){const i=this.width*e,s=this.height*e;this.x=t-(t-this.x)*e,this.y=r-(r-this.y)*e,this.width=i,this.height=s}getArea(){return this.width*this.height}getPerimeter(){return 2*(this.width+this.height)}isEmpty(){return this.width<=0||this.height<=0}isValid(){return!isNaN(this.x)&&!isNaN(this.y)&&!isNaN(this.width)&&!isNaN(this.height)&&this.width>=0&&this.height>=0}distanceToPoint(e,t){if(this.containsPoint(e,t))return 0;const r=Math.max(0,Math.max(this.left-e,e-this.right)),i=Math.max(0,Math.max(this.top-t,t-this.bottom));return Math.sqrt(r*r+i*i)}getCorners(){return[{x:this.left,y:this.top},{x:this.right,y:this.top},{x:this.right,y:this.bottom},{x:this.left,y:this.bottom}]}clone(){return new Di(this.x,this.y,this.width,this.height)}toString(){return`BoundingBox(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toJSON(){return{x:this.x,y:this.y,width:this.width,height:this.height}}static fromJSON(e){return new Di(e.x,e.y,e.width,e.height)}static fromPoints(e){if(e.length===0)return new Di;let t=1/0,r=1/0,i=-1/0,s=-1/0;return e.forEach(a=>{t=Math.min(t,a.x),r=Math.min(r,a.y),i=Math.max(i,a.x),s=Math.max(s,a.y)}),new Di(t,r,i-t,s-r)}}class gn{constructor(e={}){this.id=e.id||this._generateId(),this.tool=e.tool||"pencil",this.strokeWidth=e.strokeWidth||5,this.strokeColor=e.strokeColor||"#000000",this.strokeOpacity=e.strokeOpacity||1,this.points=[],this.isFinished=!1,this.isSelected=!1,this.boundingBox=new Di,this._createElement(),e.x!==void 0&&e.y!==void 0&&this.addPoint({x:e.x,y:e.y,pressure:.5,width:this.strokeWidth,timestamp:Date.now()})}_createElement(){this.jsvgPath=new Ni,this.element=this.jsvgPath.svgObject,this.jsvgPath.setFillColor("none"),this.jsvgPath.setStrokeColor(this.strokeColor),this.jsvgPath.setStrokeWidth(this.strokeWidth),this.element.setAttribute("stroke-opacity",this.strokeOpacity),this.element.setAttribute("stroke-linecap","round"),this.element.setAttribute("stroke-linejoin","round"),this.element.setAttribute("data-stroke-id",this.id),this.element.setAttribute("data-tool",this.tool)}addPoint(e){const t={x:e.x,y:e.y,pressure:e.pressure||.5,width:e.width||this.strokeWidth,timestamp:e.timestamp||Date.now()};this.points.push(t),this._updatePath(),this._updateBoundingBox()}_updatePath(){if(this.points.length===0){this.jsvgPath.clearPoints();return}if(this.jsvgPath.clearPoints(),this.points.length===1){const e=this.points[0];this.jsvgPath.addPoint(e.x,e.y),this.jsvgPath.addPoint(e.x+.1,e.y)}else this._generateSmoothPath();this.jsvgPath.updatePath()}_generateSmoothPath(){if(this.points.length<2)return"";if(this.jsvgPath.addPoint(this.points[0].x,this.points[0].y),this.points.length===2){this.jsvgPath.addPoint(this.points[1].x,this.points[1].y);return}for(let e=1;e<this.points.length-1;e++){const t=this.points[e-1],r=this.points[e],i=this.points[e+1];r.x+(i.x-t.x)*.25,r.y+(i.y-t.y)*.25,i.x-(i.x-r.x)*.25,i.y-(i.y-r.y)*.25,this.jsvgPath.addPoint(i.x,i.y)}}_updateBoundingBox(){if(this.points.length===0)return;let e=1/0,t=1/0,r=-1/0,i=-1/0;this.points.forEach(s=>{const a=s.width/2;e=Math.min(e,s.x-a),t=Math.min(t,s.y-a),r=Math.max(r,s.x+a),i=Math.max(i,s.y+a)}),this.boundingBox.set(e,t,r-e,i-t)}finish(){this.isFinished=!0,this.element.setAttribute("data-finished","true")}setSelected(e){this.isSelected=e,e?(this.element.setAttribute("stroke-dasharray","5,5"),this.element.setAttribute("data-selected","true")):(this.element.removeAttribute("stroke-dasharray"),this.element.removeAttribute("data-selected"))}updateConfig(e){e.strokeColor!==void 0&&(this.strokeColor=e.strokeColor,this.jsvgPath.setStrokeColor(this.strokeColor)),e.strokeWidth!==void 0&&(this.strokeWidth=e.strokeWidth,this.jsvgPath.setStrokeWidth(this.strokeWidth)),e.strokeOpacity!==void 0&&(this.strokeOpacity=e.strokeOpacity,this.element.setAttribute("stroke-opacity",this.strokeOpacity))}isNearPoint(e,t,r=10){if(!this.boundingBox.containsPoint(e,t,r))return!1;for(let i=1;i<this.points.length;i++){const s=this.points[i-1],a=this.points[i];if(this._distanceToLineSegment(e,t,s.x,s.y,a.x,a.y)<=r)return!0}return!1}_distanceToLineSegment(e,t,r,i,s,a){const o=s-r,l=a-i,u=Math.sqrt(o*o+l*l);if(u===0)return Math.sqrt((e-r)*(e-r)+(t-i)*(t-i));const c=Math.max(0,Math.min(1,((e-r)*o+(t-i)*l)/(u*u))),h=r+c*o,f=i+c*l;return Math.sqrt((e-h)*(e-h)+(t-f)*(t-f))}getLength(){let e=0;for(let t=1;t<this.points.length;t++){const r=this.points[t-1],i=this.points[t],s=i.x-r.x,a=i.y-r.y;e+=Math.sqrt(s*s+a*a)}return e}toJSON(){return{id:this.id,tool:this.tool,strokeWidth:this.strokeWidth,strokeColor:this.strokeColor,strokeOpacity:this.strokeOpacity,points:this.points,isFinished:this.isFinished,boundingBox:this.boundingBox.toJSON()}}static fromJSON(e){const t=new gn({id:e.id,tool:e.tool,strokeWidth:e.strokeWidth,strokeColor:e.strokeColor,strokeOpacity:e.strokeOpacity});return e.points.forEach(r=>t.addPoint(r)),e.isFinished&&t.finish(),t}_generateId(){return`stroke_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}clone(){return gn.fromJSON(this.toJSON())}getPointCount(){return this.points.length}getBoundingBox(){return this.boundingBox}move(e,t){this.points.forEach(r=>{r.x+=e,r.y+=t}),this._updatePath(),this._updateBoundingBox()}scale(e,t=0,r=0){this.points.forEach(i=>{i.x=t+(i.x-t)*e,i.y=r+(i.y-r)*e,i.width*=e}),this.strokeWidth*=e,this.jsvgPath.setStrokeWidth(this.strokeWidth),this._updatePath(),this._updateBoundingBox()}}class Yo{constructor(e,t={}){this.canvas=e,this.name="",this.displayName="",this.description="",this.icon="",this.shortcut="",this.category="general",this.isActive=!1,this.isDrawing=!1,this.currentStroke=null,this.config={strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,...t},this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this)}onActivate(){this.isActive=!0,this.canvas.emit("toolActivated",{tool:this,name:this.name})}onDeactivate(){this.isActive=!1,this.isDrawing&&this.onCancel(),this.canvas.emit("toolDeactivated",{tool:this,name:this.name})}onPointerDown(e){throw new Error("Tool.onPointerDown() must be implemented by subclass")}onPointerMove(e){throw new Error("Tool.onPointerMove() must be implemented by subclass")}onPointerUp(e){throw new Error("Tool.onPointerUp() must be implemented by subclass")}onCancel(){this.isDrawing&&(this.isDrawing=!1,this.currentStroke&&this.currentStroke.id&&this.canvas.removeStroke(this.currentStroke.id),this.currentStroke=null)}updateConfig(e){this.config={...this.config,...e},this.onConfigUpdate()}onConfigUpdate(){}getConfig(){return{...this.config}}isDrawingActive(){return this.isDrawing}getCursor(){return this.name}getProperties(){return{name:this.name,displayName:this.displayName,description:this.description,icon:this.icon,shortcut:this.shortcut,category:this.category,config:this.getConfig()}}createStroke(e,t){const r={x:e,y:t,strokeWidth:this.config.strokeWidth,strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity,tool:this.name};return new gn(r)}calculateStrokeWidth(e=.5){const t=this.config.strokeWidth,r=Math.max(1,t*.3),i=t*1.5;return r+(i-r)*e}onKeyboardShortcut(e,t){return!1}getHelpText(){return`${this.displayName}: ${this.description}`}canUse(){return!this.canvas.isDestroyed&&this.isActive}}class cy extends Yo{constructor(e,t={}){super(e,{strokeWidth:5,strokeColor:"#000000",strokeOpacity:1,smoothing:.5,pressureSensitive:!0,...t}),this.displayName="Pencil",this.description="Draw freehand strokes",this.icon="pencil",this.shortcut="P",this.category="drawing",this.points=[],this.lastPoint=null,this.minDistance=2}onPointerDown(e){this.canUse()&&(this.isDrawing=!0,this.points=[],this.lastPoint={x:e.x,y:e.y},this.currentStroke=new gn({x:e.x,y:e.y,strokeWidth:this.calculateStrokeWidth(e.pressure),strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity,tool:this.name}),this.addPoint(e.x,e.y,e.pressure),this.canvas.addStroke(this.currentStroke),this.canvas.emit("strokeStarted",{stroke:this.currentStroke,tool:this.name,point:{x:e.x,y:e.y,pressure:e.pressure}}))}onPointerMove(e){if(!(!this.isDrawing||!this.currentStroke)){if(e.coalescedEvents&&e.coalescedEvents.length>0){const r=e.coalescedEvents.slice(0,5);for(const i of r)this._addPointIfNeeded(i.x,i.y,i.pressure)}else this._addPointIfNeeded(e.x,e.y,e.pressure);this.canvas.emit("strokeContinued",{stroke:this.currentStroke,tool:this.name,point:{x:e.x,y:e.y,pressure:e.pressure}})}}onPointerUp(e){!this.isDrawing||!this.currentStroke||(this.addPoint(e.x,e.y,e.pressure),this.currentStroke.finish(),this.canvas.emit("strokeCompleted",{stroke:this.currentStroke,tool:this.name,totalPoints:this.points.length}),this.isDrawing=!1,this.currentStroke=null,this.points=[],this.lastPoint=null)}onCancel(){this.isDrawing&&this.currentStroke&&(this.canvas.removeStroke(this.currentStroke.id),this.canvas.emit("strokeCancelled",{stroke:this.currentStroke,tool:this.name})),super.onCancel(),this.points=[],this.lastPoint=null}addPoint(e,t,r=.5){const i={x:e,y:t,pressure:r,width:this.calculateStrokeWidth(r),timestamp:Date.now()};this.points.push(i),this.currentStroke&&this.currentStroke.addPoint(i)}_addPointIfNeeded(e,t,r=.5){if(!this.lastPoint){this.addPoint(e,t,r),this.lastPoint={x:e,y:t};return}const i=this.getDistance(this.lastPoint,{x:e,y:t});i>=this.minDistance&&(i>8?this._interpolatePoints(this.lastPoint,{x:e,y:t,pressure:r}):this.addPoint(e,t,r),this.lastPoint={x:e,y:t})}_interpolatePoints(e,t){const r=this.getDistance(e,t),i=Math.ceil(r/3),a=Math.min(i,10);for(let o=1;o<=a;o++){const l=o/a,u=e.x+(t.x-e.x)*l,c=e.y+(t.y-e.y)*l,h=e.pressure?e.pressure+(t.pressure-e.pressure)*l:t.pressure;this.addPoint(u,c,h)}}getDistance(e,t){const r=t.x-e.x,i=t.y-e.y;return Math.sqrt(r*r+i*i)}onConfigUpdate(){this.minDistance=Math.max(1,this.config.strokeWidth*.2),this.isDrawing&&this.currentStroke&&this.currentStroke.updateConfig({strokeColor:this.config.strokeColor,strokeOpacity:this.config.strokeOpacity}),this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(this.config)}calculateStrokeWidth(e=.5){return this.config.pressureSensitive?super.calculateStrokeWidth(e):this.config.strokeWidth}getSmoothPath(e){if(e.length<2)return e;const t=[],r=this.config.smoothing;t.push(e[0]);for(let i=1;i<e.length-1;i++){const s=e[i-1],a=e[i],o=e[i+1],l={x:a.x+r*((s.x+o.x)/2-a.x),y:a.y+r*((s.y+o.y)/2-a.y),pressure:a.pressure,width:a.width,timestamp:a.timestamp};t.push(l)}return e.length>1&&t.push(e[e.length-1]),t}onKeyboardShortcut(e,t){switch(e){case"[":return this.updateConfig({strokeWidth:Math.max(1,this.config.strokeWidth-1)}),this.canvas.toolManager.updateToolConfig(this.name,this.config),!0;case"]":return this.updateConfig({strokeWidth:Math.min(50,this.config.strokeWidth+1)}),this.canvas.toolManager.updateToolConfig(this.name,this.config),!0;default:return super.onKeyboardShortcut(e,t)}}getHelpText(){return`${super.getHelpText()}
94
94
  Shortcuts: [ ] to adjust brush size`}}class hy extends Yo{constructor(e,t={}){super(e,{size:12,hardness:.8,mode:"radius",...t}),this.displayName="Eraser",this.description="Erase strokes (M to toggle mode)",this.icon="eraser",this.shortcut="E",this.category="editing",this.isErasing=!1,this.erasedPoints=new Set}onPointerDown(e){this.canUse()&&(this.isErasing=!0,this._eraseAtPoint(e.x,e.y),this.canvas.emit("eraseStarted",{tool:this.name,point:{x:e.x,y:e.y}}))}onPointerMove(e){this.isErasing&&this._eraseAtPoint(e.x,e.y)}onPointerUp(e){this.isErasing&&(this.isErasing=!1,this.canvas.emit("eraseCompleted",{tool:this.name}))}onCancel(){this.isErasing=!1,super.onCancel()}_eraseAtPoint(e,t){this.config.mode==="stroke"?this._eraseWholeStrokes(e,t):this._eraseInRadius(e,t)}_eraseWholeStrokes(e,t){const r=this.config.size||20,i=[];for(const[s,a]of this.canvas.strokes)a.isNearPoint(e,t,r)&&i.push(s);i.forEach(s=>{this.canvas.removeStroke(s)})}_eraseInRadius(e,t){const r=this.config.size||20,i=r*r,s=[];for(const[a,o]of this.canvas.strokes){const l=o.getBoundingBox();if(this._circleIntersectsRect(e,t,r,l)){const u=[];for(let c=0;c<o.points.length;c++){const h=o.points[c],f=h.x-e,d=h.y-t;f*f+d*d<=i&&u.push(c)}u.length>0&&s.push({id:a,stroke:o,pointsToRemove:u})}}s.forEach(({id:a,stroke:o,pointsToRemove:l})=>{l.length>=o.points.length*.8?this.canvas.removeStroke(a):this._splitStrokeAtErasedPoints(o,l)})}_circleIntersectsRect(e,t,r,i){const s=Math.max(i.left,Math.min(e,i.right)),a=Math.max(i.top,Math.min(t,i.bottom)),o=e-s,l=t-a;return o*o+l*l<=r*r}_splitStrokeAtErasedPoints(e,t){if(t.length===0)return;t.sort((s,a)=>s-a);const r=[];let i=0;for(let s=0;s<t.length;s++){const a=t[s];if(a>i){const o=e.points.slice(i,a);o.length>=2&&r.push(o)}i=a+1}if(i<e.points.length){const s=e.points.slice(i);s.length>=2&&r.push(s)}this.canvas.removeStroke(e.id),r.forEach((s,a)=>{const o=new gn({strokeWidth:e.strokeWidth,strokeColor:e.strokeColor,strokeOpacity:e.strokeOpacity,tool:e.tool});s.forEach(l=>{o.addPoint(l)}),o.finish(),this.canvas.addStroke(o)})}getCursor(){return"eraser"}onKeyboardShortcut(e,t){switch(e){case"[":return this.updateConfig({size:Math.max(5,this.config.size-5)}),!0;case"]":return this.updateConfig({size:Math.min(100,this.config.size+5)}),!0;case"m":return this.toggleMode(),!0;default:return super.onKeyboardShortcut(e,t)}}toggleMode(){const e=this.config.mode==="stroke"?"radius":"stroke";this.updateConfig({mode:e}),this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(this.config),this.canvas.emit("eraserModeChanged",{mode:e,description:this._getModeDescription(e)})}_getModeDescription(e){return e==="stroke"?"Whole Stroke Erasing":"Radius Erasing"}onConfigUpdate(){this.canvas.cursor&&this.canvas.cursor.setSize(this.config.size)}getHelpText(){return`${super.getHelpText()}
95
95
  Shortcuts: [ ] to adjust size, M to toggle mode
96
96
  Current mode: ${this._getModeDescription(this.config.mode)}`}getMode(){return this.config.mode}setMode(e){(e==="stroke"||e==="radius")&&(this.updateConfig({mode:e}),this.canvas.cursor&&this.canvas.cursor.updateFromToolConfig(this.config))}}class o9{constructor(e){this.canvas=e,this.selectedElement=null,this.handles=[],this.isResizing=!1,this.resizeData=null,this.handleSize=8,this.handleColor="#007bff",this.handleStrokeColor="#ffffff",this.handleStrokeWidth=1,this.selectionBorderColor="#007bff",this.selectionBorderWidth=2,this.selectionBorder=null,this.selectionBorderPadding={top:8,right:8,bottom:8,left:8},this.minSize=20,this.maxSize=800,this.maintainAspectRatio=!0}selectElement(e){var t;this.clearSelection(),!(!e||!e.classList.contains("omd-item"))&&((t=e==null?void 0:e.dataset)==null?void 0:t.locked)!=="true"&&(this.selectedElement=e,this._createSelectionBorder(),this._createResizeHandles(),this._updateHandlePositions(),e.classList.add("omd-selected"),this.canvas.emit("omdElementSelected",{element:e}))}clearSelection(){this.selectedElement&&(this.selectedElement.classList.remove("omd-selected"),this.selectedElement=null),this._removeSelectionBorder(),this._removeResizeHandles(),this.isResizing=!1,this.resizeData=null,this.canvas.emit("omdElementDeselected")}getHandleAtPoint(e,t){const r=this.handleSize/2+3;for(const i of this.handles){const s=parseFloat(i.element.getAttribute("x"))+this.handleSize/2,a=parseFloat(i.element.getAttribute("y"))+this.handleSize/2;if(Math.hypot(e-s,t-a)<=r)return i}return null}startResize(e,t,r,i=!1){if(!this.selectedElement||!e)return;this.isResizing=!0,this.maintainAspectRatio=i;const s=this.selectedElement.getAttribute("transform")||"translate(0,0)",a=s.match(/translate\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/),o=a?parseFloat(a[1]):0,l=a?parseFloat(a[2]):0,u=s.match(/scale\(\s*([^,)]+)(?:\s*,\s*([^)]+))?\s*\)/),c=u?parseFloat(u[1]):1,h=u?u[2]?parseFloat(u[2]):c:1,f=this._getElementBounds();this.resizeData={handle:e,startX:t,startY:r,originalTransform:s,currentX:o,currentY:l,currentScaleX:c,currentScaleY:h,originalBounds:f,startWidth:f.width*c,startHeight:f.height*h},this.selectedElement.classList.add("omd-resizing")}updateResize(e,t){if(!this.isResizing||!this.resizeData)return;const{handle:r,startX:i,startY:s,originalBounds:a,startWidth:o,startHeight:l}=this.resizeData,u=e-i,c=t-s;let h=o,f=l,d=0,p=0;switch(r.type){case"nw":h=o-u,f=l-c,d=u,p=c;break;case"ne":h=o+u,f=l-c,p=c;break;case"sw":h=o-u,f=l+c,d=u;break;case"se":h=o+u,f=l+c;break;case"n":f=l-c,p=c;break;case"s":f=l+c;break;case"w":h=o-u,d=u;break;case"e":h=o+u;break}if(this.maintainAspectRatio){const g=o/l,b=Math.abs(h-o),w=Math.abs(f-l);b>=w?(f=h/g,r.type.includes("n")&&(p=l-f)):(h=f*g,r.type.includes("w")&&(d=o-h))}h=Math.max(this.minSize,Math.min(this.maxSize,h)),f=Math.max(this.minSize,Math.min(this.maxSize,f));const m=h/a.width,y=f/a.height,v=this.resizeData.currentX+d,S=this.resizeData.currentY+p;this.selectedElement.setAttribute("transform",`translate(${v}, ${S}) scale(${m}, ${y})`),this._updateHandlePositions(),this._updateSelectionBorder()}finishResize(){this.isResizing&&(this.isResizing=!1,this.selectedElement&&this.selectedElement.classList.remove("omd-resizing"),this._updateHandlePositions(),this._updateSelectionBorder(),this.canvas.emit("omdElementResized",{element:this.selectedElement,transform:this.selectedElement.getAttribute("transform")}),this.resizeData=null)}setSelectionStyle({color:e,width:t,dasharray:r,cornerRadius:i,padding:s,paddingX:a,paddingY:o,paddingTop:l,paddingRight:u,paddingBottom:c,paddingLeft:h}={}){e!==void 0&&(this.selectionBorderColor=e),t!==void 0&&(this.selectionBorderWidth=t),r!==void 0&&(this.selectionBorderDasharray=r),i!==void 0&&(this.selectionBorderCornerRadius=i);const f=s??null,d={top:l??o??f??this.selectionBorderPadding.top,right:u??a??f??this.selectionBorderPadding.right,bottom:c??o??f??this.selectionBorderPadding.bottom,left:h??a??f??this.selectionBorderPadding.left};this.selectionBorderPadding=d,this.selectionBorder&&(this.selectionBorder.setAttribute("stroke",this.selectionBorderColor),this.selectionBorder.setAttribute("stroke-width",this.selectionBorderWidth),this.selectionBorder.setAttribute("stroke-dasharray",this.selectionBorderDasharray!==void 0?this.selectionBorderDasharray:"4,2"),this.selectionBorderCornerRadius!==void 0&&(this.selectionBorder.setAttribute("rx",this.selectionBorderCornerRadius),this.selectionBorder.setAttribute("ry",this.selectionBorderCornerRadius)),this._updateSelectionBorder())}setHandleStyle({size:e,color:t,strokeColor:r,strokeWidth:i,cornerRadius:s}={}){e!==void 0&&(this.handleSize=e),t!==void 0&&(this.handleColor=t),r!==void 0&&(this.handleStrokeColor=r),i!==void 0&&(this.handleStrokeWidth=i),s!==void 0&&(this.handleCornerRadius=s);const a=this.handleCornerRadius!==void 0?this.handleCornerRadius:1;this.handles.forEach(o=>{o.element.setAttribute("width",this.handleSize),o.element.setAttribute("height",this.handleSize),o.element.setAttribute("fill",this.handleColor),o.element.setAttribute("stroke",this.handleStrokeColor),o.element.setAttribute("stroke-width",this.handleStrokeWidth),o.element.setAttribute("rx",a)}),this.handles.length>0&&this._updateHandlePositions()}updateIfSelected(e){this.selectedElement&&this.selectedElement===e&&(this._updateHandlePositions(),this._updateSelectionBorder())}getCursorForHandle(e){return{nw:"nw-resize",n:"n-resize",ne:"ne-resize",e:"e-resize",se:"se-resize",s:"s-resize",sw:"sw-resize",w:"w-resize"}[e]||"default"}_createSelectionBorder(){this.selectedElement&&(this.selectionBorder=document.createElementNS("http://www.w3.org/2000/svg","rect"),this.selectionBorder.setAttribute("fill","none"),this.selectionBorder.setAttribute("stroke",this.selectionBorderColor),this.selectionBorder.setAttribute("stroke-width",this.selectionBorderWidth),this.selectionBorder.setAttribute("stroke-dasharray",this.selectionBorderDasharray!==void 0?this.selectionBorderDasharray:"4,2"),this.selectionBorderCornerRadius!==void 0&&(this.selectionBorder.setAttribute("rx",this.selectionBorderCornerRadius),this.selectionBorder.setAttribute("ry",this.selectionBorderCornerRadius)),this.selectionBorder.style.pointerEvents="none",this.selectionBorder.classList.add("omd-selection-border"),this.canvas.uiLayer.appendChild(this.selectionBorder),this._updateSelectionBorder())}_updateSelectionBorder(){if(!this.selectionBorder||!this.selectedElement)return;const e=this._getTransformedBounds(),t=this.selectionBorderPadding;this.selectionBorder.setAttribute("x",e.x-t.left),this.selectionBorder.setAttribute("y",e.y-t.top),this.selectionBorder.setAttribute("width",e.width+t.left+t.right),this.selectionBorder.setAttribute("height",e.height+t.top+t.bottom)}_removeSelectionBorder(){this.selectionBorder&&(this.selectionBorder.remove(),this.selectionBorder=null)}_createResizeHandles(){if(!this.selectedElement)return;[{type:"nw",pos:"top-left"},{type:"ne",pos:"top-right"},{type:"se",pos:"bottom-right"},{type:"sw",pos:"bottom-left"}].forEach(t=>{const r=this._createHandle(t.type,t.pos);this.handles.push(r),this.canvas.uiLayer.appendChild(r.element)})}_createHandle(e,t){const r=document.createElementNS("http://www.w3.org/2000/svg","rect"),i=this.handleCornerRadius!==void 0?this.handleCornerRadius:1;return r.setAttribute("width",this.handleSize),r.setAttribute("height",this.handleSize),r.setAttribute("fill",this.handleColor),r.setAttribute("stroke",this.handleStrokeColor),r.setAttribute("stroke-width",this.handleStrokeWidth),r.setAttribute("rx",i),r.style.cursor=this.getCursorForHandle(e),r.classList.add("resize-handle",`resize-handle-${e}`),r.addEventListener("mouseenter",()=>{r.setAttribute("fill","#0056b3")}),r.addEventListener("mouseleave",()=>{r.setAttribute("fill",this.handleColor)}),{element:r,type:e,position:t}}_updateHandlePositions(){if(!this.selectedElement||this.handles.length===0)return;const e=this._getTransformedBounds(),t=this.handleSize/2,r={nw:{x:e.x-t,y:e.y-t},n:{x:e.x+e.width/2-t,y:e.y-t},ne:{x:e.x+e.width-t,y:e.y-t},e:{x:e.x+e.width-t,y:e.y+e.height/2-t},se:{x:e.x+e.width-t,y:e.y+e.height-t},s:{x:e.x+e.width/2-t,y:e.y+e.height-t},sw:{x:e.x-t,y:e.y+e.height-t},w:{x:e.x-t,y:e.y+e.height/2-t}};this.handles.forEach(i=>{const s=r[i.type];s&&(i.element.setAttribute("x",s.x),i.element.setAttribute("y",s.y))})}_removeResizeHandles(){this.handles.forEach(e=>{e.element.remove()}),this.handles=[]}_getElementBounds(){if(!this.selectedElement)return{x:0,y:0,width:0,height:0};try{const e=this.selectedElement.firstElementChild;if(!e)return this.selectedElement.getBBox();const t=e.querySelectorAll("clipPath");if(t.length>0){let r=0,i=null;for(const s of t){const a=s.querySelector("rect");if(a){const o=parseFloat(a.getAttribute("width"))||0,l=parseFloat(a.getAttribute("height"))||0,u=parseFloat(a.getAttribute("x"))||0,c=parseFloat(a.getAttribute("y"))||0,h=o*l;if(h>r){r=h;const f=e.firstElementChild;let d=0,p=0;if(f){const m=f.getAttribute("transform");if(m){const y=m.match(/translate\(\s*([^,]+)(?:,\s*([^)]+))?\s*\)/);y&&(d=parseFloat(y[1])||0,p=parseFloat(y[2])||0)}}i={x:u+d,y:c+p,width:o,height:l}}}}if(i)return i}return e.getBBox()}catch{return{x:0,y:0,width:100,height:100}}}_getTransformedBounds(){if(!this.selectedElement)return{x:0,y:0,width:0,height:0};const e=this.selectedElement.getAttribute("transform")||"",t=e.match(/translate\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/),r=e.match(/scale\(\s*([^,)]+)(?:\s*,\s*([^)]+))?\s*\)/),i=t?parseFloat(t[1]):0,s=t?parseFloat(t[2]):0,a=r?parseFloat(r[1]):1,o=r?r[2]?parseFloat(r[2]):a:1,l=this._getElementBounds();return{x:i+l.x*a,y:s+l.y*o,width:l.width*a,height:l.height*o}}}const u9=10,l9="#007bff",c9=.3;class h9 extends Yo{constructor(e,t={}){super(e,{selectionColor:l9,selectionOpacity:c9,...t}),this.displayName="Pointer",this.description="Select and interact with components",this.icon="pointer",this.shortcut="V",this.category="navigation",this.isSelecting=!1,this.selectionBox=null,this.startPoint=null,this.selectedSegments=new Map,this.isDraggingOMD=!1,this.draggedOMDElement=null,this.selectedOMDElements=new Set,this.isDraggingStrokes=!1,this.dragStartPoint=null,this.potentialDeselect=null,this.hasSeparatedForDrag=!1,this.selectionBoundsPadding={top:t.selectionBoundsPaddingTop??t.selectionBoundsPaddingY??t.selectionBoundsPadding??14,right:t.selectionBoundsPaddingRight??t.selectionBoundsPaddingX??t.selectionBoundsPadding??14,bottom:t.selectionBoundsPaddingBottom??t.selectionBoundsPaddingY??t.selectionBoundsPadding??14,left:t.selectionBoundsPaddingLeft??t.selectionBoundsPaddingX??t.selectionBoundsPadding??14},this.resizeHandleManager=new o9(e),e&&(e.resizeHandleManager=this.resizeHandleManager)}onPointerDown(e){var s;if(!this.canUse())return;const t=this.resizeHandleManager.getHandleAtPoint(e.x,e.y);if(t){this.resizeHandleManager.startResize(t,e.x,e.y,e.shiftKey),this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);return}const r=this._findSegmentAtPoint(e.x,e.y);let i=this._findOMDElementAtPoint(e.x,e.y);if(((s=i==null?void 0:i.dataset)==null?void 0:s.locked)==="true"&&(i=null),r)if(this._isSegmentSelected(r)){this.isDraggingStrokes=!0,this.hasSeparatedForDrag=!1,this.dragStartPoint={x:e.x,y:e.y},this.potentialDeselect=r,this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);return}else e.shiftKey||(this.resizeHandleManager.clearSelection(),this.selectedOMDElements.clear()),this._handleSegmentClick(r,e.shiftKey),this.isDraggingStrokes=!0,this.hasSeparatedForDrag=!1,this.dragStartPoint={x:e.x,y:e.y},this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);else if(i){if(this.selectedOMDElements.has(i)){this.isDraggingOMD=!0,this.draggedOMDElement=i,this.startPoint={x:e.x,y:e.y},this.selectedOMDElements.size===1&&this.resizeHandleManager.selectElement(i),this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);return}e.shiftKey||(this.selectedSegments.clear(),this._clearSelectionVisuals(),this.selectedOMDElements.clear(),this.resizeHandleManager.clearSelection()),this.selectedOMDElements.add(i),this.resizeHandleManager.selectElement(i),this.isDraggingOMD=!0,this.draggedOMDElement=i,this.startPoint={x:e.x,y:e.y},this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);return}else{const a=this._getSelectionBounds();if(a&&e.x>=a.x&&e.x<=a.x+a.width&&e.y>=a.y&&e.y<=a.y+a.height){this.isDraggingStrokes=!0,this.isDraggingOMD=!0,this.hasSeparatedForDrag=!1,this.dragStartPoint={x:e.x,y:e.y},this.startPoint={x:e.x,y:e.y},this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0);return}this.resizeHandleManager.clearSelection(),this.selectedOMDElements.clear(),this._startBoxSelection(e.x,e.y,e.shiftKey),this.startPoint={x:e.x,y:e.y},this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!0)}}onPointerMove(e){if(this.resizeHandleManager.isResizing){this.resizeHandleManager.updateResize(e.x,e.y);return}let t=!1;if(this.isDraggingOMD&&(this._dragOMDElements(e.x,e.y),t=!0),this.isDraggingStrokes&&this.dragStartPoint){const r=e.x-this.dragStartPoint.x,i=e.y-this.dragStartPoint.y;if(r!==0||i!==0){this.potentialDeselect=null,this.hasSeparatedForDrag||(this._separateSelectedParts(),this.hasSeparatedForDrag=!0);const s=new Set;for(const[a,o]of this.selectedSegments){const l=this.canvas.strokes.get(a);l&&(l.move(r,i),s.add(a))}this.dragStartPoint={x:e.x,y:e.y},this._updateSegmentSelectionVisuals(),this.canvas.emit("strokesMoved",{dx:r,dy:i,strokeIds:Array.from(s)})}t=!0}t||!this.isSelecting||!this.selectionBox||(this._updateSelectionBox(e.x,e.y),this._updateBoxSelection())}onPointerUp(e){if(this.resizeHandleManager.isResizing){this.resizeHandleManager.finishResize(),this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1);return}if(this.isDraggingOMD){this.isDraggingOMD=!1,this.draggedOMDElement=null,this.startPoint=null,this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1);return}if(this.isDraggingStrokes){this.potentialDeselect&&(this._handleSegmentClick(this.potentialDeselect,e.shiftKey),this.potentialDeselect=null),this.isDraggingStrokes=!1,this.dragStartPoint=null,this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1);return}this.isSelecting&&this._finishBoxSelection(),this.isSelecting=!1,this._removeSelectionBox(),this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1)}onCancel(){this.isSelecting=!1,this._removeSelectionBox(),this.clearSelection(),this.isDraggingOMD=!1,this.draggedOMDElement=null,this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1),super.onCancel()}onDeactivate(){this.isActive=!1,this.isDraggingOMD=!1,this.draggedOMDElement=null,this.isSelecting=!1,this.startPoint=null,this.canvas.eventManager&&(this.canvas.eventManager.isDrawing=!1),this.clearSelection(),super.onDeactivate()}onActivate(){this.isActive=!0,this.isDraggingOMD=!1,this.draggedOMDElement=null,this.isSelecting=!1,this.startPoint=null,this.canvas.cursor&&(this.canvas.cursor.show(),this.canvas.cursor.setShape("pointer")),this.clearSelection(),super.onActivate()}onKeyboardShortcut(e,t){return(t.ctrlKey||t.metaKey)&&e==="a"?(this._selectAllSegments(),!0):e==="delete"||e==="backspace"?(this._deleteSelectedSegments(),!0):!1}getCursor(){var e,t;return this.resizeHandleManager.isResizing?this.resizeHandleManager.getCursorForHandle(((t=(e=this.resizeHandleManager.resizeData)==null?void 0:e.handle)==null?void 0:t.type)||"se"):"pointer"}canUse(){return super.canUse()}clearSelection(){this.selectedSegments.clear(),this.selectedOMDElements.clear(),this.resizeHandleManager.clearSelection(),this._removeSelectionBox(),this._clearSelectionVisuals(),this.isSelecting=!1,this.startPoint=null,this.canvas.emit("selectionChanged",{selected:[]})}_clearSelectionVisuals(){const e=this.canvas.uiLayer.querySelector(".segment-selection-layer");if(e)for(;e.firstChild;)e.removeChild(e.firstChild);this.canvas.uiLayer.querySelectorAll('[stroke="'+this.config.selectionColor+'"]').forEach(r=>{r.parentNode&&r.parentNode.removeChild(r)})}_handleSegmentClick({strokeId:e,segmentIndex:t},r){const i=this.selectedSegments.get(e)||new Set;i.has(t)?(i.delete(t),i.size===0&&this.selectedSegments.delete(e)):(r||this.selectedSegments.clear(),this.selectedSegments.has(e)||this.selectedSegments.set(e,new Set),this.selectedSegments.get(e).add(t)),this._updateSegmentSelectionVisuals(),this.canvas.emit("selectionChanged",{selected:this._getSelectedSegmentsAsArray()})}_startBoxSelection(e,t,r){r||this.clearSelection(),this.isSelecting=!0,this._createSelectionBox(e,t)}_finishBoxSelection(){this._updateSegmentSelectionVisuals(),this.canvas.emit("selectionChanged",{selected:this._getSelectedSegmentsAsArray()})}_getSelectedSegmentsAsArray(){const e=[];for(const[t,r]of this.selectedSegments.entries())for(const i of r)e.push({strokeId:t,segmentIndex:i});return e}_isSegmentSelected({strokeId:e,segmentIndex:t}){const r=this.selectedSegments.get(e);return r?r.has(t):!1}_getSelectionBounds(){let e=1/0,t=1/0,r=-1/0,i=-1/0,s=!1;if(this.selectedSegments.size>0)for(const[o,l]of this.selectedSegments.entries()){const u=this.canvas.strokes.get(o);if(!(!u||!u.points))for(const c of l){if(c>=u.points.length-1)continue;const h=u.points[c],f=u.points[c+1];e=Math.min(e,h.x,f.x),t=Math.min(t,h.y,f.y),r=Math.max(r,h.x,f.x),i=Math.max(i,h.y,f.y),s=!0}}if(this.selectedOMDElements.size>0)for(const o of this.selectedOMDElements){const l=this._getOMDElementBounds(o);l&&(e=Math.min(e,l.x),t=Math.min(t,l.y),r=Math.max(r,l.x+l.width),i=Math.max(i,l.y+l.height),s=!0)}if(!s)return null;const a=this.selectionBoundsPadding;return{x:e-a.left,y:t-a.top,width:r+a.right-(e-a.left),height:i+a.bottom-(t-a.top)}}_dragOMDElements(e,t){if(!this.startPoint)return;const r=e-this.startPoint.x,i=t-this.startPoint.y;if(!(r===0&&i===0)){for(const s of this.selectedOMDElements)this._moveOMDElement(s,r,i);if(this.startPoint={x:e,y:t},this.selectedOMDElements.size===1){const s=this.selectedOMDElements.values().next().value;this.resizeHandleManager.updateIfSelected(s)}this._updateSegmentSelectionVisuals()}}_moveOMDElement(e,t,r){const i=e.getAttribute("transform")||"",s=i.match(/translate\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/),a=i.match(/scale\(\s*([^,)]+)(?:\s*,\s*([^)]+))?\s*\)/);let o=s?parseFloat(s[1]):0,l=s?parseFloat(s[2]):0;const u=o+t,c=l+r;let h=`translate(${u}, ${c})`;if(a){const f=parseFloat(a[1])||1,d=a[2]?parseFloat(a[2]):f;h+=` scale(${f}, ${d})`}e.setAttribute("transform",h)}_getOMDElementBounds(e){try{const t=e.getAttribute("transform")||"";let r=0,i=0,s=1,a=1;const o=t.match(/translate\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/);o&&(r=parseFloat(o[1])||0,i=parseFloat(o[2])||0);const l=t.match(/scale\(\s*([^,)]+)(?:\s*,\s*([^)]+))?\s*\)/);l&&(s=parseFloat(l[1])||1,a=l[2]?parseFloat(l[2]):s);const u=e.firstElementChild;let c=null;if(u){const h=u.querySelectorAll("clipPath");if(h.length>0){let f=0;for(const d of h){const p=d.querySelector("rect");if(p){const m=parseFloat(p.getAttribute("width"))||0,y=parseFloat(p.getAttribute("height"))||0,v=parseFloat(p.getAttribute("x"))||0,S=parseFloat(p.getAttribute("y"))||0;if(m*y>f){f=m*y;const g=u.firstElementChild;let b=0,w=0;if(g){const x=g.getAttribute("transform");if(x){const N=x.match(/translate\(\s*([^,]+)(?:,\s*([^)]+))?\s*\)/);N&&(b=parseFloat(N[1])||0,w=parseFloat(N[2])||0)}}c={x:v+b,y:S+w,width:m,height:y}}}}}c||(c=u.getBBox())}else c=e.getBBox();return{x:r+c.x*s,y:i+c.y*a,width:c.width*s,height:c.height*a}}catch{return null}}_findSegmentAtPoint(e,t){let r=null,i=u9;for(const[s,a]of this.canvas.strokes)if(!(!a.points||a.points.length<2))for(let o=0;o<a.points.length-1;o++){const l=a.points[o],u=a.points[o+1],c=this._pointToSegmentDistance(e,t,l,u);c<i&&(i=c,r={strokeId:s,segmentIndex:o})}return r}_findOMDElementAtPoint(e,t){var s,a;const r=(s=this.canvas.drawingLayer)==null?void 0:s.querySelector(".omd-layer");if(!r)return null;const i=r.querySelectorAll(".omd-item");for(const o of i)if(((a=o==null?void 0:o.dataset)==null?void 0:a.locked)!=="true")try{const l=this._getOMDElementBounds(o);if(!l)continue;const u=10;if(e>=l.x-u&&e<=l.x+l.width+u&&t>=l.y-u&&t<=l.y+l.height+u)return o}catch{continue}return null}_pointToSegmentDistance(e,t,r,i){const s=(i.x-r.x)**2+(i.y-r.y)**2;if(s===0)return Math.hypot(e-r.x,t-r.y);let a=((e-r.x)*(i.x-r.x)+(t-r.y)*(i.y-r.y))/s;a=Math.max(0,Math.min(1,a));const o=r.x+a*(i.x-r.x),l=r.y+a*(i.y-r.y);return Math.hypot(e-o,t-l)}_createSelectionBox(e,t){this.selectionBox=document.createElementNS("http://www.w3.org/2000/svg","rect"),this.selectionBox.setAttribute("x",e),this.selectionBox.setAttribute("y",t),this.selectionBox.setAttribute("width",0),this.selectionBox.setAttribute("height",0),this.selectionBox.setAttribute("fill","rgba(0, 123, 255, 0.2)"),this.selectionBox.setAttribute("stroke","#007bff"),this.selectionBox.setAttribute("stroke-width","1"),this.selectionBox.setAttribute("stroke-dasharray","4,2"),this.selectionBox.style.pointerEvents="none",this.selectionBox.setAttribute("data-selection-box","true"),this.canvas.uiLayer?this.canvas.uiLayer.appendChild(this.selectionBox):this.canvas.svg?this.canvas.svg.appendChild(this.selectionBox):console.error("No canvas layer found to add selection box!")}_updateSelectionBox(e,t){if(!this.selectionBox||!this.startPoint)return;const r=Math.min(this.startPoint.x,e),i=Math.min(this.startPoint.y,t),s=Math.abs(this.startPoint.x-e),a=Math.abs(this.startPoint.y-t);this.selectionBox.setAttribute("x",r),this.selectionBox.setAttribute("y",i),this.selectionBox.setAttribute("width",s),this.selectionBox.setAttribute("height",a)}_removeSelectionBox(){this.selectionBox&&(this.selectionBox.remove(),this.selectionBox=null),this.startPoint=null}_updateBoxSelection(){var o,l;if(!this.selectionBox)return;const e=parseFloat(this.selectionBox.getAttribute("x")),t=parseFloat(this.selectionBox.getAttribute("y")),r=parseFloat(this.selectionBox.getAttribute("width")),i=parseFloat(this.selectionBox.getAttribute("height")),s=new Di(e,t,r,i);for(const[u,c]of this.canvas.strokes)if(!(!c.points||c.points.length<2))for(let h=0;h<c.points.length-1;h++){const f=c.points[h],d=c.points[h+1];this._segmentIntersectsBox(f,d,s)&&(this.selectedSegments.has(u)||this.selectedSegments.set(u,new Set),this.selectedSegments.get(u).add(h))}const a=(o=this.canvas.drawingLayer)==null?void 0:o.querySelector(".omd-layer");if(a){const u=a.querySelectorAll(".omd-item");for(const c of u){if(((l=c==null?void 0:c.dataset)==null?void 0:l.locked)==="true")continue;const h=this._getOMDElementBounds(c);h&&!(h.x>e+r||h.x+h.width<e||h.y>t+i||h.y+h.height<t)&&this.selectedOMDElements.add(c)}}this.resizeHandleManager.clearSelection(),this._updateSegmentSelectionVisuals()}_segmentIntersectsBox(e,t,r){if(r.containsPoint(e.x,e.y)||r.containsPoint(t.x,t.y))return!0;const{x:i,y:s,width:a,height:o}=r,l=i+a,u=s+o,c=[{a:{x:i,y:s},b:{x:l,y:s}},{a:{x:l,y:s},b:{x:l,y:u}},{a:{x:l,y:u},b:{x:i,y:u}},{a:{x:i,y:u},b:{x:i,y:s}}];for(const h of c)if(this._lineIntersectsLine(e,t,h.a,h.b))return!0;return!1}_lineIntersectsLine(e,t,r,i){const s=(t.x-e.x)*(i.y-r.y)-(t.y-e.y)*(i.x-r.x);if(s===0)return!1;const a=((r.x-e.x)*(i.y-r.y)-(r.y-e.y)*(i.x-r.x))/s,o=-((t.x-e.x)*(r.y-e.y)-(t.y-e.y)*(r.x-e.x))/s;return a>=0&&a<=1&&o>=0&&o<=1}_updateSegmentSelectionVisuals(){var i;const e=this.canvas.uiLayer.querySelector(".segment-selection-layer")||this._createSelectionLayer();for(;e.firstChild;)e.removeChild(e.firstChild);if(this.selectedSegments.size===0&&this.selectedOMDElements.size>0&&((i=this.resizeHandleManager)==null?void 0:i.selectedElement)!==null)return;const t=this._getSelectionBounds();if(!t)return;const r=document.createElementNS("http://www.w3.org/2000/svg","rect");r.setAttribute("x",t.x),r.setAttribute("y",t.y),r.setAttribute("width",t.width),r.setAttribute("height",t.height),r.setAttribute("fill","none"),r.setAttribute("stroke","#007bff"),r.setAttribute("stroke-width","1.5"),r.setAttribute("stroke-dasharray","6, 4"),r.setAttribute("stroke-opacity","0.6"),r.setAttribute("rx","8"),r.setAttribute("ry","8"),r.style.pointerEvents="none",r.classList.add("selection-bounds"),e.appendChild(r)}_createSelectionLayer(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");return e.classList.add("segment-selection-layer"),this.canvas.uiLayer.appendChild(e),e}_selectAllSegments(){var t,r;this.selectedSegments.clear(),this.selectedOMDElements.clear();for(const[i,s]of this.canvas.strokes){if(!s.points||s.points.length<2)continue;const a=new Set;for(let o=0;o<s.points.length-1;o++)a.add(o);a.size>0&&this.selectedSegments.set(i,a)}const e=(t=this.canvas.drawingLayer)==null?void 0:t.querySelector(".omd-layer");if(e){const i=e.querySelectorAll(".omd-item");for(const s of i)((r=s==null?void 0:s.dataset)==null?void 0:r.locked)!=="true"&&this.selectedOMDElements.add(s)}this._updateSegmentSelectionVisuals(),this.canvas.emit("selectionChanged",{selected:this._getSelectedSegmentsAsArray()})}_deleteSelectedSegments(){let e=!1;if(this.selectedOMDElements.size>0){for(const t of this.selectedOMDElements)t.remove();this.selectedOMDElements.clear(),this.resizeHandleManager.clearSelection(),e=!0}if(this.selectedSegments.size>0){const t=Array.from(this.selectedSegments.entries());for(const[r,i]of t){const s=this.canvas.strokes.get(r);if(!s||!s.points||s.points.length<2)continue;const a=Array.from(i).sort((u,c)=>u-c),o=s.points.length-1;if(a.length>=o*.8){this.canvas.removeStroke(r);continue}this._splitStrokeKeepingUnselected(s,a)}e=!0}e&&(this.clearSelection(),this.canvas.emit("selectionDeleted"))}_splitStrokeKeepingUnselected(e,t){const r=e.points.length-1,i=[];for(let a=0;a<r;a++)t.includes(a)||i.push(a);if(i.length===0){this.canvas.removeStroke(e.id);return}const s=this._groupConsecutiveSegments(i);this.canvas.removeStroke(e.id),s.forEach(a=>{this._createStrokeFromSegments(e,a)})}_separateSelectedParts(){const e=new Map,t=Array.from(this.selectedSegments.entries());for(const[r,i]of t){const s=this.canvas.strokes.get(r);if(!s||!s.points||s.points.length<2)continue;const a=s.points.length-1;if(i.size===a){e.set(r,i);continue}const o=Array.from(i).sort((h,f)=>h-f),l=[];for(let h=0;h<a;h++)i.has(h)||l.push(h);const u=this._groupConsecutiveSegments(o),c=this._groupConsecutiveSegments(l);u.forEach(h=>{const f=this._createStrokeFromSegments(s,h);if(f){const d=new Set;for(let p=0;p<f.points.length-1;p++)d.add(p);e.set(f.id,d)}}),c.forEach(h=>{this._createStrokeFromSegments(s,h)}),this.canvas.removeStroke(r)}this.selectedSegments=e}_groupConsecutiveSegments(e){if(e.length===0)return[];const t=[];let r=[e[0]];for(let i=1;i<e.length;i++){const s=e[i],a=e[i-1];s===a+1?r.push(s):(t.push(r),r=[s])}return t.push(r),t}_createStrokeFromSegments(e,t){if(t.length===0)return null;const r=[];r.push(e.points[t[0]]);for(const s of t)r.push(e.points[s+1]);if(r.length<2)return null;const i=new gn({strokeWidth:e.strokeWidth,strokeColor:e.strokeColor,strokeOpacity:e.strokeOpacity,tool:e.tool});return r.forEach(s=>{i.addPoint(s)}),i.finish(),this.canvas.addStroke(i),i}}class fy{constructor(e){this.canvas=e,this.isVisible=!0,this.currentShape="pencil",this.size=20,this.color="#007bff",this._createElement(),this.canvas.uiLayer.appendChild(this.element)}_createElement(){this.element=document.createElementNS("http://www.w3.org/2000/svg","g"),this.element.setAttribute("class","omd-cursor"),this.element.style.pointerEvents="none",this.element.style.opacity="0.8",this._createShapes(),this.hide()}_createShapes(){this.shapes={},this.shapes.default=this._createCrosshair(),this.shapes.pointer=this._createPointerCursor(),this.shapes.pencil=this._createPencilCursor(),this.shapes.eraser=this._createEraserCursor(),this.shapes.select=this._createSelectCursor(),Object.values(this.shapes).forEach(e=>{this.element.appendChild(e)}),this.setShape("pencil")}_createCrosshair(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");e.setAttribute("data-shape","default");const t=document.createElementNS("http://www.w3.org/2000/svg","line");t.setAttribute("x1","-10"),t.setAttribute("y1","0"),t.setAttribute("x2","10"),t.setAttribute("y2","0"),t.setAttribute("stroke",this.color),t.setAttribute("stroke-width","1");const r=document.createElementNS("http://www.w3.org/2000/svg","line");return r.setAttribute("x1","0"),r.setAttribute("y1","-10"),r.setAttribute("x2","0"),r.setAttribute("y2","10"),r.setAttribute("stroke",this.color),r.setAttribute("stroke-width","1"),e.appendChild(t),e.appendChild(r),e}_createPencilCursor(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");return e.setAttribute("data-shape","pencil"),this.brushCircle=document.createElementNS("http://www.w3.org/2000/svg","circle"),this.brushCircle.setAttribute("cx","0"),this.brushCircle.setAttribute("cy","0"),this.brushCircle.setAttribute("r",this.size/2),this.brushCircle.setAttribute("fill",this.color),this.brushCircle.setAttribute("stroke","none"),e.appendChild(this.brushCircle),e}_createEraserCursor(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");e.setAttribute("data-shape","eraser");const t=document.createElementNS("http://www.w3.org/2000/svg","circle");t.setAttribute("r",this.size/2),t.setAttribute("fill","none"),t.setAttribute("stroke","#dc3545"),t.setAttribute("stroke-width","1.5"),t.setAttribute("class","eraser-circle");const r=document.createElementNS("http://www.w3.org/2000/svg","circle");r.setAttribute("r",this.size/3),r.setAttribute("fill","rgba(220, 53, 69, 0.15)"),r.setAttribute("class","eraser-mode-indicator"),r.style.display="none";const i=document.createElementNS("http://www.w3.org/2000/svg","line");i.setAttribute("x1",-this.size/5),i.setAttribute("y1",-this.size/5),i.setAttribute("x2",this.size/5),i.setAttribute("y2",this.size/5),i.setAttribute("stroke","#dc3545"),i.setAttribute("stroke-width","1.5"),i.setAttribute("class","eraser-x1");const s=document.createElementNS("http://www.w3.org/2000/svg","line");return s.setAttribute("x1",this.size/5),s.setAttribute("y1",-this.size/5),s.setAttribute("x2",-this.size/5),s.setAttribute("y2",this.size/5),s.setAttribute("stroke","#dc3545"),s.setAttribute("stroke-width","1.5"),s.setAttribute("class","eraser-x2"),e.appendChild(t),e.appendChild(r),e.appendChild(i),e.appendChild(s),e}_createSelectCursor(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");e.setAttribute("data-shape","select");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M 2,2 L 2,16 L 7,11 L 10,18 L 12,17 L 9,10 L 16,10 Z"),t.setAttribute("fill","white"),t.setAttribute("stroke","#000000"),t.setAttribute("stroke-width","1.2"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}_createPointerCursor(){const e=document.createElementNS("http://www.w3.org/2000/svg","g");e.setAttribute("data-shape","pointer");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M1.63448 2.04462C1.60922 1.98633 1.60208 1.92179 1.61397 1.85938C1.62585 1.79697 1.65623 1.73958 1.70116 1.69466C1.74608 1.64973 1.80347 1.61935 1.86588 1.60747C1.92829 1.59558 1.99283 1.60272 2.05112 1.62798L12.2911 5.78798C12.3534 5.81335 12.4061 5.85768 12.4417 5.91469C12.4774 5.9717 12.4941 6.03849 12.4897 6.10557C12.4852 6.17266 12.4597 6.23663 12.4169 6.28842C12.374 6.3402 12.3159 6.37717 12.2508 6.39406L8.33144 7.40526C8.11 7.46219 7.90784 7.5774 7.74599 7.73891C7.58415 7.90042 7.46852 8.10234 7.41112 8.32366L6.40056 12.2443C6.38367 12.3094 6.3467 12.3675 6.29492 12.4104C6.24313 12.4532 6.17916 12.4787 6.11207 12.4832C6.04499 12.4876 5.9782 12.4709 5.92119 12.4352C5.86419 12.3996 5.81985 12.3469 5.79448 12.2846L1.63448 2.04462Z"),t.setAttribute("fill","white"),t.setAttribute("stroke","#000000"),t.setAttribute("stroke-width","1.28"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}setShape(e){this.currentShape=e,Object.values(this.shapes).forEach(t=>{t.style.display="none"}),this.shapes[e]?this.shapes[e].style.display="block":this.shapes.default.style.display="block",e==="pencil"&&this.brushCircle&&this._updateBrushSize()}setPosition(e,t){this.element.setAttribute("transform",`translate(${e}, ${t})`)}show(){this.isVisible=!0,this.element.style.display="block"}hide(){this.isVisible=!1,this.element.style.display="none"}setSize(e){this.size=e,this._updateBrushSize()}_updateBrushSize(){this.brushCircle&&this.brushCircle.setAttribute("r",this.size/2);const e=this.shapes.eraser;if(e){const t=e.querySelector(".eraser-circle"),r=e.querySelector(".eraser-mode-indicator"),i=e.querySelector(".eraser-x1"),s=e.querySelector(".eraser-x2");t&&t.setAttribute("r",this.size/2),r&&r.setAttribute("r",this.size/3),i&&(i.setAttribute("x1",-this.size/5),i.setAttribute("y1",-this.size/5),i.setAttribute("x2",this.size/5),i.setAttribute("y2",this.size/5)),s&&(s.setAttribute("x1",this.size/5),s.setAttribute("y1",-this.size/5),s.setAttribute("x2",-this.size/5),s.setAttribute("y2",this.size/5))}}setColor(e){this.color=e,this.element.querySelectorAll("[stroke]").forEach(t=>{t.getAttribute("stroke")===this.color&&t.setAttribute("stroke",e)}),this.element.querySelectorAll("[fill]").forEach(t=>{t.getAttribute("fill")===this.color&&t.setAttribute("fill",e)})}setOpacity(e){this.element.style.opacity=e}setPressureFeedback(e){if(this.currentShape==="pencil"&&this.brushCircle){const t=.5+e*.5;this.brushCircle.setAttribute("transform",`scale(${t})`);const r=.3+e*.5;this.brushCircle.style.opacity=r}}showFeedback(e,t=500){const r={success:"#28a745",error:"#dc3545",info:"#17a2b8"},i=this.color;this.setColor(r[e]||r.info),this.element.style.animation="pulse 0.3s ease-in-out",setTimeout(()=>{this.setColor(i),this.element.style.animation=""},t)}updateFromToolConfig(e){if(e.strokeWidth){const t=this.currentShape==="pencil"?e.strokeWidth*4:e.strokeWidth;this.setSize(t)}e.strokeColor&&this.setColor(e.strokeColor),e.size&&this.setSize(e.size),e.mode!==void 0&&this.currentShape==="eraser"&&this._updateEraserMode(e.mode)}_updateEraserMode(e){const t=this.shapes.eraser;if(!t)return;const r=t.querySelector(".eraser-circle"),i=t.querySelector(".eraser-mode-indicator"),s=t.querySelector(".eraser-x1"),a=t.querySelector(".eraser-x2");e==="radius"?(r&&(r.setAttribute("stroke","#ff9f43"),r.setAttribute("stroke-dasharray","3,3")),i&&(i.style.display="block",i.setAttribute("fill","rgba(255, 159, 67, 0.3)")),s&&(s.style.display="none"),a&&(a.style.display="none")):(r&&(r.setAttribute("stroke","#dc3545"),r.setAttribute("stroke-dasharray","none")),i&&(i.style.display="none"),s&&(s.style.display="block"),a&&(a.style.display="block"))}getState(){return{isVisible:this.isVisible,shape:this.currentShape,size:this.size,color:this.color}}destroy(){this.element.parentNode&&this.element.parentNode.removeChild(this.element)}attachTo(e){!e||!this.element||e.appendChild(this.element)}}class dy{constructor(e){this.canvas=e,this.buttons=new Map,this.activeButton=null,this.omdColor=Fe,this.toolbarWidth=64,this.toolbarHeight=28,this.customPosition=null,this._createElement(),this._createToolButtons(),this.canvas.on("toolChanged",t=>{this._updateActiveButton(t.detail.name)}),this.canvas.on("resized",()=>{this._updatePosition()})}_createElement(){this.toolbarGroup=new Oe,this.toolbarGroup.svgObject.style.cursor="pointer";const e=i=>i.stopPropagation(),t=i=>{var s,a;i.stopPropagation(),(a=(s=this.canvas.cursor)==null?void 0:s.hide)==null||a.call(s)},r=i=>{i.stopPropagation(),this._restoreCanvasCursor(i)};this.toolbarGroup.svgObject.addEventListener("pointerdown",e),this.toolbarGroup.svgObject.addEventListener("pointermove",e),this.toolbarGroup.svgObject.addEventListener("pointerup",e),this.toolbarGroup.svgObject.addEventListener("pointerenter",t),this.toolbarGroup.svgObject.addEventListener("pointerleave",r),this.toolbarGroup.svgObject.addEventListener("pointercancel",r),this.background=new yt,this._setToolbarSize(this.toolbarWidth,this.toolbarHeight),this.background.setFillColor(this.omdColor.mediumGray),this.toolbarGroup.addChild(this.background),this._updatePosition(),this.canvas.svg.appendChild(this.toolbarGroup.svgObject)}_updatePosition(){const e=this.canvas.container.getBoundingClientRect(),t=this.toolbarWidth,r=this.toolbarHeight,i=(e.width-t)/2,s=e.height-r-24;this._applyPosition(i,s),this.toolbarGroup.svgObject.style.zIndex="1000",this.toolbarGroup.svgObject.style.pointerEvents="auto",this._updateViewBox(i,s)}_createToolButtons(){const e=this.canvas.toolManager.getAllToolMetadata(),t=24,r=4,i=4;let s=i;const a=i;e.forEach(c=>{const h=this._createJsvgButton(c,t);h.setPosition(s,a),this.toolbarGroup.addChild(h),this.buttons.set(c.name,h),s+=t+r});const o=s-r+i,l=t+2*i;this._setToolbarSize(o,l),this._updatePosition();const u=this.canvas.toolManager.getActiveTool();u&&this._updateActiveButton(u.name)}_createJsvgButton(e,t=48){const r=new Xn;r.setWidthAndHeight(t,t),r.setCornerRadius(t/2),r.setFillColor(this.omdColor.lightGray),r.setText("");const i=this._getToolIconSvg(e.name);if(i){const s="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(i);r.addImage(s,t*.5,t*.5)}return r.setClickCallback(()=>{this.canvas.toolManager.setActiveTool(e.name)}),r.toolMeta=e,r}_getToolIconSvg(e){const t={pointer:`<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">